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);
69 // save a copy of the opened output descriptors before any output is opened or closed
70 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
71 mPreviousOutputs = mOutputs;
74 // handle output device connection
75 case AudioSystem::DEVICE_STATE_AVAILABLE:
76 if (mAvailableOutputDevices & device) {
77 ALOGW("setDeviceConnectionState() device already connected: %x", device);
78 return INVALID_OPERATION;
80 ALOGV("setDeviceConnectionState() connecting device %x", device);
82 if (checkOutputsForDevice((audio_devices_t)device, state, outputs) != NO_ERROR) {
83 return INVALID_OPERATION;
85 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
87 // register new device as available
88 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
90 if (!outputs.isEmpty()) {
92 if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
93 // handle A2DP device connection
95 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
96 paramStr = param.toString();
97 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
98 mA2dpSuspended = false;
99 } else if (AudioSystem::isBluetoothScoDevice(device)) {
100 // handle SCO device connection
101 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
102 } else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
103 // handle USB device connection
104 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
105 paramStr = mUsbCardAndDevice;
107 if (!paramStr.isEmpty()) {
108 for (size_t i = 0; i < outputs.size(); i++) {
109 mpClientInterface->setParameters(outputs[i], paramStr);
114 // handle output device disconnection
115 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
116 if (!(mAvailableOutputDevices & device)) {
117 ALOGW("setDeviceConnectionState() device not connected: %x", device);
118 return INVALID_OPERATION;
121 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
122 // remove device from available output devices
123 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
125 checkOutputsForDevice((audio_devices_t)device, state, outputs);
126 if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
127 // handle A2DP device disconnection
128 mA2dpDeviceAddress = "";
129 mA2dpSuspended = false;
130 } else if (AudioSystem::isBluetoothScoDevice(device)) {
131 // handle SCO device disconnection
132 mScoDeviceAddress = "";
133 } else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
134 // handle USB device disconnection
135 mUsbCardAndDevice = "";
140 ALOGE("setDeviceConnectionState() invalid state: %x", state);
145 checkOutputForAllStrategies();
146 // outputs must be closed after checkOutputForAllStrategies() is executed
147 if (!outputs.isEmpty()) {
148 for (size_t i = 0; i < outputs.size(); i++) {
149 // close unused outputs after device disconnection or direct outputs that have been
150 // opened by checkOutputsForDevice() to query dynamic parameters
151 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
152 (mOutputs.valueFor(outputs[i])->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
153 closeOutput(outputs[i]);
158 updateDevicesAndOutputs();
159 for (size_t i = 0; i < mOutputs.size(); i++) {
160 setOutputDevice(mOutputs.keyAt(i), getNewDevice(mOutputs.keyAt(i), true /*fromCache*/));
163 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
164 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
165 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
166 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
167 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
168 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
173 // handle input devices
174 if (AudioSystem::isInputDevice(device)) {
178 // handle input device connection
179 case AudioSystem::DEVICE_STATE_AVAILABLE: {
180 if (mAvailableInputDevices & device) {
181 ALOGW("setDeviceConnectionState() device already connected: %d", device);
182 return INVALID_OPERATION;
184 mAvailableInputDevices = (audio_devices_t)(mAvailableInputDevices | device);
188 // handle input device disconnection
189 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
190 if (!(mAvailableInputDevices & device)) {
191 ALOGW("setDeviceConnectionState() device not connected: %d", device);
192 return INVALID_OPERATION;
194 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
198 ALOGE("setDeviceConnectionState() invalid state: %x", state);
202 audio_io_handle_t activeInput = getActiveInput();
203 if (activeInput != 0) {
204 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
205 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
206 if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
207 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
208 inputDesc->mDevice, newDevice, activeInput);
209 inputDesc->mDevice = newDevice;
210 AudioParameter param = AudioParameter();
211 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
212 mpClientInterface->setParameters(activeInput, param.toString());
219 ALOGW("setDeviceConnectionState() invalid device: %x", device);
223 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
224 const char *device_address)
226 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
227 String8 address = String8(device_address);
228 if (AudioSystem::isOutputDevice(device)) {
229 if (device & mAvailableOutputDevices) {
230 if (AudioSystem::isA2dpDevice(device) &&
231 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
234 if (AudioSystem::isBluetoothScoDevice(device) &&
235 address != "" && mScoDeviceAddress != address) {
238 if (audio_is_usb_device((audio_devices_t)device) &&
239 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
240 ALOGE("setDeviceConnectionState() invalid device: %x", device);
243 state = AudioSystem::DEVICE_STATE_AVAILABLE;
245 } else if (AudioSystem::isInputDevice(device)) {
246 if (device & mAvailableInputDevices) {
247 state = AudioSystem::DEVICE_STATE_AVAILABLE;
254 void AudioPolicyManagerBase::setPhoneState(int state)
256 ALOGV("setPhoneState() state %d", state);
257 audio_devices_t newDevice = (audio_devices_t)0;
258 if (state < 0 || state >= AudioSystem::NUM_MODES) {
259 ALOGW("setPhoneState() invalid state %d", state);
263 if (state == mPhoneState ) {
264 ALOGW("setPhoneState() setting same state %d", state);
268 // if leaving call state, handle special case of active streams
269 // pertaining to sonification strategy see handleIncallSonification()
271 ALOGV("setPhoneState() in call state management: new state is %d", state);
272 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
273 handleIncallSonification(stream, false, true);
277 // store previous phone state for management of sonification strategy below
278 int oldState = mPhoneState;
282 // are we entering or starting a call
283 if (!isStateInCall(oldState) && isStateInCall(state)) {
284 ALOGV(" Entering call in setPhoneState()");
285 // force routing command to audio hardware when starting a call
286 // even if no device change is needed
288 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
289 ALOGV(" Exiting call in setPhoneState()");
290 // force routing command to audio hardware when exiting a call
291 // even if no device change is needed
293 } else if (isStateInCall(state) && (state != oldState)) {
294 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
295 // force routing command to audio hardware when switching between telephony and VoIP
296 // even if no device change is needed
300 // check for device and output changes triggered by new phone state
301 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
303 checkOutputForAllStrategies();
304 updateDevicesAndOutputs();
306 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
308 // force routing command to audio hardware when ending call
309 // even if no device change is needed
310 if (isStateInCall(oldState) && newDevice == 0) {
311 newDevice = hwOutputDesc->device();
314 // when changing from ring tone to in call mode, mute the ringing tone
315 // immediately and delay the route change to avoid sending the ring tone
316 // tail into the earpiece or headset.
318 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
319 // delay the device change command by twice the output latency to have some margin
320 // and be sure that audio buffers not yet affected by the mute are out when
321 // we actually apply the route change
322 delayMs = hwOutputDesc->mLatency*2;
323 setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
326 // change routing is necessary
327 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
329 // if entering in call state, handle special case of active streams
330 // pertaining to sonification strategy see handleIncallSonification()
331 if (isStateInCall(state)) {
332 ALOGV("setPhoneState() in call state management: new state is %d", state);
333 // unmute the ringing tone after a sufficient delay if it was muted before
334 // setting output device above
335 if (oldState == AudioSystem::MODE_RINGTONE) {
336 setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
338 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
339 handleIncallSonification(stream, true, true);
343 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
344 if (state == AudioSystem::MODE_RINGTONE &&
345 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
346 mLimitRingtoneVolume = true;
348 mLimitRingtoneVolume = false;
352 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
354 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
356 bool forceVolumeReeval = false;
358 case AudioSystem::FOR_COMMUNICATION:
359 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
360 config != AudioSystem::FORCE_NONE) {
361 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
364 forceVolumeReeval = true;
365 mForceUse[usage] = config;
367 case AudioSystem::FOR_MEDIA:
368 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
369 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
370 config != AudioSystem::FORCE_ANALOG_DOCK &&
371 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
372 config != AudioSystem::FORCE_NO_BT_A2DP) {
373 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
376 mForceUse[usage] = config;
378 case AudioSystem::FOR_RECORD:
379 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
380 config != AudioSystem::FORCE_NONE) {
381 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
384 mForceUse[usage] = config;
386 case AudioSystem::FOR_DOCK:
387 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
388 config != AudioSystem::FORCE_BT_DESK_DOCK &&
389 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
390 config != AudioSystem::FORCE_ANALOG_DOCK &&
391 config != AudioSystem::FORCE_DIGITAL_DOCK) {
392 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
394 forceVolumeReeval = true;
395 mForceUse[usage] = config;
398 ALOGW("setForceUse() invalid usage %d", usage);
402 // check for device and output changes triggered by new force usage
404 checkOutputForAllStrategies();
405 updateDevicesAndOutputs();
406 for (size_t i = 0; i < mOutputs.size(); i++) {
407 audio_io_handle_t output = mOutputs.keyAt(i);
408 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
409 setOutputDevice(output, newDevice, (newDevice != 0));
410 if (forceVolumeReeval && (newDevice != 0)) {
411 applyStreamVolumes(output, newDevice, 0, true);
415 audio_io_handle_t activeInput = getActiveInput();
416 if (activeInput != 0) {
417 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
418 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
419 if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
420 ALOGV("setForceUse() changing device from %x to %x for input %d",
421 inputDesc->mDevice, newDevice, activeInput);
422 inputDesc->mDevice = newDevice;
423 AudioParameter param = AudioParameter();
424 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
425 mpClientInterface->setParameters(activeInput, param.toString());
431 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
433 return mForceUse[usage];
436 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
438 ALOGV("setSystemProperty() property %s, value %s", property, value);
439 if (strcmp(property, "ro.camera.sound.forced") == 0) {
441 ALOGV("ENFORCED_AUDIBLE cannot be muted");
442 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
444 ALOGV("ENFORCED_AUDIBLE can be muted");
445 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
450 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
451 audio_devices_t device,
452 uint32_t samplingRate,
454 uint32_t channelMask,
455 audio_output_flags_t flags)
457 for (size_t i = 0; i < mHwModules.size(); i++) {
458 if (mHwModules[i]->mHandle == 0) {
461 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
462 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
463 if (profile->isCompatibleProfile(device, samplingRate, format,
465 AUDIO_OUTPUT_FLAG_DIRECT)) {
466 if (mAvailableOutputDevices & profile->mSupportedDevices) {
467 return mHwModules[i]->mOutputProfiles[j];
475 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
476 uint32_t samplingRate,
478 uint32_t channelMask,
479 AudioSystem::output_flags flags)
481 audio_io_handle_t output = 0;
482 uint32_t latency = 0;
483 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
484 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
485 ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
486 stream, samplingRate, format, channelMask, flags);
488 #ifdef AUDIO_POLICY_TEST
489 if (mCurOutput != 0) {
490 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
491 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
493 if (mTestOutputs[mCurOutput] == 0) {
494 ALOGV("getOutput() opening test output");
495 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
496 outputDesc->mDevice = mTestDevice;
497 outputDesc->mSamplingRate = mTestSamplingRate;
498 outputDesc->mFormat = mTestFormat;
499 outputDesc->mChannelMask = mTestChannels;
500 outputDesc->mLatency = mTestLatencyMs;
501 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
502 outputDesc->mRefCount[stream] = 0;
503 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
504 &outputDesc->mSamplingRate,
505 &outputDesc->mFormat,
506 &outputDesc->mChannelMask,
507 &outputDesc->mLatency,
509 if (mTestOutputs[mCurOutput]) {
510 AudioParameter outputCmd = AudioParameter();
511 outputCmd.addInt(String8("set_id"),mCurOutput);
512 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
513 addOutput(mTestOutputs[mCurOutput], outputDesc);
516 return mTestOutputs[mCurOutput];
518 #endif //AUDIO_POLICY_TEST
520 // open a direct output if required by specified parameters
521 IOProfile *profile = getProfileForDirectOutput(device,
525 (audio_output_flags_t)flags);
526 if (profile != NULL) {
528 ALOGV("getOutput() opening direct output device %x", device);
530 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(profile);
531 outputDesc->mDevice = device;
532 outputDesc->mSamplingRate = samplingRate;
533 outputDesc->mFormat = (audio_format_t)format;
534 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
535 outputDesc->mLatency = 0;
536 outputDesc->mFlags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);;
537 outputDesc->mRefCount[stream] = 0;
538 outputDesc->mStopTime[stream] = 0;
539 output = mpClientInterface->openOutput(profile->mModule->mHandle,
540 &outputDesc->mDevice,
541 &outputDesc->mSamplingRate,
542 &outputDesc->mFormat,
543 &outputDesc->mChannelMask,
544 &outputDesc->mLatency,
547 // only accept an output with the requested parameters
549 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
550 (format != 0 && format != outputDesc->mFormat) ||
551 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
552 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
553 "format %d %d, channelMask %04x %04x", output, samplingRate,
554 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
555 outputDesc->mChannelMask);
557 mpClientInterface->closeOutput(output);
562 addOutput(output, outputDesc);
563 ALOGV("getOutput() returns direct output %d", output);
567 // ignoring channel mask due to downmix capability in mixer
569 // open a non direct output
571 // get which output is suitable for the specified stream. The actual routing change will happen
572 // when startOutput() will be called
573 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
575 output = selectOutput(outputs, flags);
577 ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
578 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
580 ALOGV("getOutput() returns output %d", output);
585 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
586 AudioSystem::output_flags flags)
588 // select one output among several that provide a path to a particular device or set of
589 // devices (the list was previously build by getOutputsForDevice()).
590 // The priority is as follows:
591 // 1: the output with the highest number of requested policy flags
592 // 2: the primary output
593 // 3: the first output in the list
595 if (outputs.size() == 0) {
598 if (outputs.size() == 1) {
602 int maxCommonFlags = 0;
603 audio_io_handle_t outputFlags = 0;
604 audio_io_handle_t outputPrimary = 0;
606 for (size_t i = 0; i < outputs.size(); i++) {
607 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
608 if (!outputDesc->isDuplicated()) {
609 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
610 if (commonFlags > maxCommonFlags) {
611 outputFlags = outputs[i];
612 maxCommonFlags = commonFlags;
613 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
615 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
616 outputPrimary = outputs[i];
621 if (outputFlags != 0) {
624 if (outputPrimary != 0) {
625 return outputPrimary;
631 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
632 AudioSystem::stream_type stream,
635 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
636 ssize_t index = mOutputs.indexOfKey(output);
638 ALOGW("startOutput() unknow output %d", output);
642 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
644 // increment usage count for this stream on the requested output:
645 // NOTE that the usage count is the same for duplicated output and hardware output which is
646 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
647 outputDesc->changeRefCount(stream, 1);
649 if (outputDesc->mRefCount[stream] == 1) {
650 audio_devices_t prevDevice = outputDesc->device();
651 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
652 routing_strategy strategy = getStrategy(stream);
653 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
654 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
657 for (size_t i = 0; i < mOutputs.size(); i++) {
658 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
659 if (desc != outputDesc) {
660 // force a device change if any other output is managed by the same hw
661 // module and has a current device selection that differs from selected device.
662 // In this case, the audio HAL must receive the new device selection so that it can
663 // change the device currently selected by the other active output.
664 if (outputDesc->sharesHwModuleWith(desc) &&
665 desc->device() != newDevice) {
668 // wait for audio on other active outputs to be presented when starting
669 // a notification so that audio focus effect can propagate.
670 if (shouldWait && (desc->refCount() != 0) && (waitMs < desc->latency())) {
671 waitMs = desc->latency();
675 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
677 // handle special case for sonification while in call
679 handleIncallSonification(stream, true, false);
682 // apply volume rules for current stream and device if necessary
683 checkAndSetVolume(stream,
684 mStreams[stream].getVolumeIndex((audio_devices_t)newDevice),
688 // update the outputs if starting an output with a stream that can affect notification
690 handleNotificationRoutingForStream(stream);
691 if (waitMs > muteWaitMs) {
692 usleep((waitMs - muteWaitMs) * 2 * 1000);
699 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
700 AudioSystem::stream_type stream,
703 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
704 ssize_t index = mOutputs.indexOfKey(output);
706 ALOGW("stopOutput() unknow output %d", output);
710 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
712 // handle special case for sonification while in call
714 handleIncallSonification(stream, false, false);
717 if (outputDesc->mRefCount[stream] > 0) {
718 // decrement usage count of this stream on the output
719 outputDesc->changeRefCount(stream, -1);
720 // store time at which the stream was stopped - see isStreamActive()
721 if (outputDesc->mRefCount[stream] == 0) {
722 outputDesc->mStopTime[stream] = systemTime();
723 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
724 // delay the device switch by twice the latency because stopOutput() is executed when
725 // the track stop() command is received and at that time the audio track buffer can
726 // still contain data that needs to be drained. The latency only covers the audio HAL
727 // and kernel buffers. Also the latency does not always include additional delay in the
728 // audio path (audio DSP, CODEC ...)
729 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
731 // force restoring the device selection on other active outputs if it differs from the
732 // one being selected for this output
733 for (size_t i = 0; i < mOutputs.size(); i++) {
734 audio_io_handle_t curOutput = mOutputs.keyAt(i);
735 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
736 if (curOutput != output &&
737 desc->refCount() != 0 &&
738 outputDesc->sharesHwModuleWith(desc) &&
739 newDevice != desc->device()) {
740 setOutputDevice(curOutput,
741 getNewDevice(curOutput, false /*fromCache*/),
743 outputDesc->mLatency*2);
746 // update the outputs if stopping one with a stream that can affect notification routing
747 handleNotificationRoutingForStream(stream);
751 ALOGW("stopOutput() refcount is already 0 for output %d", output);
752 return INVALID_OPERATION;
756 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
758 ALOGV("releaseOutput() %d", output);
759 ssize_t index = mOutputs.indexOfKey(output);
761 ALOGW("releaseOutput() releasing unknown output %d", output);
765 #ifdef AUDIO_POLICY_TEST
766 int testIndex = testOutputIndex(output);
767 if (testIndex != 0) {
768 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
769 if (outputDesc->refCount() == 0) {
770 mpClientInterface->closeOutput(output);
771 delete mOutputs.valueAt(index);
772 mOutputs.removeItem(output);
773 mTestOutputs[testIndex] = 0;
777 #endif //AUDIO_POLICY_TEST
779 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
780 mpClientInterface->closeOutput(output);
781 delete mOutputs.valueAt(index);
782 mOutputs.removeItem(output);
787 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
788 uint32_t samplingRate,
790 uint32_t channelMask,
791 AudioSystem::audio_in_acoustics acoustics)
793 audio_io_handle_t input = 0;
794 audio_devices_t device = getDeviceForInputSource(inputSource);
796 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
797 inputSource, samplingRate, format, channelMask, acoustics);
800 ALOGW("getInput() could not find device for inputSource %d", inputSource);
804 // adapt channel selection to input source
805 switch(inputSource) {
806 case AUDIO_SOURCE_VOICE_UPLINK:
807 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
809 case AUDIO_SOURCE_VOICE_DOWNLINK:
810 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
812 case AUDIO_SOURCE_VOICE_CALL:
813 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
819 IOProfile *profile = getInputProfile(device,
823 if (profile == NULL) {
824 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
826 device, samplingRate, format, channelMask);
830 if (profile->mModule->mHandle == 0) {
831 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
835 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
837 inputDesc->mInputSource = inputSource;
838 inputDesc->mDevice = device;
839 inputDesc->mSamplingRate = samplingRate;
840 inputDesc->mFormat = (audio_format_t)format;
841 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
842 inputDesc->mRefCount = 0;
843 input = mpClientInterface->openInput(profile->mModule->mHandle,
845 &inputDesc->mSamplingRate,
847 &inputDesc->mChannelMask);
849 // only accept input with the exact requested set of parameters
851 (samplingRate != inputDesc->mSamplingRate) ||
852 (format != inputDesc->mFormat) ||
853 (channelMask != inputDesc->mChannelMask)) {
854 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
855 samplingRate, format, channelMask);
857 mpClientInterface->closeInput(input);
862 mInputs.add(input, inputDesc);
866 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
868 ALOGV("startInput() input %d", input);
869 ssize_t index = mInputs.indexOfKey(input);
871 ALOGW("startInput() unknow input %d", input);
874 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
876 #ifdef AUDIO_POLICY_TEST
878 #endif //AUDIO_POLICY_TEST
880 // refuse 2 active AudioRecord clients at the same time
881 if (getActiveInput() != 0) {
882 ALOGW("startInput() input %d failed: other input already started", input);
883 return INVALID_OPERATION;
887 AudioParameter param = AudioParameter();
888 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
890 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
891 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
893 mpClientInterface->setParameters(input, param.toString());
895 inputDesc->mRefCount = 1;
899 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
901 ALOGV("stopInput() input %d", input);
902 ssize_t index = mInputs.indexOfKey(input);
904 ALOGW("stopInput() unknow input %d", input);
907 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
909 if (inputDesc->mRefCount == 0) {
910 ALOGW("stopInput() input %d already stopped", input);
911 return INVALID_OPERATION;
913 AudioParameter param = AudioParameter();
914 param.addInt(String8(AudioParameter::keyRouting), 0);
915 mpClientInterface->setParameters(input, param.toString());
916 inputDesc->mRefCount = 0;
921 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
923 ALOGV("releaseInput() %d", input);
924 ssize_t index = mInputs.indexOfKey(input);
926 ALOGW("releaseInput() releasing unknown input %d", input);
929 mpClientInterface->closeInput(input);
930 delete mInputs.valueAt(index);
931 mInputs.removeItem(input);
932 ALOGV("releaseInput() exit");
935 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
939 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
940 if (indexMin < 0 || indexMin >= indexMax) {
941 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
944 mStreams[stream].mIndexMin = indexMin;
945 mStreams[stream].mIndexMax = indexMax;
948 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
950 audio_devices_t device)
953 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
956 if (!audio_is_output_device(device)) {
960 // Force max volume if stream cannot be muted
961 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
963 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
964 stream, device, index);
966 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
967 // clear all device specific values
968 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
969 mStreams[stream].mIndexCur.clear();
971 mStreams[stream].mIndexCur.add(device, index);
973 // compute and apply stream volume on all outputs according to connected device
974 status_t status = NO_ERROR;
975 for (size_t i = 0; i < mOutputs.size(); i++) {
976 audio_devices_t curDevice =
977 getDeviceForVolume((audio_devices_t)mOutputs.valueAt(i)->device());
978 if (device == curDevice) {
979 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
980 if (volStatus != NO_ERROR) {
988 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
990 audio_devices_t device)
995 if (!audio_is_output_device(device)) {
998 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
999 // the strategy the stream belongs to.
1000 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1001 device = (audio_devices_t)getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1003 device = getDeviceForVolume(device);
1005 *index = mStreams[stream].getVolumeIndex(device);
1006 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1010 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
1012 ALOGV("getOutputForEffect()");
1013 // apply simple rule where global effects are attached to the same output as MUSIC streams
1015 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1016 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1017 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1019 for (size_t i = 0; i < dstOutputs.size(); i++) {
1020 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1021 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1025 return dstOutputs[outIdx];
1028 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
1029 audio_io_handle_t io,
1034 ssize_t index = mOutputs.indexOfKey(io);
1036 index = mInputs.indexOfKey(io);
1038 ALOGW("registerEffect() unknown io %d", io);
1039 return INVALID_OPERATION;
1043 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1044 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1045 desc->name, desc->memoryUsage);
1046 return INVALID_OPERATION;
1048 mTotalEffectsMemory += desc->memoryUsage;
1049 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1050 desc->name, io, strategy, session, id);
1051 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1053 EffectDescriptor *pDesc = new EffectDescriptor();
1054 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1056 pDesc->mStrategy = (routing_strategy)strategy;
1057 pDesc->mSession = session;
1058 pDesc->mEnabled = false;
1060 mEffects.add(id, pDesc);
1065 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1067 ssize_t index = mEffects.indexOfKey(id);
1069 ALOGW("unregisterEffect() unknown effect ID %d", id);
1070 return INVALID_OPERATION;
1073 EffectDescriptor *pDesc = mEffects.valueAt(index);
1075 setEffectEnabled(pDesc, false);
1077 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1078 ALOGW("unregisterEffect() memory %d too big for total %d",
1079 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1080 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1082 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1083 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1084 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1086 mEffects.removeItem(id);
1092 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1094 ssize_t index = mEffects.indexOfKey(id);
1096 ALOGW("unregisterEffect() unknown effect ID %d", id);
1097 return INVALID_OPERATION;
1100 return setEffectEnabled(mEffects.valueAt(index), enabled);
1103 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1105 if (enabled == pDesc->mEnabled) {
1106 ALOGV("setEffectEnabled(%s) effect already %s",
1107 enabled?"true":"false", enabled?"enabled":"disabled");
1108 return INVALID_OPERATION;
1112 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1113 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1114 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1115 return INVALID_OPERATION;
1117 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1118 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1120 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1121 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1122 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1123 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1125 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1126 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1128 pDesc->mEnabled = enabled;
1132 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1134 nsecs_t sysTime = systemTime();
1135 for (size_t i = 0; i < mOutputs.size(); i++) {
1136 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
1137 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
1145 status_t AudioPolicyManagerBase::dump(int fd)
1147 const size_t SIZE = 256;
1151 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1152 result.append(buffer);
1154 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1155 result.append(buffer);
1156 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1157 result.append(buffer);
1158 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1159 result.append(buffer);
1160 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1161 result.append(buffer);
1162 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1163 result.append(buffer);
1164 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1165 result.append(buffer);
1166 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1167 result.append(buffer);
1168 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1169 result.append(buffer);
1170 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1171 result.append(buffer);
1172 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1173 result.append(buffer);
1174 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1175 result.append(buffer);
1176 write(fd, result.string(), result.size());
1179 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1180 write(fd, buffer, strlen(buffer));
1181 for (size_t i = 0; i < mHwModules.size(); i++) {
1182 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1183 write(fd, buffer, strlen(buffer));
1184 mHwModules[i]->dump(fd);
1187 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1188 write(fd, buffer, strlen(buffer));
1189 for (size_t i = 0; i < mOutputs.size(); i++) {
1190 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1191 write(fd, buffer, strlen(buffer));
1192 mOutputs.valueAt(i)->dump(fd);
1195 snprintf(buffer, SIZE, "\nInputs dump:\n");
1196 write(fd, buffer, strlen(buffer));
1197 for (size_t i = 0; i < mInputs.size(); i++) {
1198 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1199 write(fd, buffer, strlen(buffer));
1200 mInputs.valueAt(i)->dump(fd);
1203 snprintf(buffer, SIZE, "\nStreams dump:\n");
1204 write(fd, buffer, strlen(buffer));
1205 snprintf(buffer, SIZE,
1206 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1207 write(fd, buffer, strlen(buffer));
1208 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1209 snprintf(buffer, SIZE, " %02d ", i);
1210 write(fd, buffer, strlen(buffer));
1211 mStreams[i].dump(fd);
1214 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1215 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1216 write(fd, buffer, strlen(buffer));
1218 snprintf(buffer, SIZE, "Registered effects:\n");
1219 write(fd, buffer, strlen(buffer));
1220 for (size_t i = 0; i < mEffects.size(); i++) {
1221 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1222 write(fd, buffer, strlen(buffer));
1223 mEffects.valueAt(i)->dump(fd);
1230 // ----------------------------------------------------------------------------
1231 // AudioPolicyManagerBase
1232 // ----------------------------------------------------------------------------
1234 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1236 #ifdef AUDIO_POLICY_TEST
1238 #endif //AUDIO_POLICY_TEST
1239 mPrimaryOutput((audio_io_handle_t)0),
1240 mAvailableOutputDevices((audio_devices_t)0),
1241 mPhoneState(AudioSystem::MODE_NORMAL),
1242 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1243 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1244 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false)
1246 mpClientInterface = clientInterface;
1248 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1249 mForceUse[i] = AudioSystem::FORCE_NONE;
1252 initializeVolumeCurves();
1254 mA2dpDeviceAddress = String8("");
1255 mScoDeviceAddress = String8("");
1256 mUsbCardAndDevice = String8("");
1258 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1259 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1260 ALOGE("could not load audio policy configuration file, setting defaults");
1261 defaultAudioPolicyConfig();
1265 // open all output streams needed to access attached devices
1266 for (size_t i = 0; i < mHwModules.size(); i++) {
1267 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1268 if (mHwModules[i]->mHandle == 0) {
1269 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1272 // open all output streams needed to access attached devices
1273 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1275 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1277 if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1278 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1279 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1280 outProfile->mSupportedDevices);
1281 audio_io_handle_t output = mpClientInterface->openOutput(
1282 outProfile->mModule->mHandle,
1283 &outputDesc->mDevice,
1284 &outputDesc->mSamplingRate,
1285 &outputDesc->mFormat,
1286 &outputDesc->mChannelMask,
1287 &outputDesc->mLatency,
1288 outputDesc->mFlags);
1292 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1293 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1294 if (mPrimaryOutput == 0 &&
1295 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1296 mPrimaryOutput = output;
1298 addOutput(output, outputDesc);
1299 setOutputDevice(output,
1300 (audio_devices_t)(mDefaultOutputDevice &
1301 outProfile->mSupportedDevices),
1308 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1309 "Not output found for attached devices %08x",
1310 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1312 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1314 updateDevicesAndOutputs();
1316 #ifdef AUDIO_POLICY_TEST
1317 if (mPrimaryOutput != 0) {
1318 AudioParameter outputCmd = AudioParameter();
1319 outputCmd.addInt(String8("set_id"), 0);
1320 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1322 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1323 mTestSamplingRate = 44100;
1324 mTestFormat = AudioSystem::PCM_16_BIT;
1325 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1328 mDirectOutput = false;
1329 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1330 mTestOutputs[i] = 0;
1333 const size_t SIZE = 256;
1335 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1336 run(buffer, ANDROID_PRIORITY_AUDIO);
1338 #endif //AUDIO_POLICY_TEST
1341 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1343 #ifdef AUDIO_POLICY_TEST
1345 #endif //AUDIO_POLICY_TEST
1346 for (size_t i = 0; i < mOutputs.size(); i++) {
1347 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1348 delete mOutputs.valueAt(i);
1350 for (size_t i = 0; i < mInputs.size(); i++) {
1351 mpClientInterface->closeInput(mInputs.keyAt(i));
1352 delete mInputs.valueAt(i);
1354 for (size_t i = 0; i < mHwModules.size(); i++) {
1355 delete mHwModules[i];
1359 status_t AudioPolicyManagerBase::initCheck()
1361 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1364 #ifdef AUDIO_POLICY_TEST
1365 bool AudioPolicyManagerBase::threadLoop()
1367 ALOGV("entering threadLoop()");
1368 while (!exitPending())
1374 Mutex::Autolock _l(mLock);
1375 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1377 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1378 AudioParameter param = AudioParameter(command);
1380 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1382 ALOGV("Test command %s received", command.string());
1384 if (param.get(String8("target"), target) != NO_ERROR) {
1387 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1388 param.remove(String8("test_cmd_policy_output"));
1389 mCurOutput = valueInt;
1391 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1392 param.remove(String8("test_cmd_policy_direct"));
1393 if (value == "false") {
1394 mDirectOutput = false;
1395 } else if (value == "true") {
1396 mDirectOutput = true;
1399 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1400 param.remove(String8("test_cmd_policy_input"));
1401 mTestInput = valueInt;
1404 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1405 param.remove(String8("test_cmd_policy_format"));
1406 int format = AudioSystem::INVALID_FORMAT;
1407 if (value == "PCM 16 bits") {
1408 format = AudioSystem::PCM_16_BIT;
1409 } else if (value == "PCM 8 bits") {
1410 format = AudioSystem::PCM_8_BIT;
1411 } else if (value == "Compressed MP3") {
1412 format = AudioSystem::MP3;
1414 if (format != AudioSystem::INVALID_FORMAT) {
1415 if (target == "Manager") {
1416 mTestFormat = format;
1417 } else if (mTestOutputs[mCurOutput] != 0) {
1418 AudioParameter outputParam = AudioParameter();
1419 outputParam.addInt(String8("format"), format);
1420 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1424 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1425 param.remove(String8("test_cmd_policy_channels"));
1428 if (value == "Channels Stereo") {
1429 channels = AudioSystem::CHANNEL_OUT_STEREO;
1430 } else if (value == "Channels Mono") {
1431 channels = AudioSystem::CHANNEL_OUT_MONO;
1433 if (channels != 0) {
1434 if (target == "Manager") {
1435 mTestChannels = channels;
1436 } else if (mTestOutputs[mCurOutput] != 0) {
1437 AudioParameter outputParam = AudioParameter();
1438 outputParam.addInt(String8("channels"), channels);
1439 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1443 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1444 param.remove(String8("test_cmd_policy_sampleRate"));
1445 if (valueInt >= 0 && valueInt <= 96000) {
1446 int samplingRate = valueInt;
1447 if (target == "Manager") {
1448 mTestSamplingRate = samplingRate;
1449 } else if (mTestOutputs[mCurOutput] != 0) {
1450 AudioParameter outputParam = AudioParameter();
1451 outputParam.addInt(String8("sampling_rate"), samplingRate);
1452 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1457 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1458 param.remove(String8("test_cmd_policy_reopen"));
1460 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1461 mpClientInterface->closeOutput(mPrimaryOutput);
1463 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1465 delete mOutputs.valueFor(mPrimaryOutput);
1466 mOutputs.removeItem(mPrimaryOutput);
1468 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1469 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1470 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1471 &outputDesc->mDevice,
1472 &outputDesc->mSamplingRate,
1473 &outputDesc->mFormat,
1474 &outputDesc->mChannelMask,
1475 &outputDesc->mLatency,
1476 outputDesc->mFlags);
1477 if (mPrimaryOutput == 0) {
1478 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1479 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1481 AudioParameter outputCmd = AudioParameter();
1482 outputCmd.addInt(String8("set_id"), 0);
1483 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1484 addOutput(mPrimaryOutput, outputDesc);
1489 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1495 void AudioPolicyManagerBase::exit()
1498 AutoMutex _l(mLock);
1500 mWaitWorkCV.signal();
1502 requestExitAndWait();
1505 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1507 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1508 if (output == mTestOutputs[i]) return i;
1512 #endif //AUDIO_POLICY_TEST
1516 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1518 outputDesc->mId = id;
1519 mOutputs.add(id, outputDesc);
1523 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1524 AudioSystem::device_connection_state state,
1525 SortedVector<audio_io_handle_t>& outputs)
1527 AudioOutputDescriptor *desc;
1529 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1530 // first list already open outputs that can be routed to this device
1531 for (size_t i = 0; i < mOutputs.size(); i++) {
1532 desc = mOutputs.valueAt(i);
1533 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1534 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1535 outputs.add(mOutputs.keyAt(i));
1538 // then look for output profiles that can be routed to this device
1539 SortedVector<IOProfile *> profiles;
1540 for (size_t i = 0; i < mHwModules.size(); i++)
1542 if (mHwModules[i]->mHandle == 0) {
1545 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1547 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1548 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1549 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1554 if (profiles.isEmpty() && outputs.isEmpty()) {
1555 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1559 // open outputs for matching profiles if needed. Direct outputs are also opened to
1560 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1561 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1562 IOProfile *profile = profiles[profile_index];
1564 // nothing to do if one output is already opened for this profile
1566 for (j = 0; j < outputs.size(); j++) {
1567 desc = mOutputs.valueAt(j);
1568 if (!desc->isDuplicated() && desc->mProfile == profile) {
1572 if (j != outputs.size()) {
1576 ALOGV("opening output for device %08x", device);
1577 desc = new AudioOutputDescriptor(profile);
1578 desc->mDevice = device;
1579 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1581 &desc->mSamplingRate,
1583 &desc->mChannelMask,
1587 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1590 if (profile->mSamplingRates[0] == 0) {
1591 reply = mpClientInterface->getParameters(output,
1592 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1593 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1595 value = strpbrk((char *)reply.string(), "=");
1596 if (value != NULL) {
1597 loadSamplingRates(value, profile);
1600 if (profile->mFormats[0] == 0) {
1601 reply = mpClientInterface->getParameters(output,
1602 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1603 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1605 value = strpbrk((char *)reply.string(), "=");
1606 if (value != NULL) {
1607 loadFormats(value, profile);
1610 if (profile->mChannelMasks[0] == 0) {
1611 reply = mpClientInterface->getParameters(output,
1612 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1613 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1615 value = strpbrk((char *)reply.string(), "=");
1616 if (value != NULL) {
1617 loadOutChannels(value + 1, profile);
1620 if (((profile->mSamplingRates[0] == 0) &&
1621 (profile->mSamplingRates.size() < 2)) ||
1622 ((profile->mFormats[0] == 0) &&
1623 (profile->mFormats.size() < 2)) ||
1624 ((profile->mFormats[0] == 0) &&
1625 (profile->mChannelMasks.size() < 2))) {
1626 ALOGW("checkOutputsForDevice() direct output missing param");
1629 addOutput(output, desc);
1632 audio_io_handle_t duplicatedOutput = 0;
1633 // add output descriptor
1634 addOutput(output, desc);
1635 // set initial stream volume for device
1636 applyStreamVolumes(output, device, 0, true);
1638 //TODO: configure audio effect output stage here
1640 // open a duplicating output thread for the new output and the primary output
1641 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1643 if (duplicatedOutput != 0) {
1644 // add duplicated output descriptor
1645 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1646 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1647 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1648 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1649 dupOutputDesc->mFormat = desc->mFormat;
1650 dupOutputDesc->mChannelMask = desc->mChannelMask;
1651 dupOutputDesc->mLatency = desc->mLatency;
1652 addOutput(duplicatedOutput, dupOutputDesc);
1653 applyStreamVolumes(duplicatedOutput, device, 0, true);
1655 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1656 mPrimaryOutput, output);
1657 mpClientInterface->closeOutput(output);
1658 mOutputs.removeItem(output);
1664 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1666 profiles.removeAt(profile_index);
1669 outputs.add(output);
1670 ALOGV("checkOutputsForDevice(): adding output %d", output);
1674 if (profiles.isEmpty()) {
1675 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1679 // check if one opened output is not needed any more after disconnecting one device
1680 for (size_t i = 0; i < mOutputs.size(); i++) {
1681 desc = mOutputs.valueAt(i);
1682 if (!desc->isDuplicated() &&
1683 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1684 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1685 outputs.add(mOutputs.keyAt(i));
1688 for (size_t i = 0; i < mHwModules.size(); i++)
1690 if (mHwModules[i]->mHandle == 0) {
1693 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1695 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1696 if ((profile->mSupportedDevices & device) &&
1697 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1698 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1700 if (profile->mSamplingRates[0] == 0) {
1701 profile->mSamplingRates.clear();
1702 profile->mSamplingRates.add(0);
1704 if (profile->mFormats[0] == 0) {
1705 profile->mFormats.clear();
1706 profile->mFormats.add((audio_format_t)0);
1708 if (profile->mChannelMasks[0] == 0) {
1709 profile->mChannelMasks.clear();
1710 profile->mChannelMasks.add((audio_channel_mask_t)0);
1719 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1721 ALOGV("closeOutput(%d)", output);
1723 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1724 if (outputDesc == NULL) {
1725 ALOGW("closeOutput() unknown output %d", output);
1729 // look for duplicated outputs connected to the output being removed.
1730 for (size_t i = 0; i < mOutputs.size(); i++) {
1731 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1732 if (dupOutputDesc->isDuplicated() &&
1733 (dupOutputDesc->mOutput1 == outputDesc ||
1734 dupOutputDesc->mOutput2 == outputDesc)) {
1735 AudioOutputDescriptor *outputDesc2;
1736 if (dupOutputDesc->mOutput1 == outputDesc) {
1737 outputDesc2 = dupOutputDesc->mOutput2;
1739 outputDesc2 = dupOutputDesc->mOutput1;
1741 // As all active tracks on duplicated output will be deleted,
1742 // and as they were also referenced on the other output, the reference
1743 // count for their stream type must be adjusted accordingly on
1744 // the other output.
1745 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1746 int refCount = dupOutputDesc->mRefCount[j];
1747 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1749 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1750 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1752 mpClientInterface->closeOutput(duplicatedOutput);
1753 delete mOutputs.valueFor(duplicatedOutput);
1754 mOutputs.removeItem(duplicatedOutput);
1758 AudioParameter param;
1759 param.add(String8("closing"), String8("true"));
1760 mpClientInterface->setParameters(output, param.toString());
1762 mpClientInterface->closeOutput(output);
1763 delete mOutputs.valueFor(output);
1764 mOutputs.removeItem(output);
1767 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
1768 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
1770 SortedVector<audio_io_handle_t> outputs;
1772 ALOGVV("getOutputsForDevice() device %04x", device);
1773 for (size_t i = 0; i < openOutputs.size(); i++) {
1774 ALOGVV("output %d isDuplicated=%d device=%04x",
1775 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
1776 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
1777 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
1778 outputs.add(openOutputs.keyAt(i));
1784 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1785 SortedVector<audio_io_handle_t>& outputs2)
1787 if (outputs1.size() != outputs2.size()) {
1790 for (size_t i = 0; i < outputs1.size(); i++) {
1791 if (outputs1[i] != outputs2[i]) {
1798 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1800 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
1801 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
1802 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
1803 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
1805 if (!vectorsEqual(srcOutputs,dstOutputs)) {
1806 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1807 strategy, srcOutputs[0], dstOutputs[0]);
1808 // mute strategy while moving tracks from one output to another
1809 for (size_t i = 0; i < srcOutputs.size(); i++) {
1810 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
1811 if (desc->strategyRefCount(strategy) != 0) {
1812 setStrategyMute(strategy, true, srcOutputs[i]);
1813 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
1817 // Move effects associated to this strategy from previous output to new output
1818 if (strategy == STRATEGY_MEDIA) {
1820 for (size_t i = 0; i < dstOutputs.size(); i++) {
1821 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1822 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1826 SortedVector<audio_io_handle_t> moved;
1827 for (size_t i = 0; i < mEffects.size(); i++) {
1828 EffectDescriptor *desc = mEffects.valueAt(i);
1829 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
1830 desc->mIo != dstOutputs[outIdx]) {
1831 if (moved.indexOf(desc->mIo) < 0) {
1832 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1833 mEffects.keyAt(i), dstOutputs[outIdx]);
1834 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
1835 dstOutputs[outIdx]);
1836 moved.add(desc->mIo);
1838 desc->mIo = dstOutputs[outIdx];
1842 // Move tracks associated to this strategy from previous output to new output
1843 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1844 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1845 //FIXME see fixme on name change
1846 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
1847 dstOutputs[0] /* ignored */);
1853 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1855 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1856 checkOutputForStrategy(STRATEGY_PHONE);
1857 checkOutputForStrategy(STRATEGY_SONIFICATION);
1858 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1859 checkOutputForStrategy(STRATEGY_MEDIA);
1860 checkOutputForStrategy(STRATEGY_DTMF);
1863 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1869 for (size_t i = 0; i < mOutputs.size(); i++) {
1870 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1871 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1872 return mOutputs.keyAt(i);
1879 void AudioPolicyManagerBase::checkA2dpSuspend()
1884 audio_io_handle_t a2dpOutput = getA2dpOutput();
1885 if (a2dpOutput == 0) {
1889 // suspend A2DP output if:
1890 // (NOT already suspended) &&
1891 // ((SCO device is connected &&
1892 // (forced usage for communication || for record is SCO))) ||
1893 // (phone state is ringing || in call)
1895 // restore A2DP output if:
1896 // (Already suspended) &&
1897 // ((SCO device is NOT connected ||
1898 // (forced usage NOT for communication && NOT for record is SCO))) &&
1899 // (phone state is NOT ringing && NOT in call)
1901 if (mA2dpSuspended) {
1902 if (((mScoDeviceAddress == "") ||
1903 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1904 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1905 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1906 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1908 mpClientInterface->restoreOutput(a2dpOutput);
1909 mA2dpSuspended = false;
1912 if (((mScoDeviceAddress != "") &&
1913 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1914 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1915 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1916 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1918 mpClientInterface->suspendOutput(a2dpOutput);
1919 mA2dpSuspended = true;
1924 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1926 audio_devices_t device = (audio_devices_t)0;
1928 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1929 // check the following by order of priority to request a routing change if necessary:
1930 // 1: the strategy enforced audible is active on the output:
1931 // use device for strategy enforced audible
1932 // 2: we are in call or the strategy phone is active on the output:
1933 // use device for strategy phone
1934 // 3: the strategy sonification is active on the output:
1935 // use device for strategy sonification
1936 // 4: the strategy "respectful" sonification is active on the output:
1937 // use device for strategy "respectful" sonification
1938 // 5: the strategy media is active on the output:
1939 // use device for strategy media
1940 // 6: the strategy DTMF is active on the output:
1941 // use device for strategy DTMF
1942 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1943 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1944 } else if (isInCall() ||
1945 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1946 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1947 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1948 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1949 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
1950 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
1951 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1952 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1953 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1954 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1957 ALOGV("getNewDevice() selected device %x", device);
1961 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1962 return (uint32_t)getStrategy(stream);
1965 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1966 audio_devices_t devices;
1967 // By checking the range of stream before calling getStrategy, we avoid
1968 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
1969 // and then return STRATEGY_MEDIA, but we want to return the empty set.
1970 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1971 devices = (audio_devices_t)0;
1973 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1974 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
1979 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1980 AudioSystem::stream_type stream) {
1981 // stream to strategy mapping
1983 case AudioSystem::VOICE_CALL:
1984 case AudioSystem::BLUETOOTH_SCO:
1985 return STRATEGY_PHONE;
1986 case AudioSystem::RING:
1987 case AudioSystem::ALARM:
1988 return STRATEGY_SONIFICATION;
1989 case AudioSystem::NOTIFICATION:
1990 return STRATEGY_SONIFICATION_RESPECTFUL;
1991 case AudioSystem::DTMF:
1992 return STRATEGY_DTMF;
1994 ALOGE("unknown stream type");
1995 case AudioSystem::SYSTEM:
1996 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1997 // while key clicks are played produces a poor result
1998 case AudioSystem::TTS:
1999 case AudioSystem::MUSIC:
2000 return STRATEGY_MEDIA;
2001 case AudioSystem::ENFORCED_AUDIBLE:
2002 return STRATEGY_ENFORCED_AUDIBLE;
2006 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2008 case AudioSystem::MUSIC:
2009 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2010 updateDevicesAndOutputs();
2017 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2020 uint32_t device = 0;
2023 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2024 strategy, mDeviceForStrategy[strategy]);
2025 return mDeviceForStrategy[strategy];
2030 case STRATEGY_SONIFICATION_RESPECTFUL:
2032 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2033 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2034 // while media is playing (or has recently played), use the same device
2035 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2037 // when media is not playing anymore, fall back on the sonification behavior
2038 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2045 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2046 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2049 // when in call, DTMF and PHONE strategies follow the same rules
2052 case STRATEGY_PHONE:
2053 // for phone strategy, we first consider the forced use and then the available devices by order
2055 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2056 case AudioSystem::FORCE_BT_SCO:
2057 if (!isInCall() || strategy != STRATEGY_DTMF) {
2058 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2061 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2063 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
2065 // if SCO device is requested but no SCO device is available, fall back to default case
2068 default: // FORCE_NONE
2069 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2070 if (mHasA2dp && !isInCall() &&
2071 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2072 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2073 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2075 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2078 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2080 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2082 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2084 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2086 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2088 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2090 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2092 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
2094 device = mDefaultOutputDevice;
2096 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2100 case AudioSystem::FORCE_SPEAKER:
2101 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2102 // A2DP speaker when forcing to speaker output
2103 if (mHasA2dp && !isInCall() &&
2104 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2105 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2106 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2109 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2111 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2113 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2115 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2117 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2119 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2121 device = mDefaultOutputDevice;
2123 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2129 case STRATEGY_SONIFICATION:
2131 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2132 // handleIncallSonification().
2134 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2139 case STRATEGY_ENFORCED_AUDIBLE:
2140 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2142 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2143 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2145 if (strategy == STRATEGY_SONIFICATION ||
2146 !mStreams[AUDIO_STREAM_ENFORCED_AUDIBLE].mCanBeMuted) {
2147 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2149 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2152 // The second device used for sonification is the same as the device used by media strategy
2155 case STRATEGY_MEDIA: {
2156 uint32_t device2 = 0;
2157 if (mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2158 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2159 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2161 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2164 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2168 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2171 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2174 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2177 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2180 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2183 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2186 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2189 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2192 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2193 // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise
2196 device = mDefaultOutputDevice;
2198 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2203 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2207 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2208 return (audio_devices_t)device;
2211 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2213 for (int i = 0; i < NUM_STRATEGIES; i++) {
2214 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2216 mPreviousOutputs = mOutputs;
2219 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2220 audio_devices_t prevDevice,
2223 // mute/unmute strategies using an incompatible device combination
2224 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2225 // if unmuting, unmute only after the specified delay
2226 if (outputDesc->isDuplicated()) {
2230 uint32_t muteWaitMs = 0;
2231 audio_devices_t device = outputDesc->device();
2232 bool shouldMute = (outputDesc->refCount() != 0) &&
2233 (AudioSystem::popCount(device) >= 2);
2234 // temporary mute output if device selection changes to avoid volume bursts due to
2235 // different per device volumes
2236 bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
2238 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2239 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2240 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2241 bool doMute = false;
2243 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2245 outputDesc->mStrategyMutedByDevice[i] = true;
2246 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2248 outputDesc->mStrategyMutedByDevice[i] = false;
2250 if (doMute || tempMute) {
2251 for (size_t j = 0; j < mOutputs.size(); j++) {
2252 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2253 if ((desc->supportedDevices() & outputDesc->supportedDevices()) == 0) {
2256 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2257 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2258 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2259 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2260 if (desc->strategyRefCount((routing_strategy)i) != 0) {
2262 setStrategyMute((routing_strategy)i, true, curOutput);
2263 setStrategyMute((routing_strategy)i, false, curOutput,
2264 desc->latency() * 2, device);
2266 if (tempMute || mute) {
2267 if (muteWaitMs < desc->latency()) {
2268 muteWaitMs = desc->latency();
2276 // FIXME: should not need to double latency if volume could be applied immediately by the
2277 // audioflinger mixer. We must account for the delay between now and the next time
2278 // the audioflinger thread for this output will process a buffer (which corresponds to
2279 // one buffer size, usually 1/2 or 1/4 of the latency).
2281 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2282 if (muteWaitMs > delayMs) {
2283 muteWaitMs -= delayMs;
2284 usleep(muteWaitMs * 1000);
2290 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2291 audio_devices_t device,
2295 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2296 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2297 AudioParameter param;
2298 uint32_t muteWaitMs = 0;
2300 if (outputDesc->isDuplicated()) {
2301 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2302 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2305 // filter devices according to output selected
2306 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2308 audio_devices_t prevDevice = outputDesc->mDevice;
2310 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2313 outputDesc->mDevice = device;
2315 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2317 // Do not change the routing if:
2318 // - the requested device is 0
2319 // - the requested device is the same as current device and force is not specified.
2320 // Doing this check here allows the caller to call setOutputDevice() without conditions
2321 if ((device == 0 || device == prevDevice) && !force) {
2322 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2326 ALOGV("setOutputDevice() changing device");
2328 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2329 mpClientInterface->setParameters(output, param.toString(), delayMs);
2331 // update stream volumes according to new device
2332 applyStreamVolumes(output, device, delayMs);
2337 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2338 uint32_t samplingRate,
2340 uint32_t channelMask)
2342 // Choose an input profile based on the requested capture parameters: select the first available
2343 // profile supporting all requested parameters.
2345 for (size_t i = 0; i < mHwModules.size(); i++)
2347 if (mHwModules[i]->mHandle == 0) {
2350 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2352 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2353 if (profile->isCompatibleProfile(device, samplingRate, format,
2354 channelMask,(audio_output_flags_t)0)) {
2362 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2364 uint32_t device = 0;
2366 switch(inputSource) {
2367 case AUDIO_SOURCE_DEFAULT:
2368 case AUDIO_SOURCE_MIC:
2369 case AUDIO_SOURCE_VOICE_RECOGNITION:
2370 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2371 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2372 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2373 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2374 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
2375 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
2376 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2377 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2380 case AUDIO_SOURCE_CAMCORDER:
2381 if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BACK_MIC) {
2382 device = AudioSystem::DEVICE_IN_BACK_MIC;
2383 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2384 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2387 case AUDIO_SOURCE_VOICE_UPLINK:
2388 case AUDIO_SOURCE_VOICE_DOWNLINK:
2389 case AUDIO_SOURCE_VOICE_CALL:
2390 if (mAvailableInputDevices & AudioSystem::DEVICE_IN_VOICE_CALL) {
2391 device = AudioSystem::DEVICE_IN_VOICE_CALL;
2395 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2398 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2399 return (audio_devices_t)device;
2402 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
2404 for (size_t i = 0; i < mInputs.size(); i++) {
2405 if (mInputs.valueAt(i)->mRefCount > 0) {
2406 return mInputs.keyAt(i);
2413 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2416 // this happens when forcing a route update and no track is active on an output.
2417 // In this case the returned category is not important.
2418 device = AUDIO_DEVICE_OUT_SPEAKER;
2419 } else if (AudioSystem::popCount(device) > 1) {
2420 // Multiple device selection is either:
2421 // - speaker + one other device: give priority to speaker in this case.
2422 // - one A2DP device + another device: happens with duplicated output. In this case
2423 // retain the device on the A2DP output as the other must not correspond to an active
2424 // selection if not the speaker.
2425 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2426 device = AUDIO_DEVICE_OUT_SPEAKER;
2428 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2432 ALOGW_IF(AudioSystem::popCount(device) != 1,
2433 "getDeviceForVolume() invalid device combination: %08x",
2439 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2441 switch(getDeviceForVolume(device)) {
2442 case AUDIO_DEVICE_OUT_EARPIECE:
2443 return DEVICE_CATEGORY_EARPIECE;
2444 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2445 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2446 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2447 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2448 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2449 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2450 return DEVICE_CATEGORY_HEADSET;
2451 case AUDIO_DEVICE_OUT_SPEAKER:
2452 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2453 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2454 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2455 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2456 case AUDIO_DEVICE_OUT_USB_DEVICE:
2458 return DEVICE_CATEGORY_SPEAKER;
2462 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2465 device_category deviceCategory = getDeviceCategory(device);
2466 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2468 // the volume index in the UI is relative to the min and max volume indices for this stream type
2469 int nbSteps = 1 + curve[VOLMAX].mIndex -
2470 curve[VOLMIN].mIndex;
2471 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2472 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2474 // find what part of the curve this index volume belongs to, or if it's out of bounds
2476 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2478 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2480 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2482 } else if (volIdx <= curve[VOLMAX].mIndex) {
2484 } else { // out of bounds
2488 // linear interpolation in the attenuation table in dB
2489 float decibels = curve[segment].mDBAttenuation +
2490 ((float)(volIdx - curve[segment].mIndex)) *
2491 ( (curve[segment+1].mDBAttenuation -
2492 curve[segment].mDBAttenuation) /
2493 ((float)(curve[segment+1].mIndex -
2494 curve[segment].mIndex)) );
2496 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2498 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2499 curve[segment].mIndex, volIdx,
2500 curve[segment+1].mIndex,
2501 curve[segment].mDBAttenuation,
2503 curve[segment+1].mDBAttenuation,
2506 return amplification;
2509 const AudioPolicyManagerBase::VolumeCurvePoint
2510 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2511 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2514 const AudioPolicyManagerBase::VolumeCurvePoint
2515 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2516 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2519 const AudioPolicyManagerBase::VolumeCurvePoint
2520 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2521 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2524 const AudioPolicyManagerBase::VolumeCurvePoint
2525 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2526 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2529 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2530 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2531 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2532 const AudioPolicyManagerBase::VolumeCurvePoint
2533 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2534 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2537 const AudioPolicyManagerBase::VolumeCurvePoint
2538 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2539 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2542 const AudioPolicyManagerBase::VolumeCurvePoint
2543 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2544 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2545 { // AUDIO_STREAM_VOICE_CALL
2546 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2547 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2548 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2550 { // AUDIO_STREAM_SYSTEM
2551 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2552 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2553 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2555 { // AUDIO_STREAM_RING
2556 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2557 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2558 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2560 { // AUDIO_STREAM_MUSIC
2561 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2562 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2563 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2565 { // AUDIO_STREAM_ALARM
2566 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2567 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2568 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2570 { // AUDIO_STREAM_NOTIFICATION
2571 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2572 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2573 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2575 { // AUDIO_STREAM_BLUETOOTH_SCO
2576 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2577 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2578 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2580 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2581 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2582 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2583 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2585 { // AUDIO_STREAM_DTMF
2586 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2587 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2588 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2590 { // AUDIO_STREAM_TTS
2591 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2592 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2593 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2597 void AudioPolicyManagerBase::initializeVolumeCurves()
2599 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2600 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2601 mStreams[i].mVolumeCurve[j] =
2602 sVolumeProfiles[i][j];
2607 float AudioPolicyManagerBase::computeVolume(int stream,
2609 audio_io_handle_t output,
2610 audio_devices_t device)
2613 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2614 StreamDescriptor &streamDesc = mStreams[stream];
2617 device = outputDesc->device();
2620 // if volume is not 0 (not muted), force media volume to max on digital output
2621 if (stream == AudioSystem::MUSIC &&
2622 index != mStreams[stream].mIndexMin &&
2623 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2624 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2625 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2626 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2630 volume = volIndexToAmpl(device, streamDesc, index);
2632 // if a headset is connected, apply the following rules to ring tones and notifications
2633 // to avoid sound level bursts in user's ears:
2634 // - always attenuate ring tones and notifications volume by 6dB
2635 // - if music is playing, always limit the volume to current music volume,
2636 // with a minimum threshold at -36dB so that notification is always perceived.
2637 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2638 if ((device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
2639 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2640 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
2641 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
2642 ((stream_strategy == STRATEGY_SONIFICATION)
2643 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2644 || (stream == AudioSystem::SYSTEM)) &&
2645 streamDesc.mCanBeMuted) {
2646 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2647 // when the phone is ringing we must consider that music could have been paused just before
2648 // by the music application and behave as if music was active if the last music track was
2650 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2651 mLimitRingtoneVolume) {
2652 float musicVol = computeVolume(AudioSystem::MUSIC,
2653 mStreams[AudioSystem::MUSIC].getVolumeIndex(device),
2656 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2657 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2658 if (volume > minVol) {
2660 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2668 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2670 audio_io_handle_t output,
2671 audio_devices_t device,
2676 // do not change actual stream volume if the stream is muted
2677 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2678 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2679 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2683 // do not change in call volume if bluetooth is connected and vice versa
2684 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2685 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2686 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2687 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2688 return INVALID_OPERATION;
2691 float volume = computeVolume(stream, index, output, device);
2692 // We actually change the volume if:
2693 // - the float value returned by computeVolume() changed
2694 // - the force flag is set
2695 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2697 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2698 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2699 if (stream == AudioSystem::VOICE_CALL ||
2700 stream == AudioSystem::DTMF ||
2701 stream == AudioSystem::BLUETOOTH_SCO) {
2702 // offset value to reflect actual hardware volume that never reaches 0
2703 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2704 volume = 0.01 + 0.99 * volume;
2705 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2707 if (stream == AudioSystem::BLUETOOTH_SCO) {
2708 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2712 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2715 if (stream == AudioSystem::VOICE_CALL ||
2716 stream == AudioSystem::BLUETOOTH_SCO) {
2718 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2719 if (stream == AudioSystem::VOICE_CALL) {
2720 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2725 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2726 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2727 mLastVoiceVolume = voiceVolume;
2734 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2735 audio_devices_t device,
2739 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2741 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2742 checkAndSetVolume(stream,
2743 mStreams[stream].getVolumeIndex(device),
2751 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2753 audio_io_handle_t output,
2755 audio_devices_t device)
2757 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2758 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2759 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2760 setStreamMute(stream, on, output, delayMs, device);
2765 void AudioPolicyManagerBase::setStreamMute(int stream,
2767 audio_io_handle_t output,
2769 audio_devices_t device)
2771 StreamDescriptor &streamDesc = mStreams[stream];
2772 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2774 device = outputDesc->device();
2777 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
2778 stream, on, output, outputDesc->mMuteCount[stream], device);
2781 if (outputDesc->mMuteCount[stream] == 0) {
2782 if (streamDesc.mCanBeMuted) {
2783 checkAndSetVolume(stream, 0, output, device, delayMs);
2786 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2787 outputDesc->mMuteCount[stream]++;
2789 if (outputDesc->mMuteCount[stream] == 0) {
2790 ALOGV("setStreamMute() unmuting non muted stream!");
2793 if (--outputDesc->mMuteCount[stream] == 0) {
2794 checkAndSetVolume(stream,
2795 streamDesc.getVolumeIndex((audio_devices_t)device),
2803 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2805 // if the stream pertains to sonification strategy and we are in call we must
2806 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2807 // in the device used for phone strategy and play the tone if the selected device does not
2808 // interfere with the device used for phone strategy
2809 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2810 // many times as there are active tracks on the output
2811 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2812 if ((stream_strategy == STRATEGY_SONIFICATION) ||
2813 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2814 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2815 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2816 stream, starting, outputDesc->mDevice, stateChange);
2817 if (outputDesc->mRefCount[stream]) {
2820 muteCount = outputDesc->mRefCount[stream];
2822 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2823 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2824 for (int i = 0; i < muteCount; i++) {
2825 setStreamMute(stream, starting, mPrimaryOutput);
2828 ALOGV("handleIncallSonification() high visibility");
2829 if (outputDesc->device() &
2830 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2831 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2832 for (int i = 0; i < muteCount; i++) {
2833 setStreamMute(stream, starting, mPrimaryOutput);
2837 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2839 mpClientInterface->stopTone();
2846 bool AudioPolicyManagerBase::isInCall()
2848 return isStateInCall(mPhoneState);
2851 bool AudioPolicyManagerBase::isStateInCall(int state) {
2852 return ((state == AudioSystem::MODE_IN_CALL) ||
2853 (state == AudioSystem::MODE_IN_COMMUNICATION));
2856 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
2857 uint32_t samplingRate,
2858 audio_format_t format,
2859 audio_channel_mask_t channelMask,
2860 audio_output_flags_t flags,
2861 audio_devices_t device)
2863 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2864 (format != 0 && !AudioSystem::isLinearPCM(format)));
2867 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2869 return MAX_EFFECTS_CPU_LOAD;
2872 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2874 return MAX_EFFECTS_MEMORY;
2877 // --- AudioOutputDescriptor class implementation
2879 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2880 const IOProfile *profile)
2881 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
2882 mChannelMask((audio_channel_mask_t)0), mLatency(0),
2883 mFlags((audio_output_flags_t)0), mDevice((audio_devices_t)0),
2884 mOutput1(0), mOutput2(0), mProfile(profile)
2886 // clear usage count for all stream types
2887 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2889 mCurVolume[i] = -1.0;
2893 if (profile != NULL) {
2894 mSamplingRate = profile->mSamplingRates[0];
2895 mFormat = profile->mFormats[0];
2896 mChannelMask = profile->mChannelMasks[0];
2897 mFlags = profile->mFlags;
2901 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2903 if (isDuplicated()) {
2904 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
2910 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
2912 if (isDuplicated()) {
2913 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
2919 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
2920 const AudioOutputDescriptor *outputDesc)
2922 if (isDuplicated()) {
2923 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
2924 } else if (outputDesc->isDuplicated()){
2925 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
2927 return (mProfile->mModule == outputDesc->mProfile->mModule);
2931 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2933 // forward usage count change to attached outputs
2934 if (isDuplicated()) {
2935 mOutput1->changeRefCount(stream, delta);
2936 mOutput2->changeRefCount(stream, delta);
2938 if ((delta + (int)mRefCount[stream]) < 0) {
2939 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2940 mRefCount[stream] = 0;
2943 mRefCount[stream] += delta;
2944 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2947 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2949 uint32_t refcount = 0;
2950 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2951 refcount += mRefCount[i];
2956 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2958 uint32_t refCount = 0;
2959 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2960 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2961 refCount += mRefCount[i];
2967 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
2969 if (isDuplicated()) {
2970 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
2972 return mProfile->mSupportedDevices ;
2976 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2978 const size_t SIZE = 256;
2982 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2983 result.append(buffer);
2984 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2985 result.append(buffer);
2986 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
2987 result.append(buffer);
2988 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2989 result.append(buffer);
2990 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2991 result.append(buffer);
2992 snprintf(buffer, SIZE, " Devices %08x\n", device());
2993 result.append(buffer);
2994 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2995 result.append(buffer);
2996 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2997 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2998 result.append(buffer);
3000 write(fd, result.string(), result.size());
3005 // --- AudioInputDescriptor class implementation
3007 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3008 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3009 mDevice((audio_devices_t)0), mRefCount(0),
3010 mInputSource(0), mProfile(profile)
3014 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3016 const size_t SIZE = 256;
3020 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3021 result.append(buffer);
3022 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3023 result.append(buffer);
3024 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3025 result.append(buffer);
3026 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3027 result.append(buffer);
3028 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3029 result.append(buffer);
3030 write(fd, result.string(), result.size());
3035 // --- StreamDescriptor class implementation
3037 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3038 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3040 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3043 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3045 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3046 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3047 if (mIndexCur.indexOfKey(device) < 0) {
3048 device = AUDIO_DEVICE_OUT_DEFAULT;
3050 return mIndexCur.valueFor(device);
3053 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3055 const size_t SIZE = 256;
3059 snprintf(buffer, SIZE, "%s %02d %02d ",
3060 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3061 result.append(buffer);
3062 for (size_t i = 0; i < mIndexCur.size(); i++) {
3063 snprintf(buffer, SIZE, "%04x : %02d, ",
3065 mIndexCur.valueAt(i));
3066 result.append(buffer);
3068 result.append("\n");
3070 write(fd, result.string(), result.size());
3073 // --- EffectDescriptor class implementation
3075 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3077 const size_t SIZE = 256;
3081 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3082 result.append(buffer);
3083 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3084 result.append(buffer);
3085 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3086 result.append(buffer);
3087 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3088 result.append(buffer);
3089 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3090 result.append(buffer);
3091 write(fd, result.string(), result.size());
3096 // --- IOProfile class implementation
3098 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3099 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3103 AudioPolicyManagerBase::HwModule::~HwModule()
3105 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3106 delete mOutputProfiles[i];
3108 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3109 delete mInputProfiles[i];
3111 free((void *)mName);
3114 void AudioPolicyManagerBase::HwModule::dump(int fd)
3116 const size_t SIZE = 256;
3120 snprintf(buffer, SIZE, " - name: %s\n", mName);
3121 result.append(buffer);
3122 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3123 result.append(buffer);
3124 write(fd, result.string(), result.size());
3125 if (mOutputProfiles.size()) {
3126 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3127 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3128 snprintf(buffer, SIZE, " output %d:\n", i);
3129 write(fd, buffer, strlen(buffer));
3130 mOutputProfiles[i]->dump(fd);
3133 if (mInputProfiles.size()) {
3134 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3135 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3136 snprintf(buffer, SIZE, " input %d:\n", i);
3137 write(fd, buffer, strlen(buffer));
3138 mInputProfiles[i]->dump(fd);
3143 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3144 : mFlags((audio_output_flags_t)0), mModule(module)
3148 AudioPolicyManagerBase::IOProfile::~IOProfile()
3152 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3153 // means a parameter is don't care
3154 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3155 uint32_t samplingRate,
3157 uint32_t channelMask,
3158 audio_output_flags_t flags) const
3160 if ((mSupportedDevices & device) != device) {
3163 if ((mFlags & flags) != flags) {
3166 if (samplingRate != 0) {
3168 for (i = 0; i < mSamplingRates.size(); i++)
3170 if (mSamplingRates[i] == samplingRate) {
3174 if (i == mSamplingRates.size()) {
3180 for (i = 0; i < mFormats.size(); i++)
3182 if (mFormats[i] == format) {
3186 if (i == mFormats.size()) {
3190 if (channelMask != 0) {
3192 for (i = 0; i < mChannelMasks.size(); i++)
3194 if (mChannelMasks[i] == channelMask) {
3198 if (i == mChannelMasks.size()) {
3205 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3207 const size_t SIZE = 256;
3211 snprintf(buffer, SIZE, " - sampling rates: ");
3212 result.append(buffer);
3213 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3214 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3215 result.append(buffer);
3216 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3219 snprintf(buffer, SIZE, " - channel masks: ");
3220 result.append(buffer);
3221 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3222 snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3223 result.append(buffer);
3224 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3227 snprintf(buffer, SIZE, " - formats: ");
3228 result.append(buffer);
3229 for (size_t i = 0; i < mFormats.size(); i++) {
3230 snprintf(buffer, SIZE, "%d", mFormats[i]);
3231 result.append(buffer);
3232 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3235 snprintf(buffer, SIZE, " - devices: %04x\n", mSupportedDevices);
3236 result.append(buffer);
3237 snprintf(buffer, SIZE, " - flags: %04x\n", mFlags);
3238 result.append(buffer);
3240 write(fd, result.string(), result.size());
3243 // --- audio_policy.conf file parsing
3245 struct StringToEnum {
3250 #define STRING_TO_ENUM(string) { #string, string }
3251 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3253 const struct StringToEnum sDeviceNameToEnumTable[] = {
3254 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3255 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3256 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3257 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3258 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3259 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3260 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3261 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3262 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3263 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3264 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3265 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3266 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3267 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3268 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3269 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3270 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3271 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3274 const struct StringToEnum sFlagNameToEnumTable[] = {
3275 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3276 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3277 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3278 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3281 const struct StringToEnum sFormatNameToEnumTable[] = {
3282 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3283 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3284 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3285 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3286 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3289 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3290 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3291 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3292 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3293 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3296 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3297 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3298 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3302 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3306 for (size_t i = 0; i < size; i++) {
3307 if (strcmp(table[i].name, name) == 0) {
3308 ALOGV("stringToEnum() found %s", table[i].name);
3309 return table[i].value;
3315 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3319 // it is OK to cast name to non const here as we are not going to use it after
3320 // strtok() modifies it
3321 char *flagName = strtok(name, "|");
3322 while (flagName != NULL) {
3323 if (strlen(flagName) != 0) {
3324 flag |= stringToEnum(sFlagNameToEnumTable,
3325 ARRAY_SIZE(sFlagNameToEnumTable),
3328 flagName = strtok(NULL, "|");
3330 return (audio_output_flags_t)flag;
3333 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3335 uint32_t device = 0;
3337 char *devName = strtok(name, "|");
3338 while (devName != NULL) {
3339 if (strlen(devName) != 0) {
3340 device |= stringToEnum(sDeviceNameToEnumTable,
3341 ARRAY_SIZE(sDeviceNameToEnumTable),
3344 devName = strtok(NULL, "|");
3346 return (audio_devices_t)device;
3349 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3351 char *str = strtok(name, "|");
3353 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3354 // rates should be read from the output stream after it is opened for the first time
3355 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3356 profile->mSamplingRates.add(0);
3360 while (str != NULL) {
3361 uint32_t rate = atoi(str);
3363 ALOGV("loadSamplingRates() adding rate %d", rate);
3364 profile->mSamplingRates.add(rate);
3366 str = strtok(NULL, "|");
3371 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3373 char *str = strtok(name, "|");
3375 // by convention, "0' in the first entry in mFormats indicates the supported formats
3376 // should be read from the output stream after it is opened for the first time
3377 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3378 profile->mFormats.add((audio_format_t)0);
3382 while (str != NULL) {
3383 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3384 ARRAY_SIZE(sFormatNameToEnumTable),
3387 profile->mFormats.add(format);
3389 str = strtok(NULL, "|");
3394 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3396 const char *str = strtok(name, "|");
3398 ALOGV("loadInChannels() %s", name);
3400 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3401 profile->mChannelMasks.add((audio_channel_mask_t)0);
3405 while (str != NULL) {
3406 audio_channel_mask_t channelMask =
3407 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3408 ARRAY_SIZE(sInChannelsNameToEnumTable),
3410 if (channelMask != 0) {
3411 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3412 profile->mChannelMasks.add(channelMask);
3414 str = strtok(NULL, "|");
3419 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3421 const char *str = strtok(name, "|");
3423 ALOGV("loadOutChannels() %s", name);
3425 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3426 // masks should be read from the output stream after it is opened for the first time
3427 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3428 profile->mChannelMasks.add((audio_channel_mask_t)0);
3432 while (str != NULL) {
3433 audio_channel_mask_t channelMask =
3434 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3435 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3437 if (channelMask != 0) {
3438 profile->mChannelMasks.add(channelMask);
3440 str = strtok(NULL, "|");
3445 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3447 cnode *node = root->first_child;
3449 IOProfile *profile = new IOProfile(module);
3452 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3453 loadSamplingRates((char *)node->value, profile);
3454 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3455 loadFormats((char *)node->value, profile);
3456 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3457 loadInChannels((char *)node->value, profile);
3458 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3459 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3463 ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3464 "loadInput() invalid supported devices");
3465 ALOGW_IF(profile->mChannelMasks.size() == 0,
3466 "loadInput() invalid supported channel masks");
3467 ALOGW_IF(profile->mSamplingRates.size() == 0,
3468 "loadInput() invalid supported sampling rates");
3469 ALOGW_IF(profile->mFormats.size() == 0,
3470 "loadInput() invalid supported formats");
3471 if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3472 (profile->mChannelMasks.size() != 0) &&
3473 (profile->mSamplingRates.size() != 0) &&
3474 (profile->mFormats.size() != 0)) {
3476 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3478 module->mInputProfiles.add(profile);
3486 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3488 cnode *node = root->first_child;
3490 IOProfile *profile = new IOProfile(module);
3493 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3494 loadSamplingRates((char *)node->value, profile);
3495 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3496 loadFormats((char *)node->value, profile);
3497 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3498 loadOutChannels((char *)node->value, profile);
3499 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3500 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3501 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3502 profile->mFlags = parseFlagNames((char *)node->value);
3506 ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3507 "loadOutput() invalid supported devices");
3508 ALOGW_IF(profile->mChannelMasks.size() == 0,
3509 "loadOutput() invalid supported channel masks");
3510 ALOGW_IF(profile->mSamplingRates.size() == 0,
3511 "loadOutput() invalid supported sampling rates");
3512 ALOGW_IF(profile->mFormats.size() == 0,
3513 "loadOutput() invalid supported formats");
3514 if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3515 (profile->mChannelMasks.size() != 0) &&
3516 (profile->mSamplingRates.size() != 0) &&
3517 (profile->mFormats.size() != 0)) {
3519 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3520 profile->mSupportedDevices, profile->mFlags);
3522 module->mOutputProfiles.add(profile);
3530 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3532 cnode *node = config_find(root, OUTPUTS_TAG);
3533 status_t status = NAME_NOT_FOUND;
3535 HwModule *module = new HwModule(root->name);
3538 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3540 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3544 node = node->first_child;
3546 ALOGV("loadHwModule() loading output %s", node->name);
3547 status_t tmpStatus = loadOutput(node, module);
3548 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3554 node = config_find(root, INPUTS_TAG);
3556 node = node->first_child;
3558 ALOGV("loadHwModule() loading input %s", node->name);
3559 status_t tmpStatus = loadInput(node, module);
3560 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3566 if (status == NO_ERROR) {
3567 mHwModules.add(module);
3573 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3575 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3580 node = node->first_child;
3582 ALOGV("loadHwModules() loading module %s", node->name);
3588 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3590 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3594 node = node->first_child;
3596 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3597 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3598 ALOGW_IF(mAttachedOutputDevices == 0, "loadGlobalConfig() no attached output devices");
3599 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3600 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3601 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3602 ARRAY_SIZE(sDeviceNameToEnumTable),
3603 (char *)node->value);
3604 ALOGW_IF(mDefaultOutputDevice == 0, "loadGlobalConfig() default device not specified");
3605 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3606 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3607 mAvailableInputDevices = parseDeviceNames((char *)node->value);
3608 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3614 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3619 data = (char *)load_file(path, NULL);
3623 root = config_node("", "");
3624 config_load(root, data);
3626 loadGlobalConfig(root);
3627 loadHwModules(root);
3633 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3638 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3643 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3644 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3645 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3647 module = new HwModule("primary");
3649 profile = new IOProfile(module);
3650 profile->mSamplingRates.add(44100);
3651 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3652 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3653 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3654 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3655 module->mOutputProfiles.add(profile);
3657 profile = new IOProfile(module);
3658 profile->mSamplingRates.add(8000);
3659 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3660 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3661 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3662 module->mInputProfiles.add(profile);
3664 mHwModules.add(module);
3667 }; // namespace android