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
19 #include <utils/Log.h>
20 #include <hardware_legacy/AudioPolicyManagerBase.h>
21 #include <hardware/audio_effect.h>
22 #include <hardware/audio.h>
24 #include <hardware_legacy/audio_policy_conf.h>
26 namespace android_audio_legacy {
28 // ----------------------------------------------------------------------------
29 // AudioPolicyInterface implementation
30 // ----------------------------------------------------------------------------
33 status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
34 AudioSystem::device_connection_state state,
35 const char *device_address)
37 audio_io_handle_t output = 0;
39 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
41 // connect/disconnect only 1 device at a time
42 if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
44 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
45 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
49 // handle output devices
50 if (AudioSystem::isOutputDevice(device)) {
52 if (!mHasA2dp && AudioSystem::isA2dpDevice(device)) {
53 ALOGE("setDeviceConnectionState() invalid device: %x", device);
56 if (!mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
57 ALOGE("setDeviceConnectionState() invalid device: %x", device);
63 // handle output device connection
64 case AudioSystem::DEVICE_STATE_AVAILABLE:
65 if (mAvailableOutputDevices & device) {
66 ALOGW("setDeviceConnectionState() device already connected: %x", device);
67 return INVALID_OPERATION;
69 ALOGV("setDeviceConnectionState() connecting device %x", device);
71 // register new device as available
72 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
74 output = checkOutputForDevice((audio_devices_t)device, state);
76 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
77 return INVALID_OPERATION;
79 // handle A2DP device connection
80 if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
82 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
83 mpClientInterface->setParameters(output, param.toString());
84 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
85 mA2dpSuspended = false;
86 } else if (AudioSystem::isBluetoothScoDevice(device)) {
87 ALOGV("setDeviceConnectionState() BT SCO device, address %s", device_address);
88 // keep track of SCO device address
89 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
90 } else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
91 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
92 mpClientInterface->setParameters(output, mUsbCardAndDevice);
95 // handle output device disconnection
96 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
97 if (!(mAvailableOutputDevices & device)) {
98 ALOGW("setDeviceConnectionState() device not connected: %x", device);
99 return INVALID_OPERATION;
103 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
104 // remove device from available output devices
105 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
107 output = checkOutputForDevice((audio_devices_t)device, state);
108 // handle A2DP device disconnection
109 if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
110 mA2dpDeviceAddress = "";
111 mA2dpSuspended = false;
112 } else if (AudioSystem::isBluetoothScoDevice(device)) {
113 mScoDeviceAddress = "";
114 } else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
115 mUsbCardAndDevice = "";
120 ALOGE("setDeviceConnectionState() invalid state: %x", state);
125 checkOutputForAllStrategies();
126 // outputs must be closed after checkOutputForAllStrategies() is executed
127 if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && output != 0) {
131 updateDeviceForStrategy();
132 for (size_t i = 0; i < mOutputs.size(); i++) {
133 setOutputDevice(mOutputs.keyAt(i), getNewDevice(mOutputs.keyAt(i), true /*fromCache*/));
136 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
137 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
138 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
139 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
140 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
141 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
146 // handle input devices
147 if (AudioSystem::isInputDevice(device)) {
151 // handle input device connection
152 case AudioSystem::DEVICE_STATE_AVAILABLE: {
153 if (mAvailableInputDevices & device) {
154 ALOGW("setDeviceConnectionState() device already connected: %d", device);
155 return INVALID_OPERATION;
157 mAvailableInputDevices = (audio_devices_t)(mAvailableInputDevices | device);
161 // handle input device disconnection
162 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
163 if (!(mAvailableInputDevices & device)) {
164 ALOGW("setDeviceConnectionState() device not connected: %d", device);
165 return INVALID_OPERATION;
167 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
171 ALOGE("setDeviceConnectionState() invalid state: %x", state);
175 audio_io_handle_t activeInput = getActiveInput();
176 if (activeInput != 0) {
177 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
178 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
179 if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
180 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
181 inputDesc->mDevice, newDevice, activeInput);
182 inputDesc->mDevice = newDevice;
183 AudioParameter param = AudioParameter();
184 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
185 mpClientInterface->setParameters(activeInput, param.toString());
192 ALOGW("setDeviceConnectionState() invalid device: %x", device);
196 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
197 const char *device_address)
199 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
200 String8 address = String8(device_address);
201 if (AudioSystem::isOutputDevice(device)) {
202 if (device & mAvailableOutputDevices) {
203 if (AudioSystem::isA2dpDevice(device) &&
204 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
207 if (AudioSystem::isBluetoothScoDevice(device) &&
208 address != "" && mScoDeviceAddress != address) {
211 if (audio_is_usb_device((audio_devices_t)device) &&
212 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
213 ALOGE("setDeviceConnectionState() invalid device: %x", device);
216 state = AudioSystem::DEVICE_STATE_AVAILABLE;
218 } else if (AudioSystem::isInputDevice(device)) {
219 if (device & mAvailableInputDevices) {
220 state = AudioSystem::DEVICE_STATE_AVAILABLE;
227 void AudioPolicyManagerBase::setPhoneState(int state)
229 ALOGV("setPhoneState() state %d", state);
230 audio_devices_t newDevice = (audio_devices_t)0;
231 if (state < 0 || state >= AudioSystem::NUM_MODES) {
232 ALOGW("setPhoneState() invalid state %d", state);
236 if (state == mPhoneState ) {
237 ALOGW("setPhoneState() setting same state %d", state);
241 // if leaving call state, handle special case of active streams
242 // pertaining to sonification strategy see handleIncallSonification()
244 ALOGV("setPhoneState() in call state management: new state is %d", state);
245 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
246 handleIncallSonification(stream, false, true);
250 // store previous phone state for management of sonification strategy below
251 int oldState = mPhoneState;
255 // are we entering or starting a call
256 if (!isStateInCall(oldState) && isStateInCall(state)) {
257 ALOGV(" Entering call in setPhoneState()");
258 // force routing command to audio hardware when starting a call
259 // even if no device change is needed
261 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
262 ALOGV(" Exiting call in setPhoneState()");
263 // force routing command to audio hardware when exiting a call
264 // even if no device change is needed
266 } else if (isStateInCall(state) && (state != oldState)) {
267 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
268 // force routing command to audio hardware when switching between telephony and VoIP
269 // even if no device change is needed
273 // check for device and output changes triggered by new phone state
274 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
276 checkOutputForAllStrategies();
277 updateDeviceForStrategy();
279 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
281 // force routing command to audio hardware when ending call
282 // even if no device change is needed
283 if (isStateInCall(oldState) && newDevice == 0) {
284 newDevice = hwOutputDesc->device();
287 // when changing from ring tone to in call mode, mute the ringing tone
288 // immediately and delay the route change to avoid sending the ring tone
289 // tail into the earpiece or headset.
291 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
292 // delay the device change command by twice the output latency to have some margin
293 // and be sure that audio buffers not yet affected by the mute are out when
294 // we actually apply the route change
295 delayMs = hwOutputDesc->mLatency*2;
296 setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
299 // change routing is necessary
300 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
302 // if entering in call state, handle special case of active streams
303 // pertaining to sonification strategy see handleIncallSonification()
304 if (isStateInCall(state)) {
305 ALOGV("setPhoneState() in call state management: new state is %d", state);
306 // unmute the ringing tone after a sufficient delay if it was muted before
307 // setting output device above
308 if (oldState == AudioSystem::MODE_RINGTONE) {
309 setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
311 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
312 handleIncallSonification(stream, true, true);
316 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
317 if (state == AudioSystem::MODE_RINGTONE &&
318 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
319 mLimitRingtoneVolume = true;
321 mLimitRingtoneVolume = false;
325 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
327 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
329 bool forceVolumeReeval = false;
331 case AudioSystem::FOR_COMMUNICATION:
332 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
333 config != AudioSystem::FORCE_NONE) {
334 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
337 forceVolumeReeval = true;
338 mForceUse[usage] = config;
340 case AudioSystem::FOR_MEDIA:
341 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
342 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
343 config != AudioSystem::FORCE_ANALOG_DOCK &&
344 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE) {
345 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
348 mForceUse[usage] = config;
350 case AudioSystem::FOR_RECORD:
351 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
352 config != AudioSystem::FORCE_NONE) {
353 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
356 mForceUse[usage] = config;
358 case AudioSystem::FOR_DOCK:
359 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
360 config != AudioSystem::FORCE_BT_DESK_DOCK &&
361 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
362 config != AudioSystem::FORCE_ANALOG_DOCK &&
363 config != AudioSystem::FORCE_DIGITAL_DOCK) {
364 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
366 forceVolumeReeval = true;
367 mForceUse[usage] = config;
370 ALOGW("setForceUse() invalid usage %d", usage);
374 // check for device and output changes triggered by new force usage
376 checkOutputForAllStrategies();
377 updateDeviceForStrategy();
378 for (size_t i = 0; i < mOutputs.size(); i++) {
379 audio_io_handle_t output = mOutputs.keyAt(i);
380 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
381 setOutputDevice(output, newDevice, true);
382 if (forceVolumeReeval) {
383 applyStreamVolumes(output, newDevice, 0, true);
387 audio_io_handle_t activeInput = getActiveInput();
388 if (activeInput != 0) {
389 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
390 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
391 if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
392 ALOGV("setForceUse() changing device from %x to %x for input %d",
393 inputDesc->mDevice, newDevice, activeInput);
394 inputDesc->mDevice = newDevice;
395 AudioParameter param = AudioParameter();
396 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
397 mpClientInterface->setParameters(activeInput, param.toString());
403 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
405 return mForceUse[usage];
408 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
410 ALOGV("setSystemProperty() property %s, value %s", property, value);
411 if (strcmp(property, "ro.camera.sound.forced") == 0) {
413 ALOGV("ENFORCED_AUDIBLE cannot be muted");
414 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
416 ALOGV("ENFORCED_AUDIBLE can be muted");
417 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
422 audio_module_handle_t AudioPolicyManagerBase::getModuleForDirectoutput(audio_devices_t device,
423 uint32_t samplingRate,
425 uint32_t channelMask,
426 audio_output_flags_t flags)
428 for (size_t i = 0; i < mHwModules.size(); i++) {
429 if (mHwModules[i]->mHandle == 0) {
432 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
433 if (mHwModules[i]->mOutputProfiles[j]->isCompatibleProfile(device, samplingRate, format,
434 channelMask, flags)) {
435 return mHwModules[i]->mHandle;
442 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
443 uint32_t samplingRate,
445 uint32_t channelMask,
446 AudioSystem::output_flags flags)
448 audio_io_handle_t output = 0;
449 uint32_t latency = 0;
450 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
451 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
452 ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
453 stream, samplingRate, format, channelMask, flags);
455 #ifdef AUDIO_POLICY_TEST
456 if (mCurOutput != 0) {
457 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
458 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
460 if (mTestOutputs[mCurOutput] == 0) {
461 ALOGV("getOutput() opening test output");
462 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
463 outputDesc->mDevice = mTestDevice;
464 outputDesc->mSamplingRate = mTestSamplingRate;
465 outputDesc->mFormat = mTestFormat;
466 outputDesc->mChannelMask = mTestChannels;
467 outputDesc->mLatency = mTestLatencyMs;
468 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
469 outputDesc->mRefCount[stream] = 0;
470 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
471 &outputDesc->mSamplingRate,
472 &outputDesc->mFormat,
473 &outputDesc->mChannelMask,
474 &outputDesc->mLatency,
476 if (mTestOutputs[mCurOutput]) {
477 AudioParameter outputCmd = AudioParameter();
478 outputCmd.addInt(String8("set_id"),mCurOutput);
479 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
480 addOutput(mTestOutputs[mCurOutput], outputDesc);
483 return mTestOutputs[mCurOutput];
485 #endif //AUDIO_POLICY_TEST
487 // open a direct output if required by specified parameters
488 if (needsDirectOuput((audio_stream_type_t)stream,
490 (audio_format_t)format,
491 (audio_channel_mask_t)channelMask,
492 (audio_output_flags_t)flags,
495 ALOGV("getOutput() opening direct output device %x", device);
497 audio_module_handle_t module = getModuleForDirectoutput(device,
501 (audio_output_flags_t)flags);
505 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
506 outputDesc->mDevice = device;
507 outputDesc->mSamplingRate = samplingRate;
508 outputDesc->mFormat = (audio_format_t)format;
509 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
510 outputDesc->mLatency = 0;
511 outputDesc->mFlags = (audio_output_flags_t)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
512 outputDesc->mRefCount[stream] = 0;
513 outputDesc->mStopTime[stream] = 0;
514 output = mpClientInterface->openOutput(module,
515 &outputDesc->mDevice,
516 &outputDesc->mSamplingRate,
517 &outputDesc->mFormat,
518 &outputDesc->mChannelMask,
519 &outputDesc->mLatency,
522 // only accept an output with the requested parameters
524 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
525 (format != 0 && format != outputDesc->mFormat) ||
526 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
527 ALOGV("getOutput() failed opening direct output: samplingRate %d,"
528 "format %d, channelMask %d", samplingRate, format, channelMask);
530 mpClientInterface->closeOutput(output);
535 addOutput(output, outputDesc);
539 // ignoring channel mask due to downmix capability in mixer
541 // open a non direct output
543 // get which output is suitable for the specified stream. The actual routing change will happen
544 // when startOutput() will be called
545 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device);
547 output = selectOutput(outputs, flags);
549 ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
550 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
552 ALOGV("getOutput() returns output %d", output);
557 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
558 AudioSystem::output_flags flags)
560 // select one output among several that provide a path to a particular device or set of
561 // devices (the list was previously build by getOutputsForDevice()).
562 // The priority is as follows:
563 // 1: the output with the highest number of requested policy flags
564 // 2: the primary output
565 // 3: the first output in the list
567 if (outputs.size() == 0) {
570 if (outputs.size() == 1) {
574 int maxCommonFlags = 0;
575 audio_io_handle_t outputFlags = 0;
576 audio_io_handle_t outputPrimary = 0;
578 for (size_t i = 0; i < outputs.size(); i++) {
579 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
580 if (!outputDesc->isDuplicated()) {
581 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
582 if (commonFlags > maxCommonFlags) {
583 outputFlags = outputs[i];
584 maxCommonFlags = commonFlags;
585 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
587 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
588 outputPrimary = outputs[i];
593 if (outputFlags != 0) {
596 if (outputPrimary != 0) {
597 return outputPrimary;
603 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
604 AudioSystem::stream_type stream,
607 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
608 ssize_t index = mOutputs.indexOfKey(output);
610 ALOGW("startOutput() unknow output %d", output);
614 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
616 // increment usage count for this stream on the requested output:
617 // NOTE that the usage count is the same for duplicated output and hardware output which is
618 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
619 outputDesc->changeRefCount(stream, 1);
621 if (outputDesc->mRefCount[stream] == 1) {
622 audio_devices_t prevDevice = outputDesc->device();
623 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
624 routing_strategy strategy = getStrategy(stream);
625 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
626 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
629 for (size_t i = 0; i < mOutputs.size(); i++) {
630 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
631 if (desc != outputDesc) {
632 // force a device change if any other output is managed by the same hw
633 // module and has a current device selection that differs from selected device.
634 // In this case, the audio HAL must receive the new device selection so that it can
635 // change the device currently selected by the other active output.
636 if (outputDesc->sharesHwModuleWith(desc) &&
637 desc->device() != newDevice) {
640 // wait for audio on other active outputs to be presented when starting
641 // a notification so that audio focus effect can propagate.
642 if (shouldWait && (desc->refCount() != 0) && (waitMs < desc->latency())) {
643 waitMs = desc->latency();
647 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
649 // handle special case for sonification while in call
651 handleIncallSonification(stream, true, false);
654 // apply volume rules for current stream and device if necessary
655 checkAndSetVolume(stream,
656 mStreams[stream].getVolumeIndex((audio_devices_t)newDevice),
660 // update the outputs if starting an output with a stream that can affect notification
662 handleNotificationRoutingForStream(stream);
663 if (waitMs > muteWaitMs) {
664 usleep((waitMs - muteWaitMs) * 2 * 1000);
671 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
672 AudioSystem::stream_type stream,
675 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
676 ssize_t index = mOutputs.indexOfKey(output);
678 ALOGW("stopOutput() unknow output %d", output);
682 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
684 // handle special case for sonification while in call
686 handleIncallSonification(stream, false, false);
689 if (outputDesc->mRefCount[stream] > 0) {
690 // decrement usage count of this stream on the output
691 outputDesc->changeRefCount(stream, -1);
692 // store time at which the stream was stopped - see isStreamActive()
693 if (outputDesc->mRefCount[stream] == 0) {
694 outputDesc->mStopTime[stream] = systemTime();
695 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
696 // delay the device switch by twice the latency because stopOutput() is executed when
697 // the track stop() command is received and at that time the audio track buffer can
698 // still contain data that needs to be drained. The latency only covers the audio HAL
699 // and kernel buffers. Also the latency does not always include additional delay in the
700 // audio path (audio DSP, CODEC ...)
701 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
703 // force restoring the device selection on other active outputs if it differs from the
704 // one being selected for this output
705 for (size_t i = 0; i < mOutputs.size(); i++) {
706 audio_io_handle_t curOutput = mOutputs.keyAt(i);
707 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
708 if (curOutput != output &&
709 desc->refCount() != 0 &&
710 outputDesc->sharesHwModuleWith(desc) &&
711 newDevice != desc->device()) {
712 setOutputDevice(curOutput,
713 getNewDevice(curOutput, false /*fromCache*/),
715 outputDesc->mLatency*2);
718 // update the outputs if stopping one with a stream that can affect notification routing
719 handleNotificationRoutingForStream(stream);
723 ALOGW("stopOutput() refcount is already 0 for output %d", output);
724 return INVALID_OPERATION;
728 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
730 ALOGV("releaseOutput() %d", output);
731 ssize_t index = mOutputs.indexOfKey(output);
733 ALOGW("releaseOutput() releasing unknown output %d", output);
737 #ifdef AUDIO_POLICY_TEST
738 int testIndex = testOutputIndex(output);
739 if (testIndex != 0) {
740 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
741 if (outputDesc->refCount() == 0) {
742 mpClientInterface->closeOutput(output);
743 delete mOutputs.valueAt(index);
744 mOutputs.removeItem(output);
745 mTestOutputs[testIndex] = 0;
749 #endif //AUDIO_POLICY_TEST
751 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
752 mpClientInterface->closeOutput(output);
753 delete mOutputs.valueAt(index);
754 mOutputs.removeItem(output);
759 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
760 uint32_t samplingRate,
762 uint32_t channelMask,
763 AudioSystem::audio_in_acoustics acoustics)
765 audio_io_handle_t input = 0;
766 audio_devices_t device = getDeviceForInputSource(inputSource);
768 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
769 inputSource, samplingRate, format, channelMask, acoustics);
772 ALOGW("getInput() could not find device for inputSource %d", inputSource);
776 // adapt channel selection to input source
777 switch(inputSource) {
778 case AUDIO_SOURCE_VOICE_UPLINK:
779 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
781 case AUDIO_SOURCE_VOICE_DOWNLINK:
782 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
784 case AUDIO_SOURCE_VOICE_CALL:
785 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
791 IOProfile *profile = getInputProfile(device,
795 if (profile == NULL) {
796 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
798 device, samplingRate, format, channelMask);
802 if (profile->mModule->mHandle == 0) {
803 ALOGE("checkOutputForDevice(): could not open HW module %s",
804 profile->mModule->mName);
808 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
810 inputDesc->mInputSource = inputSource;
811 inputDesc->mDevice = device;
812 inputDesc->mSamplingRate = samplingRate;
813 inputDesc->mFormat = (audio_format_t)format;
814 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
815 inputDesc->mRefCount = 0;
816 input = mpClientInterface->openInput(profile->mModule->mHandle,
818 &inputDesc->mSamplingRate,
820 &inputDesc->mChannelMask);
822 // only accept input with the exact requested set of parameters
824 (samplingRate != inputDesc->mSamplingRate) ||
825 (format != inputDesc->mFormat) ||
826 (channelMask != inputDesc->mChannelMask)) {
827 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
828 samplingRate, format, channelMask);
830 mpClientInterface->closeInput(input);
835 mInputs.add(input, inputDesc);
839 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
841 ALOGV("startInput() input %d", input);
842 ssize_t index = mInputs.indexOfKey(input);
844 ALOGW("startInput() unknow input %d", input);
847 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
849 #ifdef AUDIO_POLICY_TEST
851 #endif //AUDIO_POLICY_TEST
853 // refuse 2 active AudioRecord clients at the same time
854 if (getActiveInput() != 0) {
855 ALOGW("startInput() input %d failed: other input already started", input);
856 return INVALID_OPERATION;
860 AudioParameter param = AudioParameter();
861 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
863 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
864 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
866 mpClientInterface->setParameters(input, param.toString());
868 inputDesc->mRefCount = 1;
872 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
874 ALOGV("stopInput() input %d", input);
875 ssize_t index = mInputs.indexOfKey(input);
877 ALOGW("stopInput() unknow input %d", input);
880 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
882 if (inputDesc->mRefCount == 0) {
883 ALOGW("stopInput() input %d already stopped", input);
884 return INVALID_OPERATION;
886 AudioParameter param = AudioParameter();
887 param.addInt(String8(AudioParameter::keyRouting), 0);
888 mpClientInterface->setParameters(input, param.toString());
889 inputDesc->mRefCount = 0;
894 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
896 ALOGV("releaseInput() %d", input);
897 ssize_t index = mInputs.indexOfKey(input);
899 ALOGW("releaseInput() releasing unknown input %d", input);
902 mpClientInterface->closeInput(input);
903 delete mInputs.valueAt(index);
904 mInputs.removeItem(input);
905 ALOGV("releaseInput() exit");
908 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
912 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
913 if (indexMin < 0 || indexMin >= indexMax) {
914 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
917 mStreams[stream].mIndexMin = indexMin;
918 mStreams[stream].mIndexMax = indexMax;
921 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
923 audio_devices_t device)
926 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
929 if (!audio_is_output_device(device)) {
933 // Force max volume if stream cannot be muted
934 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
936 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
937 stream, device, index);
939 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
940 // clear all device specific values
941 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
942 mStreams[stream].mIndexCur.clear();
944 mStreams[stream].mIndexCur.add(device, index);
946 // compute and apply stream volume on all outputs according to connected device
947 status_t status = NO_ERROR;
948 for (size_t i = 0; i < mOutputs.size(); i++) {
949 audio_devices_t curDevice =
950 getDeviceForVolume((audio_devices_t)mOutputs.valueAt(i)->device());
951 if (device == curDevice) {
952 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
953 if (volStatus != NO_ERROR) {
961 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
963 audio_devices_t device)
968 if (!audio_is_output_device(device)) {
971 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
972 // the strategy the stream belongs to.
973 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
974 device = (audio_devices_t)getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
976 device = getDeviceForVolume(device);
978 *index = mStreams[stream].getVolumeIndex(device);
979 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
983 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
985 ALOGV("getOutputForEffect()");
986 // apply simple rule where global effects are attached to the same output as MUSIC streams
987 return getOutput(AudioSystem::MUSIC);
990 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
991 audio_io_handle_t io,
996 ssize_t index = mOutputs.indexOfKey(io);
998 index = mInputs.indexOfKey(io);
1000 ALOGW("registerEffect() unknown io %d", io);
1001 return INVALID_OPERATION;
1005 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1006 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1007 desc->name, desc->memoryUsage);
1008 return INVALID_OPERATION;
1010 mTotalEffectsMemory += desc->memoryUsage;
1011 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1012 desc->name, io, strategy, session, id);
1013 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1015 EffectDescriptor *pDesc = new EffectDescriptor();
1016 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1018 pDesc->mStrategy = (routing_strategy)strategy;
1019 pDesc->mSession = session;
1020 pDesc->mEnabled = false;
1022 mEffects.add(id, pDesc);
1027 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1029 ssize_t index = mEffects.indexOfKey(id);
1031 ALOGW("unregisterEffect() unknown effect ID %d", id);
1032 return INVALID_OPERATION;
1035 EffectDescriptor *pDesc = mEffects.valueAt(index);
1037 setEffectEnabled(pDesc, false);
1039 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1040 ALOGW("unregisterEffect() memory %d too big for total %d",
1041 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1042 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1044 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1045 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1046 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1048 mEffects.removeItem(id);
1054 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1056 ssize_t index = mEffects.indexOfKey(id);
1058 ALOGW("unregisterEffect() unknown effect ID %d", id);
1059 return INVALID_OPERATION;
1062 return setEffectEnabled(mEffects.valueAt(index), enabled);
1065 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1067 if (enabled == pDesc->mEnabled) {
1068 ALOGV("setEffectEnabled(%s) effect already %s",
1069 enabled?"true":"false", enabled?"enabled":"disabled");
1070 return INVALID_OPERATION;
1074 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1075 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1076 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1077 return INVALID_OPERATION;
1079 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1080 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1082 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1083 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1084 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1085 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1087 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1088 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1090 pDesc->mEnabled = enabled;
1094 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1096 nsecs_t sysTime = systemTime();
1097 for (size_t i = 0; i < mOutputs.size(); i++) {
1098 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
1099 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
1107 status_t AudioPolicyManagerBase::dump(int fd)
1109 const size_t SIZE = 256;
1113 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1114 result.append(buffer);
1116 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1117 result.append(buffer);
1118 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1119 result.append(buffer);
1120 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1123 result.append(buffer);
1124 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1125 result.append(buffer);
1126 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1127 result.append(buffer);
1128 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1129 result.append(buffer);
1130 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1131 result.append(buffer);
1132 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1133 result.append(buffer);
1134 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1137 result.append(buffer);
1138 write(fd, result.string(), result.size());
1141 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1142 write(fd, buffer, strlen(buffer));
1143 for (size_t i = 0; i < mHwModules.size(); i++) {
1144 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1145 write(fd, buffer, strlen(buffer));
1146 mHwModules[i]->dump(fd);
1149 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1150 write(fd, buffer, strlen(buffer));
1151 for (size_t i = 0; i < mOutputs.size(); i++) {
1152 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1153 write(fd, buffer, strlen(buffer));
1154 mOutputs.valueAt(i)->dump(fd);
1157 snprintf(buffer, SIZE, "\nInputs dump:\n");
1158 write(fd, buffer, strlen(buffer));
1159 for (size_t i = 0; i < mInputs.size(); i++) {
1160 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1161 write(fd, buffer, strlen(buffer));
1162 mInputs.valueAt(i)->dump(fd);
1165 snprintf(buffer, SIZE, "\nStreams dump:\n");
1166 write(fd, buffer, strlen(buffer));
1167 snprintf(buffer, SIZE,
1168 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1169 write(fd, buffer, strlen(buffer));
1170 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1171 snprintf(buffer, SIZE, " %02d ", i);
1172 write(fd, buffer, strlen(buffer));
1173 mStreams[i].dump(fd);
1176 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1177 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1178 write(fd, buffer, strlen(buffer));
1180 snprintf(buffer, SIZE, "Registered effects:\n");
1181 write(fd, buffer, strlen(buffer));
1182 for (size_t i = 0; i < mEffects.size(); i++) {
1183 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1184 write(fd, buffer, strlen(buffer));
1185 mEffects.valueAt(i)->dump(fd);
1192 // ----------------------------------------------------------------------------
1193 // AudioPolicyManagerBase
1194 // ----------------------------------------------------------------------------
1196 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1198 #ifdef AUDIO_POLICY_TEST
1200 #endif //AUDIO_POLICY_TEST
1201 mPrimaryOutput((audio_io_handle_t)0),
1202 mAvailableOutputDevices((audio_devices_t)0),
1203 mPhoneState(AudioSystem::MODE_NORMAL),
1204 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1205 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1206 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false)
1208 mpClientInterface = clientInterface;
1210 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1211 mForceUse[i] = AudioSystem::FORCE_NONE;
1214 initializeVolumeCurves();
1216 mA2dpDeviceAddress = String8("");
1217 mScoDeviceAddress = String8("");
1218 mUsbCardAndDevice = String8("");
1220 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1221 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1222 ALOGE("could not load audio policy configuration file");
1226 // open all output streams needed to access attached devices
1227 for (size_t i = 0; i < mHwModules.size(); i++) {
1228 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1229 if (mHwModules[i]->mHandle == 0) {
1230 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1233 // open all output streams needed to access attached devices
1234 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1236 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1238 if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1239 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1241 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1242 outProfile->mSupportedDevices);
1243 outputDesc->mSamplingRate = outProfile->mSamplingRates[0];
1244 outputDesc->mFormat = outProfile->mFormats[0];
1245 outputDesc->mChannelMask = outProfile->mChannelMasks[0];
1246 outputDesc->mFlags = outProfile->mFlags;
1247 audio_io_handle_t output = mpClientInterface->openOutput(
1248 outProfile->mModule->mHandle,
1249 &outputDesc->mDevice,
1250 &outputDesc->mSamplingRate,
1251 &outputDesc->mFormat,
1252 &outputDesc->mChannelMask,
1253 &outputDesc->mLatency,
1254 outputDesc->mFlags);
1258 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1259 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1260 if (mPrimaryOutput == 0 &&
1261 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1262 mPrimaryOutput = output;
1264 addOutput(output, outputDesc);
1265 setOutputDevice(output,
1266 (audio_devices_t)(mDefaultOutputDevice &
1267 outProfile->mSupportedDevices),
1274 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1275 "Not output found for attached devices %08x",
1276 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1278 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1280 updateDeviceForStrategy();
1281 #ifdef AUDIO_POLICY_TEST
1282 if (mPrimaryOutput != 0) {
1283 AudioParameter outputCmd = AudioParameter();
1284 outputCmd.addInt(String8("set_id"), 0);
1285 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1287 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1288 mTestSamplingRate = 44100;
1289 mTestFormat = AudioSystem::PCM_16_BIT;
1290 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1293 mDirectOutput = false;
1294 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1295 mTestOutputs[i] = 0;
1298 const size_t SIZE = 256;
1300 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1301 run(buffer, ANDROID_PRIORITY_AUDIO);
1303 #endif //AUDIO_POLICY_TEST
1306 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1308 #ifdef AUDIO_POLICY_TEST
1310 #endif //AUDIO_POLICY_TEST
1311 for (size_t i = 0; i < mOutputs.size(); i++) {
1312 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1313 delete mOutputs.valueAt(i);
1315 for (size_t i = 0; i < mInputs.size(); i++) {
1316 mpClientInterface->closeInput(mInputs.keyAt(i));
1317 delete mInputs.valueAt(i);
1319 for (size_t i = 0; i < mHwModules.size(); i++) {
1320 delete mHwModules[i];
1324 status_t AudioPolicyManagerBase::initCheck()
1326 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1329 #ifdef AUDIO_POLICY_TEST
1330 bool AudioPolicyManagerBase::threadLoop()
1332 ALOGV("entering threadLoop()");
1333 while (!exitPending())
1339 Mutex::Autolock _l(mLock);
1340 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1342 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1343 AudioParameter param = AudioParameter(command);
1345 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1347 ALOGV("Test command %s received", command.string());
1349 if (param.get(String8("target"), target) != NO_ERROR) {
1352 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1353 param.remove(String8("test_cmd_policy_output"));
1354 mCurOutput = valueInt;
1356 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1357 param.remove(String8("test_cmd_policy_direct"));
1358 if (value == "false") {
1359 mDirectOutput = false;
1360 } else if (value == "true") {
1361 mDirectOutput = true;
1364 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1365 param.remove(String8("test_cmd_policy_input"));
1366 mTestInput = valueInt;
1369 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1370 param.remove(String8("test_cmd_policy_format"));
1371 int format = AudioSystem::INVALID_FORMAT;
1372 if (value == "PCM 16 bits") {
1373 format = AudioSystem::PCM_16_BIT;
1374 } else if (value == "PCM 8 bits") {
1375 format = AudioSystem::PCM_8_BIT;
1376 } else if (value == "Compressed MP3") {
1377 format = AudioSystem::MP3;
1379 if (format != AudioSystem::INVALID_FORMAT) {
1380 if (target == "Manager") {
1381 mTestFormat = format;
1382 } else if (mTestOutputs[mCurOutput] != 0) {
1383 AudioParameter outputParam = AudioParameter();
1384 outputParam.addInt(String8("format"), format);
1385 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1389 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1390 param.remove(String8("test_cmd_policy_channels"));
1393 if (value == "Channels Stereo") {
1394 channels = AudioSystem::CHANNEL_OUT_STEREO;
1395 } else if (value == "Channels Mono") {
1396 channels = AudioSystem::CHANNEL_OUT_MONO;
1398 if (channels != 0) {
1399 if (target == "Manager") {
1400 mTestChannels = channels;
1401 } else if (mTestOutputs[mCurOutput] != 0) {
1402 AudioParameter outputParam = AudioParameter();
1403 outputParam.addInt(String8("channels"), channels);
1404 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1408 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1409 param.remove(String8("test_cmd_policy_sampleRate"));
1410 if (valueInt >= 0 && valueInt <= 96000) {
1411 int samplingRate = valueInt;
1412 if (target == "Manager") {
1413 mTestSamplingRate = samplingRate;
1414 } else if (mTestOutputs[mCurOutput] != 0) {
1415 AudioParameter outputParam = AudioParameter();
1416 outputParam.addInt(String8("sampling_rate"), samplingRate);
1417 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1422 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1423 param.remove(String8("test_cmd_policy_reopen"));
1425 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1426 mpClientInterface->closeOutput(mPrimaryOutput);
1428 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1430 delete mOutputs.valueFor(mPrimaryOutput);
1431 mOutputs.removeItem(mPrimaryOutput);
1433 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1434 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1435 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1436 &outputDesc->mDevice,
1437 &outputDesc->mSamplingRate,
1438 &outputDesc->mFormat,
1439 &outputDesc->mChannelMask,
1440 &outputDesc->mLatency,
1441 outputDesc->mFlags);
1442 if (mPrimaryOutput == 0) {
1443 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1444 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1446 AudioParameter outputCmd = AudioParameter();
1447 outputCmd.addInt(String8("set_id"), 0);
1448 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1449 addOutput(mPrimaryOutput, outputDesc);
1454 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1460 void AudioPolicyManagerBase::exit()
1463 AutoMutex _l(mLock);
1465 mWaitWorkCV.signal();
1467 requestExitAndWait();
1470 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1472 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1473 if (output == mTestOutputs[i]) return i;
1477 #endif //AUDIO_POLICY_TEST
1481 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1483 outputDesc->mId = id;
1484 mOutputs.add(id, outputDesc);
1488 audio_io_handle_t AudioPolicyManagerBase::checkOutputForDevice(
1489 audio_devices_t device,
1490 AudioSystem::device_connection_state state)
1492 audio_io_handle_t output = 0;
1493 AudioOutputDescriptor *outputDesc;
1495 // TODO handle multiple outputs supporting overlapping sets of devices.
1497 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1498 // first check if one output already open can be routed to this device
1499 for (size_t i = 0; i < mOutputs.size(); i++) {
1500 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1501 if (outputDesc->mProfile && outputDesc->mProfile->mSupportedDevices & device) {
1502 return mOutputs.keyAt(i);
1505 // then look for one available output that can be routed to this device
1506 const IOProfile *outProfile = NULL;
1507 for (size_t i = 0; i < mHwModules.size(); i++)
1509 if (mHwModules[i]->mHandle == 0) {
1512 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1514 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1515 outProfile = mHwModules[i]->mOutputProfiles[j];
1519 if (outProfile != NULL) {
1524 if (outProfile == NULL) {
1525 ALOGW("checkOutputForDevice(): No output available for device %04x", device);
1529 if (outProfile->mModule->mHandle == 0) {
1530 ALOGE("checkOutputForDevice(): could not open HW module %s",
1531 outProfile->mModule->mName);
1535 ALOGV("opening output for device %08x", device);
1536 outputDesc = new AudioOutputDescriptor(outProfile);
1537 outputDesc->mDevice = device;
1538 output = mpClientInterface->openOutput(outProfile->mModule->mHandle,
1539 &outputDesc->mDevice,
1540 &outputDesc->mSamplingRate,
1541 &outputDesc->mFormat,
1542 &outputDesc->mChannelMask,
1543 &outputDesc->mLatency,
1544 outputDesc->mFlags);
1547 audio_io_handle_t duplicatedOutput = 0;
1548 // add output descriptor
1549 addOutput(output, outputDesc);
1550 // set initial stream volume for device
1551 applyStreamVolumes(output, device);
1553 //TODO: configure audio effect output stage here
1555 // open a duplicating output thread for the new output and the primary output
1556 duplicatedOutput = mpClientInterface->openDuplicateOutput(output, mPrimaryOutput);
1557 if (duplicatedOutput != 0) {
1558 // add duplicated output descriptor
1559 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1560 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1561 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1562 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1563 dupOutputDesc->mFormat = outputDesc->mFormat;
1564 dupOutputDesc->mChannelMask = outputDesc->mChannelMask;
1565 dupOutputDesc->mLatency = outputDesc->mLatency;
1566 addOutput(duplicatedOutput, dupOutputDesc);
1567 applyStreamVolumes(duplicatedOutput, device);
1569 ALOGW("getOutput() could not open duplicated output for %d and %d",
1570 mPrimaryOutput, output);
1571 mpClientInterface->closeOutput(output);
1572 mOutputs.removeItem(output);
1577 ALOGW("checkOutputForDevice() could not open output for device %x", device);
1582 // we assume that one given device is supported by zero or one output
1583 // check if one opened output is not needed any more after disconnecting one device
1584 for (size_t i = 0; i < mOutputs.size(); i++) {
1585 outputDesc = mOutputs.valueAt(i);
1586 if (outputDesc->mProfile &&
1587 !(outputDesc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1588 output = mOutputs.keyAt(i);
1597 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1599 ALOGV("closeOutput(%d)", output);
1601 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1602 if (outputDesc == NULL) {
1603 ALOGW("closeOutput() unknown output %d", output);
1607 // look for duplicated outputs connected to the output being removed.
1608 for (size_t i = 0; i < mOutputs.size(); i++) {
1609 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1610 if (dupOutputDesc->isDuplicated() &&
1611 (dupOutputDesc->mOutput1 == outputDesc ||
1612 dupOutputDesc->mOutput2 == outputDesc)) {
1613 AudioOutputDescriptor *outputDesc2;
1614 if (dupOutputDesc->mOutput1 == outputDesc) {
1615 outputDesc2 = dupOutputDesc->mOutput2;
1617 outputDesc2 = dupOutputDesc->mOutput1;
1619 // As all active tracks on duplicated output will be deleted,
1620 // and as they were also referenced on the other output, the reference
1621 // count for their stream type must be adjusted accordingly on
1622 // the other output.
1623 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1624 int refCount = dupOutputDesc->mRefCount[j];
1625 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1627 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1628 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1630 mpClientInterface->closeOutput(duplicatedOutput);
1631 delete mOutputs.valueFor(duplicatedOutput);
1632 mOutputs.removeItem(duplicatedOutput);
1636 AudioParameter param;
1637 param.add(String8("closing"), String8("true"));
1638 mpClientInterface->setParameters(output, param.toString());
1640 mpClientInterface->closeOutput(output);
1641 delete mOutputs.valueFor(output);
1642 mOutputs.removeItem(output);
1645 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device)
1647 SortedVector<audio_io_handle_t> outputs;
1649 ALOGV("getOutputsForDevice() device %04x", device);
1650 for (size_t i = 0; i < mOutputs.size(); i++) {
1651 ALOGV("output %d isDuplicated=%d device=%04x",
1652 i, mOutputs.valueAt(i)->isDuplicated(), mOutputs.valueAt(i)->supportedDevices());
1653 if ((device & mOutputs.valueAt(i)->supportedDevices()) == device) {
1654 ALOGV("getOutputsForDevice() found output %d", mOutputs.keyAt(i));
1655 outputs.add(mOutputs.keyAt(i));
1661 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1662 SortedVector<audio_io_handle_t>& outputs2)
1664 if (outputs1.size() != outputs2.size()) {
1667 for (size_t i = 0; i < outputs1.size(); i++) {
1668 if (outputs1[i] != outputs2[i]) {
1675 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1677 SortedVector<audio_io_handle_t> srcOutputs =
1678 getOutputsForDevice(getDeviceForStrategy(strategy, true /*fromCache*/));
1679 SortedVector<audio_io_handle_t> dstOutputs =
1680 getOutputsForDevice(getDeviceForStrategy(strategy, false /*fromCache*/));
1682 if (!vectorsEqual(srcOutputs,dstOutputs)) {
1683 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1684 strategy, srcOutputs[0], dstOutputs[0]);
1685 // mute strategy while moving tracks from one output to another
1686 for (size_t i = 0; i < srcOutputs.size(); i++) {
1687 setStrategyMute(strategy, true, srcOutputs[i]);
1688 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS);
1691 // Move effects associated to this strategy from previous output to new output
1692 //FIXME: removing this code works for effects applied to a particular session as they will be
1693 // re-connected when the tracks are re-created after being invalidated.
1694 // However we need to define a policy for global effects when more than one output is possible
1695 // for (size_t i = 0; i < mEffects.size(); i++) {
1696 // EffectDescriptor *desc = mEffects.valueAt(i);
1697 // if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1698 // desc->mStrategy == strategy &&
1699 // desc->mIo == srcOutputs[0]) {
1700 // ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1701 // mEffects.keyAt(i), dstOutputs[0]);
1702 // mpClientInterface->moveEffects(desc->mSession, srcOutputs[0], dstOutputs[0]);
1703 // desc->mIo = dstOutputs[0];
1706 // Move tracks associated to this strategy from previous output to new output
1707 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1708 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1709 //FIXME see fixme on name change
1710 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutputs[0]);
1716 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1718 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1719 checkOutputForStrategy(STRATEGY_PHONE);
1720 checkOutputForStrategy(STRATEGY_SONIFICATION);
1721 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1722 checkOutputForStrategy(STRATEGY_MEDIA);
1723 checkOutputForStrategy(STRATEGY_DTMF);
1726 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1732 for (size_t i = 0; i < mOutputs.size(); i++) {
1733 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1734 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1735 return mOutputs.keyAt(i);
1742 void AudioPolicyManagerBase::checkA2dpSuspend()
1747 audio_io_handle_t a2dpOutput = getA2dpOutput();
1748 if (a2dpOutput == 0) {
1752 // suspend A2DP output if:
1753 // (NOT already suspended) &&
1754 // ((SCO device is connected &&
1755 // (forced usage for communication || for record is SCO))) ||
1756 // (phone state is ringing || in call)
1758 // restore A2DP output if:
1759 // (Already suspended) &&
1760 // ((SCO device is NOT connected ||
1761 // (forced usage NOT for communication && NOT for record is SCO))) &&
1762 // (phone state is NOT ringing && NOT in call)
1764 if (mA2dpSuspended) {
1765 if (((mScoDeviceAddress == "") ||
1766 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1767 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1768 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1769 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1771 mpClientInterface->restoreOutput(a2dpOutput);
1772 mA2dpSuspended = false;
1775 if (((mScoDeviceAddress != "") &&
1776 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1777 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1778 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1779 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1781 mpClientInterface->suspendOutput(a2dpOutput);
1782 mA2dpSuspended = true;
1787 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1789 audio_devices_t device = (audio_devices_t)0;
1791 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1792 // check the following by order of priority to request a routing change if necessary:
1793 // 1: the strategy enforced audible is active on the output:
1794 // use device for strategy enforced audible
1795 // 2: we are in call or the strategy phone is active on the output:
1796 // use device for strategy phone
1797 // 3: the strategy sonification is active on the output:
1798 // use device for strategy sonification
1799 // 4: the strategy "respectful" sonification is active on the output:
1800 // use device for strategy "respectful" sonification
1801 // 5: the strategy media is active on the output:
1802 // use device for strategy media
1803 // 6: the strategy DTMF is active on the output:
1804 // use device for strategy DTMF
1805 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1806 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1807 } else if (isInCall() ||
1808 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1809 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1810 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1811 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1812 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
1813 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
1814 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1815 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1816 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1817 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1820 ALOGV("getNewDevice() selected device %x", device);
1824 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1825 return (uint32_t)getStrategy(stream);
1828 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1829 audio_devices_t devices;
1830 // By checking the range of stream before calling getStrategy, we avoid
1831 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
1832 // and then return STRATEGY_MEDIA, but we want to return the empty set.
1833 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1834 devices = (audio_devices_t)0;
1836 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1837 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
1842 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1843 AudioSystem::stream_type stream) {
1844 // stream to strategy mapping
1846 case AudioSystem::VOICE_CALL:
1847 case AudioSystem::BLUETOOTH_SCO:
1848 return STRATEGY_PHONE;
1849 case AudioSystem::RING:
1850 case AudioSystem::ALARM:
1851 return STRATEGY_SONIFICATION;
1852 case AudioSystem::NOTIFICATION:
1853 return STRATEGY_SONIFICATION_RESPECTFUL;
1854 case AudioSystem::DTMF:
1855 return STRATEGY_DTMF;
1857 ALOGE("unknown stream type");
1858 case AudioSystem::SYSTEM:
1859 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1860 // while key clicks are played produces a poor result
1861 case AudioSystem::TTS:
1862 case AudioSystem::MUSIC:
1863 return STRATEGY_MEDIA;
1864 case AudioSystem::ENFORCED_AUDIBLE:
1865 return STRATEGY_ENFORCED_AUDIBLE;
1869 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
1871 case AudioSystem::MUSIC:
1872 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1873 updateDeviceForStrategy();
1880 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
1883 uint32_t device = 0;
1886 ALOGV("getDeviceForStrategy() from cache strategy %d, device %x",
1887 strategy, mDeviceForStrategy[strategy]);
1888 return mDeviceForStrategy[strategy];
1893 case STRATEGY_SONIFICATION_RESPECTFUL:
1895 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
1896 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
1897 // while media is playing (or has recently played), use the same device
1898 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1900 // when media is not playing anymore, fall back on the sonification behavior
1901 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
1908 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1909 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1912 // when in call, DTMF and PHONE strategies follow the same rules
1915 case STRATEGY_PHONE:
1916 // for phone strategy, we first consider the forced use and then the available devices by order
1918 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1919 case AudioSystem::FORCE_BT_SCO:
1920 if (!isInCall() || strategy != STRATEGY_DTMF) {
1921 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1924 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1926 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1928 // if SCO device is requested but no SCO device is available, fall back to default case
1931 default: // FORCE_NONE
1932 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1934 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1936 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
1937 if (mHasA2dp && !isInCall() && !mA2dpSuspended) {
1938 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1940 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1943 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
1945 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
1947 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1949 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1951 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1953 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1955 device = mDefaultOutputDevice;
1957 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
1961 case AudioSystem::FORCE_SPEAKER:
1962 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1963 // A2DP speaker when forcing to speaker output
1964 if (mHasA2dp && !isInCall() && !mA2dpSuspended) {
1965 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1968 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
1970 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
1972 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1974 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1976 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1978 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1980 device = mDefaultOutputDevice;
1982 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
1988 case STRATEGY_SONIFICATION:
1990 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1991 // handleIncallSonification().
1993 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
1998 case STRATEGY_ENFORCED_AUDIBLE:
1999 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2000 // except when in call where it doesn't default to STRATEGY_PHONE behavior
2002 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2004 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2006 // The second device used for sonification is the same as the device used by media strategy
2009 case STRATEGY_MEDIA: {
2010 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2012 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2014 if (mHasA2dp && (getA2dpOutput() != 0) && !mA2dpSuspended) {
2016 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2019 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2022 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2026 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2029 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2032 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2035 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2038 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2041 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2044 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2045 // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise
2048 device = mDefaultOutputDevice;
2050 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2055 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2059 ALOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2060 return (audio_devices_t)device;
2063 void AudioPolicyManagerBase::updateDeviceForStrategy()
2065 for (int i = 0; i < NUM_STRATEGIES; i++) {
2066 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2070 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2071 audio_devices_t prevDevice,
2074 // mute/unmute strategies using an incompatible device combination
2075 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2076 // if unmuting, unmute only after the specified delay
2077 if (outputDesc->isDuplicated()) {
2081 uint32_t muteWaitMs = 0;
2082 audio_devices_t device = outputDesc->device();
2083 bool shouldMute = (outputDesc->refCount() != 0) &&
2084 (AudioSystem::popCount(device) >= 2);
2085 // temporary mute output if device selection changes to avoid volume bursts due to
2086 // different per device volumes
2087 bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
2089 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2090 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2091 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2092 bool doMute = false;
2094 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2096 outputDesc->mStrategyMutedByDevice[i] = true;
2097 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2099 outputDesc->mStrategyMutedByDevice[i] = false;
2101 if (doMute || tempMute) {
2102 for (size_t j = 0; j < mOutputs.size(); j++) {
2103 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2104 if ((desc->supportedDevices() & outputDesc->supportedDevices()) == 0) {
2107 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2108 ALOGV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2109 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2110 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2111 if (desc->strategyRefCount((routing_strategy)i) != 0) {
2113 setStrategyMute((routing_strategy)i, true, curOutput, 0);
2114 setStrategyMute((routing_strategy)i, false, curOutput, desc->latency() * 2);
2116 if (tempMute || mute) {
2117 if (muteWaitMs < desc->latency()) {
2118 muteWaitMs = desc->latency();
2126 // FIXME: should not need to double latency if volume could be applied immediately by the
2127 // audioflinger mixer. We must account for the delay between now and the next time
2128 // the audioflinger thread for this output will process a buffer (which corresponds to
2129 // one buffer size, usually 1/2 or 1/4 of the latency).
2131 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2132 if (muteWaitMs > delayMs) {
2133 muteWaitMs -= delayMs;
2134 usleep(muteWaitMs * 1000);
2140 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2141 audio_devices_t device,
2145 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2146 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2147 AudioParameter param;
2148 uint32_t muteWaitMs = 0;
2150 if (outputDesc->isDuplicated()) {
2151 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2152 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2155 // filter devices according to output selected
2156 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2158 audio_devices_t prevDevice = outputDesc->mDevice;
2160 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2163 outputDesc->mDevice = device;
2165 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2167 // Do not change the routing if:
2168 // - the requested device is 0
2169 // - the requested device is the same as current device and force is not specified.
2170 // Doing this check here allows the caller to call setOutputDevice() without conditions
2171 if ((device == 0 || device == prevDevice) && !force) {
2172 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2176 ALOGV("setOutputDevice() changing device");
2178 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2179 mpClientInterface->setParameters(output, param.toString(), delayMs);
2181 // update stream volumes according to new device
2182 applyStreamVolumes(output, device, delayMs);
2187 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2188 uint32_t samplingRate,
2190 uint32_t channelMask)
2192 // Choose an input profile based on the requested capture parameters: select the first available
2193 // profile supporting all requested parameters.
2195 for (size_t i = 0; i < mHwModules.size(); i++)
2197 if (mHwModules[i]->mHandle == 0) {
2200 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2202 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2203 if (profile->isCompatibleProfile(device, samplingRate, format,
2204 channelMask,(audio_output_flags_t)0)) {
2212 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2214 uint32_t device = 0;
2216 switch(inputSource) {
2217 case AUDIO_SOURCE_DEFAULT:
2218 case AUDIO_SOURCE_MIC:
2219 case AUDIO_SOURCE_VOICE_RECOGNITION:
2220 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2221 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2222 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2223 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2224 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
2225 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
2226 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2227 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2230 case AUDIO_SOURCE_CAMCORDER:
2231 if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BACK_MIC) {
2232 device = AudioSystem::DEVICE_IN_BACK_MIC;
2233 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2234 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2237 case AUDIO_SOURCE_VOICE_UPLINK:
2238 case AUDIO_SOURCE_VOICE_DOWNLINK:
2239 case AUDIO_SOURCE_VOICE_CALL:
2240 if (mAvailableInputDevices & AudioSystem::DEVICE_IN_VOICE_CALL) {
2241 device = AudioSystem::DEVICE_IN_VOICE_CALL;
2245 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2248 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2249 return (audio_devices_t)device;
2252 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
2254 for (size_t i = 0; i < mInputs.size(); i++) {
2255 if (mInputs.valueAt(i)->mRefCount > 0) {
2256 return mInputs.keyAt(i);
2263 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2266 // this happens when forcing a route update and no track is active on an output.
2267 // In this case the returned category is not important.
2268 device = AUDIO_DEVICE_OUT_SPEAKER;
2269 } else if (AudioSystem::popCount(device) > 1) {
2270 // Multiple device selection is either:
2271 // - speaker + one other device: give priority to speaker in this case.
2272 // - one A2DP device + another device: happens with duplicated output. In this case
2273 // retain the device on the A2DP output as the other must not correspond to an active
2274 // selection if not the speaker.
2275 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2276 device = AUDIO_DEVICE_OUT_SPEAKER;
2278 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2282 ALOGW_IF(AudioSystem::popCount(device) != 1,
2283 "getDeviceForVolume() invalid device combination: %08x",
2289 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2291 switch(getDeviceForVolume(device)) {
2292 case AUDIO_DEVICE_OUT_EARPIECE:
2293 return DEVICE_CATEGORY_EARPIECE;
2294 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2295 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2296 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2297 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2298 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2299 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2300 return DEVICE_CATEGORY_HEADSET;
2301 case AUDIO_DEVICE_OUT_SPEAKER:
2302 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2303 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2304 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2305 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2306 case AUDIO_DEVICE_OUT_USB_DEVICE:
2308 return DEVICE_CATEGORY_SPEAKER;
2312 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2315 device_category deviceCategory = getDeviceCategory(device);
2316 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2318 // the volume index in the UI is relative to the min and max volume indices for this stream type
2319 int nbSteps = 1 + curve[VOLMAX].mIndex -
2320 curve[VOLMIN].mIndex;
2321 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2322 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2324 // find what part of the curve this index volume belongs to, or if it's out of bounds
2326 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2328 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2330 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2332 } else if (volIdx <= curve[VOLMAX].mIndex) {
2334 } else { // out of bounds
2338 // linear interpolation in the attenuation table in dB
2339 float decibels = curve[segment].mDBAttenuation +
2340 ((float)(volIdx - curve[segment].mIndex)) *
2341 ( (curve[segment+1].mDBAttenuation -
2342 curve[segment].mDBAttenuation) /
2343 ((float)(curve[segment+1].mIndex -
2344 curve[segment].mIndex)) );
2346 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2348 ALOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2349 curve[segment].mIndex, volIdx,
2350 curve[segment+1].mIndex,
2351 curve[segment].mDBAttenuation,
2353 curve[segment+1].mDBAttenuation,
2356 return amplification;
2359 const AudioPolicyManagerBase::VolumeCurvePoint
2360 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2361 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2364 const AudioPolicyManagerBase::VolumeCurvePoint
2365 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2366 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2369 const AudioPolicyManagerBase::VolumeCurvePoint
2370 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2371 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2374 const AudioPolicyManagerBase::VolumeCurvePoint
2375 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2376 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2380 const AudioPolicyManagerBase::VolumeCurvePoint
2381 *AudioPolicyManagerBase::sVolumeProfiles[AudioPolicyManagerBase::NUM_STRATEGIES]
2382 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2384 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2385 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2386 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2389 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2390 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2391 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2393 { // STRATEGY_SONIFICATION
2394 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2395 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2396 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2398 { // STRATEGY_SONIFICATION_RESPECTFUL uses same volumes as SONIFICATION
2399 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2400 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2401 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2404 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2405 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2406 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2408 { // STRATEGY_ENFORCED_AUDIBLE
2409 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2410 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2411 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2415 void AudioPolicyManagerBase::initializeVolumeCurves()
2417 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2418 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2419 mStreams[i].mVolumeCurve[j] =
2420 sVolumeProfiles[getStrategy((AudioSystem::stream_type)i)][j];
2425 float AudioPolicyManagerBase::computeVolume(int stream,
2427 audio_io_handle_t output,
2428 audio_devices_t device)
2431 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2432 StreamDescriptor &streamDesc = mStreams[stream];
2435 device = outputDesc->device();
2438 // if volume is not 0 (not muted), force media volume to max on digital output
2439 if (stream == AudioSystem::MUSIC &&
2440 index != mStreams[stream].mIndexMin &&
2441 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2442 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2443 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2444 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2448 volume = volIndexToAmpl(device, streamDesc, index);
2450 // if a headset is connected, apply the following rules to ring tones and notifications
2451 // to avoid sound level bursts in user's ears:
2452 // - always attenuate ring tones and notifications volume by 6dB
2453 // - if music is playing, always limit the volume to current music volume,
2454 // with a minimum threshold at -36dB so that notification is always perceived.
2455 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2456 if ((device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
2457 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2458 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
2459 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
2460 ((stream_strategy == STRATEGY_SONIFICATION)
2461 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2462 || (stream == AudioSystem::SYSTEM)) &&
2463 streamDesc.mCanBeMuted) {
2464 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2465 // when the phone is ringing we must consider that music could have been paused just before
2466 // by the music application and behave as if music was active if the last music track was
2468 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
2469 float musicVol = computeVolume(AudioSystem::MUSIC,
2470 mStreams[AudioSystem::MUSIC].getVolumeIndex(device),
2473 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2474 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2475 if (volume > minVol) {
2477 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2485 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2487 audio_io_handle_t output,
2488 audio_devices_t device,
2493 // do not change actual stream volume if the stream is muted
2494 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2495 ALOGV("checkAndSetVolume() stream %d muted count %d",
2496 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2500 // do not change in call volume if bluetooth is connected and vice versa
2501 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2502 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2503 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2504 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2505 return INVALID_OPERATION;
2508 float volume = computeVolume(stream, index, output, device);
2509 // We actually change the volume if:
2510 // - the float value returned by computeVolume() changed
2511 // - the force flag is set
2512 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2514 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2515 ALOGV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2516 if (stream == AudioSystem::VOICE_CALL ||
2517 stream == AudioSystem::DTMF ||
2518 stream == AudioSystem::BLUETOOTH_SCO) {
2519 // offset value to reflect actual hardware volume that never reaches 0
2520 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2521 volume = 0.01 + 0.99 * volume;
2522 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2524 if (stream == AudioSystem::BLUETOOTH_SCO) {
2525 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2529 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2532 if (stream == AudioSystem::VOICE_CALL ||
2533 stream == AudioSystem::BLUETOOTH_SCO) {
2535 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2536 if (stream == AudioSystem::VOICE_CALL) {
2537 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2542 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2543 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2544 mLastVoiceVolume = voiceVolume;
2551 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2552 audio_devices_t device,
2556 ALOGV("applyStreamVolumes() for output %d and device %x", output, device);
2558 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2559 checkAndSetVolume(stream,
2560 mStreams[stream].getVolumeIndex(device),
2568 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
2570 ALOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2571 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2572 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2573 setStreamMute(stream, on, output, delayMs);
2578 void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
2580 StreamDescriptor &streamDesc = mStreams[stream];
2581 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2582 audio_devices_t device = outputDesc->device();
2584 ALOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
2587 if (outputDesc->mMuteCount[stream] == 0) {
2588 if (streamDesc.mCanBeMuted) {
2589 checkAndSetVolume(stream, 0, output, device, delayMs);
2592 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2593 outputDesc->mMuteCount[stream]++;
2595 if (outputDesc->mMuteCount[stream] == 0) {
2596 ALOGW("setStreamMute() unmuting non muted stream!");
2599 if (--outputDesc->mMuteCount[stream] == 0) {
2600 checkAndSetVolume(stream,
2601 streamDesc.getVolumeIndex((audio_devices_t)device),
2609 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2611 // if the stream pertains to sonification strategy and we are in call we must
2612 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2613 // in the device used for phone strategy and play the tone if the selected device does not
2614 // interfere with the device used for phone strategy
2615 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2616 // many times as there are active tracks on the output
2617 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2618 if ((stream_strategy == STRATEGY_SONIFICATION) ||
2619 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2620 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2621 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2622 stream, starting, outputDesc->mDevice, stateChange);
2623 if (outputDesc->mRefCount[stream]) {
2626 muteCount = outputDesc->mRefCount[stream];
2628 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2629 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2630 for (int i = 0; i < muteCount; i++) {
2631 setStreamMute(stream, starting, mPrimaryOutput);
2634 ALOGV("handleIncallSonification() high visibility");
2635 if (outputDesc->device() &
2636 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2637 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2638 for (int i = 0; i < muteCount; i++) {
2639 setStreamMute(stream, starting, mPrimaryOutput);
2643 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2645 mpClientInterface->stopTone();
2652 bool AudioPolicyManagerBase::isInCall()
2654 return isStateInCall(mPhoneState);
2657 bool AudioPolicyManagerBase::isStateInCall(int state) {
2658 return ((state == AudioSystem::MODE_IN_CALL) ||
2659 (state == AudioSystem::MODE_IN_COMMUNICATION));
2662 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
2663 uint32_t samplingRate,
2664 audio_format_t format,
2665 audio_channel_mask_t channelMask,
2666 audio_output_flags_t flags,
2667 audio_devices_t device)
2669 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2670 (format != 0 && !AudioSystem::isLinearPCM(format)));
2673 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2675 return MAX_EFFECTS_CPU_LOAD;
2678 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2680 return MAX_EFFECTS_MEMORY;
2683 // --- AudioOutputDescriptor class implementation
2685 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2686 const IOProfile *profile)
2687 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
2688 mChannelMask((audio_channel_mask_t)0), mLatency(0),
2689 mFlags((audio_output_flags_t)0), mDevice((audio_devices_t)0),
2690 mOutput1(0), mOutput2(0), mProfile(profile)
2692 // clear usage count for all stream types
2693 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2695 mCurVolume[i] = -1.0;
2701 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2703 if (isDuplicated()) {
2704 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
2710 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
2712 if (isDuplicated()) {
2713 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
2719 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
2720 const AudioOutputDescriptor *outputDesc)
2722 if (isDuplicated()) {
2723 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
2724 } else if (outputDesc->isDuplicated()){
2725 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
2727 return (mProfile->mModule == outputDesc->mProfile->mModule);
2731 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2733 // forward usage count change to attached outputs
2734 if (isDuplicated()) {
2735 mOutput1->changeRefCount(stream, delta);
2736 mOutput2->changeRefCount(stream, delta);
2738 if ((delta + (int)mRefCount[stream]) < 0) {
2739 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2740 mRefCount[stream] = 0;
2743 mRefCount[stream] += delta;
2744 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2747 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2749 uint32_t refcount = 0;
2750 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2751 refcount += mRefCount[i];
2756 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2758 uint32_t refCount = 0;
2759 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2760 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2761 refCount += mRefCount[i];
2767 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
2769 if (isDuplicated()) {
2770 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
2772 return mProfile->mSupportedDevices ;
2776 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2778 const size_t SIZE = 256;
2782 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2783 result.append(buffer);
2784 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2785 result.append(buffer);
2786 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
2787 result.append(buffer);
2788 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2789 result.append(buffer);
2790 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2791 result.append(buffer);
2792 snprintf(buffer, SIZE, " Devices %08x\n", device());
2793 result.append(buffer);
2794 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2795 result.append(buffer);
2796 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2797 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2798 result.append(buffer);
2800 write(fd, result.string(), result.size());
2805 // --- AudioInputDescriptor class implementation
2807 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
2808 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
2809 mDevice((audio_devices_t)0), mRefCount(0),
2810 mInputSource(0), mProfile(profile)
2814 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2816 const size_t SIZE = 256;
2820 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2821 result.append(buffer);
2822 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2823 result.append(buffer);
2824 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
2825 result.append(buffer);
2826 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2827 result.append(buffer);
2828 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2829 result.append(buffer);
2830 write(fd, result.string(), result.size());
2835 // --- StreamDescriptor class implementation
2837 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
2838 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
2840 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
2843 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
2845 device = AudioPolicyManagerBase::getDeviceForVolume(device);
2846 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
2847 if (mIndexCur.indexOfKey(device) < 0) {
2848 device = AUDIO_DEVICE_OUT_DEFAULT;
2850 return mIndexCur.valueFor(device);
2853 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
2855 const size_t SIZE = 256;
2859 snprintf(buffer, SIZE, "%s %02d %02d ",
2860 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
2861 result.append(buffer);
2862 for (size_t i = 0; i < mIndexCur.size(); i++) {
2863 snprintf(buffer, SIZE, "%04x : %02d, ",
2865 mIndexCur.valueAt(i));
2866 result.append(buffer);
2868 result.append("\n");
2870 write(fd, result.string(), result.size());
2873 // --- EffectDescriptor class implementation
2875 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2877 const size_t SIZE = 256;
2881 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
2882 result.append(buffer);
2883 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2884 result.append(buffer);
2885 snprintf(buffer, SIZE, " Session: %d\n", mSession);
2886 result.append(buffer);
2887 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
2888 result.append(buffer);
2889 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
2890 result.append(buffer);
2891 write(fd, result.string(), result.size());
2896 // --- IOProfile class implementation
2898 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
2899 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
2903 AudioPolicyManagerBase::HwModule::~HwModule()
2905 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
2906 delete mOutputProfiles[i];
2908 for (size_t i = 0; i < mInputProfiles.size(); i++) {
2909 delete mInputProfiles[i];
2911 free((void *)mName);
2914 void AudioPolicyManagerBase::HwModule::dump(int fd)
2916 const size_t SIZE = 256;
2920 snprintf(buffer, SIZE, " - name: %s\n", mName);
2921 result.append(buffer);
2922 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
2923 result.append(buffer);
2924 write(fd, result.string(), result.size());
2925 if (mOutputProfiles.size()) {
2926 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
2927 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
2928 snprintf(buffer, SIZE, " output %d:\n", i);
2929 write(fd, buffer, strlen(buffer));
2930 mOutputProfiles[i]->dump(fd);
2933 if (mInputProfiles.size()) {
2934 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
2935 for (size_t i = 0; i < mInputProfiles.size(); i++) {
2936 snprintf(buffer, SIZE, " input %d:\n", i);
2937 write(fd, buffer, strlen(buffer));
2938 mInputProfiles[i]->dump(fd);
2943 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
2944 : mFlags((audio_output_flags_t)0), mModule(module)
2948 AudioPolicyManagerBase::IOProfile::~IOProfile()
2952 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
2953 // means a parameter is don't care
2954 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
2955 uint32_t samplingRate,
2957 uint32_t channelMask,
2958 audio_output_flags_t flags) const
2960 if ((mSupportedDevices & device) != device) {
2963 if ((mFlags & flags) != flags) {
2966 if (samplingRate != 0) {
2968 for (i = 0; i < mSamplingRates.size(); i++)
2970 if (mSamplingRates[i] == samplingRate) {
2974 if (i == mSamplingRates.size()) {
2980 for (i = 0; i < mFormats.size(); i++)
2982 if (mFormats[i] == format) {
2986 if (i == mFormats.size()) {
2990 if (channelMask != 0) {
2992 for (i = 0; i < mChannelMasks.size(); i++)
2994 if (mChannelMasks[i] == channelMask) {
2998 if (i == mChannelMasks.size()) {
3005 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3007 const size_t SIZE = 256;
3011 snprintf(buffer, SIZE, " - sampling rates: ");
3012 result.append(buffer);
3013 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3014 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3015 result.append(buffer);
3016 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3019 snprintf(buffer, SIZE, " - channel masks: ");
3020 result.append(buffer);
3021 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3022 snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3023 result.append(buffer);
3024 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3027 snprintf(buffer, SIZE, " - formats: ");
3028 result.append(buffer);
3029 for (size_t i = 0; i < mFormats.size(); i++) {
3030 snprintf(buffer, SIZE, "%d", mFormats[i]);
3031 result.append(buffer);
3032 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3035 snprintf(buffer, SIZE, " - devices: %04x\n", mSupportedDevices);
3036 result.append(buffer);
3037 snprintf(buffer, SIZE, " - flags: %04x\n", mFlags);
3038 result.append(buffer);
3040 write(fd, result.string(), result.size());
3043 // --- audio_policy.conf file parsing
3045 struct StringToEnum {
3050 #define STRING_TO_ENUM(string) { #string, string }
3051 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3053 const struct StringToEnum sDeviceNameToEnumTable[] = {
3054 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3055 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3056 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3057 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3058 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3059 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3060 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3061 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3062 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3063 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3064 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3065 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3066 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3067 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3068 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3069 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3070 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3071 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3074 const struct StringToEnum sFlagNameToEnumTable[] = {
3075 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3076 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3077 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3078 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3081 const struct StringToEnum sFormatNameToEnumTable[] = {
3082 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3083 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3084 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3085 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3086 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3089 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3090 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3091 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3092 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3093 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3096 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3097 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3098 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3102 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3106 for (size_t i = 0; i < size; i++) {
3107 if (strcmp(table[i].name, name) == 0) {
3108 ALOGV("stringToEnum() found %s", table[i].name);
3109 return table[i].value;
3115 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3119 // it is OK to cast name to non const here as we are not going to use it after
3120 // strtok() modifies it
3121 char *flagName = strtok(name, "|");
3122 while (flagName != NULL) {
3123 if (strlen(flagName) != 0) {
3124 flag |= stringToEnum(sFlagNameToEnumTable,
3125 ARRAY_SIZE(sFlagNameToEnumTable),
3128 flagName = strtok(NULL, "|");
3130 return (audio_output_flags_t)flag;
3133 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3135 uint32_t device = 0;
3137 char *devName = strtok(name, "|");
3138 while (devName != NULL) {
3139 if (strlen(devName) != 0) {
3140 device |= stringToEnum(sDeviceNameToEnumTable,
3141 ARRAY_SIZE(sDeviceNameToEnumTable),
3144 devName = strtok(NULL, "|");
3146 return (audio_devices_t)device;
3149 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3151 char *str = strtok(name, "|");
3153 while (str != NULL) {
3154 uint32_t rate = atoi(str);
3156 ALOGV("loadSamplingRates() adding rate %d", rate);
3157 profile->mSamplingRates.add(rate);
3159 str = strtok(NULL, "|");
3164 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3166 char *str = strtok(name, "|");
3168 while (str != NULL) {
3169 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3170 ARRAY_SIZE(sFormatNameToEnumTable),
3173 profile->mFormats.add(format);
3175 str = strtok(NULL, "|");
3180 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3182 const char *str = strtok(name, "|");
3184 ALOGV("loadInChannels() %s", name);
3185 while (str != NULL) {
3186 audio_channel_mask_t channelMask =
3187 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3188 ARRAY_SIZE(sInChannelsNameToEnumTable),
3190 if (channelMask != 0) {
3191 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3192 profile->mChannelMasks.add(channelMask);
3194 str = strtok(NULL, "|");
3199 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3201 const char *str = strtok(name, "|");
3202 audio_channel_mask_t channelMask;
3204 while (str != NULL) {
3205 channelMask = stringToEnum(sOutChannelsNameToEnumTable,
3206 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3208 if (channelMask != 0) {
3209 profile->mChannelMasks.add(channelMask);
3211 str = strtok(NULL, "|");
3216 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3218 cnode *node = root->first_child;
3220 IOProfile *profile = new IOProfile(module);
3223 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3224 loadSamplingRates((char *)node->value, profile);
3225 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3226 loadFormats((char *)node->value, profile);
3227 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3228 loadInChannels((char *)node->value, profile);
3229 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3230 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3234 ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3235 "loadInput() invalid supported devices");
3236 ALOGW_IF(profile->mChannelMasks.size() == 0,
3237 "loadInput() invalid supported channel masks");
3238 ALOGW_IF(profile->mSamplingRates.size() == 0,
3239 "loadInput() invalid supported sampling rates");
3240 ALOGW_IF(profile->mFormats.size() == 0,
3241 "loadInput() invalid supported formats");
3242 if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3243 (profile->mChannelMasks.size() != 0) &&
3244 (profile->mSamplingRates.size() != 0) &&
3245 (profile->mFormats.size() != 0)) {
3247 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3249 module->mInputProfiles.add(profile);
3257 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3259 cnode *node = root->first_child;
3261 IOProfile *profile = new IOProfile(module);
3264 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3265 loadSamplingRates((char *)node->value, profile);
3266 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3267 loadFormats((char *)node->value, profile);
3268 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3269 loadOutChannels((char *)node->value, profile);
3270 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3271 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3272 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3273 profile->mFlags = parseFlagNames((char *)node->value);
3277 ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3278 "loadOutput() invalid supported devices");
3279 ALOGW_IF(profile->mChannelMasks.size() == 0,
3280 "loadOutput() invalid supported channel masks");
3281 ALOGW_IF(profile->mSamplingRates.size() == 0,
3282 "loadOutput() invalid supported sampling rates");
3283 ALOGW_IF(profile->mFormats.size() == 0,
3284 "loadOutput() invalid supported formats");
3285 if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3286 (profile->mChannelMasks.size() != 0) &&
3287 (profile->mSamplingRates.size() != 0) &&
3288 (profile->mFormats.size() != 0)) {
3290 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3291 profile->mSupportedDevices, profile->mFlags);
3293 module->mOutputProfiles.add(profile);
3301 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3303 cnode *node = config_find(root, OUTPUTS_TAG);
3304 status_t status = NAME_NOT_FOUND;
3306 HwModule *module = new HwModule(root->name);
3309 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3311 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3315 node = node->first_child;
3317 ALOGV("loadHwModule() loading output %s", node->name);
3318 status_t tmpStatus = loadOutput(node, module);
3319 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3325 node = config_find(root, INPUTS_TAG);
3327 node = node->first_child;
3329 ALOGV("loadHwModule() loading input %s", node->name);
3330 status_t tmpStatus = loadInput(node, module);
3331 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3337 if (status == NO_ERROR) {
3338 mHwModules.add(module);
3344 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3346 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3351 node = node->first_child;
3353 ALOGV("loadHwModules() loading module %s", node->name);
3359 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3361 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3365 node = node->first_child;
3367 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3368 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3369 ALOGW_IF(mAttachedOutputDevices == 0, "loadGlobalConfig() no attached output devices");
3370 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3371 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3372 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3373 ARRAY_SIZE(sDeviceNameToEnumTable),
3374 (char *)node->value);
3375 ALOGW_IF(mDefaultOutputDevice == 0, "loadGlobalConfig() default device not specified");
3376 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3377 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3378 mAvailableInputDevices = parseDeviceNames((char *)node->value);
3379 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3385 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3390 data = (char *)load_file(path, NULL);
3394 root = config_node("", "");
3395 config_load(root, data);
3397 loadGlobalConfig(root);
3398 loadHwModules(root);
3404 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3410 }; // namespace android