2 * Copyright (C) 2009 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define LOG_TAG "AudioPolicyManagerBase"
18 //#define LOG_NDEBUG 0
20 //#define VERY_VERBOSE_LOGGING
21 #ifdef VERY_VERBOSE_LOGGING
24 #define ALOGVV(a...) do { } while(0)
27 #include <utils/Log.h>
28 #include <hardware_legacy/AudioPolicyManagerBase.h>
29 #include <hardware/audio_effect.h>
30 #include <hardware/audio.h>
32 #include <hardware_legacy/audio_policy_conf.h>
34 // For code clarity in AudioPolicyManager: a value to indicate no audio device (both for input
35 // and output) when comparing audio_devices_t mask values
36 #define APM_AUDIO_DEVICE_NONE 0
38 namespace android_audio_legacy {
40 // ----------------------------------------------------------------------------
41 // AudioPolicyInterface implementation
42 // ----------------------------------------------------------------------------
45 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
46 AudioSystem::device_connection_state state,
47 const char *device_address)
49 SortedVector <audio_io_handle_t> outputs;
51 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
53 // connect/disconnect only 1 device at a time
54 if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
56 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
57 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
61 // handle output devices
62 if (audio_is_output_device(device)) {
64 if (!mHasA2dp && audio_is_a2dp_device(device)) {
65 ALOGE("setDeviceConnectionState() invalid device: %x", device);
68 if (!mHasUsb && audio_is_usb_device(device)) {
69 ALOGE("setDeviceConnectionState() invalid device: %x", device);
73 // save a copy of the opened output descriptors before any output is opened or closed
74 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
75 mPreviousOutputs = mOutputs;
78 // handle output device connection
79 case AudioSystem::DEVICE_STATE_AVAILABLE:
80 if (mAvailableOutputDevices & device) {
81 ALOGW("setDeviceConnectionState() device already connected: %x", device);
82 return INVALID_OPERATION;
84 ALOGV("setDeviceConnectionState() connecting device %x", device);
86 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
87 return INVALID_OPERATION;
89 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
91 // register new device as available
92 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
94 if (!outputs.isEmpty()) {
96 if (mHasA2dp && audio_is_a2dp_device(device)) {
97 // handle A2DP device connection
99 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
100 paramStr = param.toString();
101 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
102 mA2dpSuspended = false;
103 } else if (audio_is_bluetooth_sco_device(device)) {
104 // handle SCO device connection
105 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
106 } else if (mHasUsb && audio_is_usb_device(device)) {
107 // handle USB device connection
108 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
109 paramStr = mUsbCardAndDevice;
111 if (!paramStr.isEmpty()) {
112 for (size_t i = 0; i < outputs.size(); i++) {
113 mpClientInterface->setParameters(outputs[i], paramStr);
118 // handle output device disconnection
119 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
120 if (!(mAvailableOutputDevices & device)) {
121 ALOGW("setDeviceConnectionState() device not connected: %x", device);
122 return INVALID_OPERATION;
125 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
126 // remove device from available output devices
127 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
129 checkOutputsForDevice(device, state, outputs);
130 if (mHasA2dp && audio_is_a2dp_device(device)) {
131 // handle A2DP device disconnection
132 mA2dpDeviceAddress = "";
133 mA2dpSuspended = false;
134 } else if (audio_is_bluetooth_sco_device(device)) {
135 // handle SCO device disconnection
136 mScoDeviceAddress = "";
137 } else if (mHasUsb && audio_is_usb_device(device)) {
138 // handle USB device disconnection
139 mUsbCardAndDevice = "";
144 ALOGE("setDeviceConnectionState() invalid state: %x", state);
149 checkOutputForAllStrategies();
150 // outputs must be closed after checkOutputForAllStrategies() is executed
151 if (!outputs.isEmpty()) {
152 for (size_t i = 0; i < outputs.size(); i++) {
153 // close unused outputs after device disconnection or direct outputs that have been
154 // opened by checkOutputsForDevice() to query dynamic parameters
155 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
156 (mOutputs.valueFor(outputs[i])->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
157 closeOutput(outputs[i]);
162 updateDevicesAndOutputs();
163 for (size_t i = 0; i < mOutputs.size(); i++) {
164 setOutputDevice(mOutputs.keyAt(i), getNewDevice(mOutputs.keyAt(i), true /*fromCache*/));
167 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
168 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
169 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
170 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
171 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
172 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
177 // handle input devices
178 if (audio_is_input_device(device)) {
182 // handle input device connection
183 case AudioSystem::DEVICE_STATE_AVAILABLE: {
184 if (mAvailableInputDevices & device) {
185 ALOGW("setDeviceConnectionState() device already connected: %d", device);
186 return INVALID_OPERATION;
188 mAvailableInputDevices = (audio_devices_t)(mAvailableInputDevices | device);
192 // handle input device disconnection
193 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
194 if (!(mAvailableInputDevices & device)) {
195 ALOGW("setDeviceConnectionState() device not connected: %d", device);
196 return INVALID_OPERATION;
198 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
202 ALOGE("setDeviceConnectionState() invalid state: %x", state);
206 audio_io_handle_t activeInput = getActiveInput();
207 if (activeInput != 0) {
208 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
209 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
210 if ((newDevice != APM_AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
211 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
212 inputDesc->mDevice, newDevice, activeInput);
213 inputDesc->mDevice = newDevice;
214 AudioParameter param = AudioParameter();
215 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
216 mpClientInterface->setParameters(activeInput, param.toString());
223 ALOGW("setDeviceConnectionState() invalid device: %x", device);
227 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
228 const char *device_address)
230 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
231 String8 address = String8(device_address);
232 if (audio_is_output_device(device)) {
233 if (device & mAvailableOutputDevices) {
234 if (audio_is_a2dp_device(device) &&
235 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
238 if (audio_is_bluetooth_sco_device(device) &&
239 address != "" && mScoDeviceAddress != address) {
242 if (audio_is_usb_device(device) &&
243 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
244 ALOGE("setDeviceConnectionState() invalid device: %x", device);
247 state = AudioSystem::DEVICE_STATE_AVAILABLE;
249 } else if (audio_is_input_device(device)) {
250 if (device & mAvailableInputDevices) {
251 state = AudioSystem::DEVICE_STATE_AVAILABLE;
258 void AudioPolicyManagerBase::setPhoneState(int state)
260 ALOGV("setPhoneState() state %d", state);
261 audio_devices_t newDevice = APM_AUDIO_DEVICE_NONE;
262 if (state < 0 || state >= AudioSystem::NUM_MODES) {
263 ALOGW("setPhoneState() invalid state %d", state);
267 if (state == mPhoneState ) {
268 ALOGW("setPhoneState() setting same state %d", state);
272 // if leaving call state, handle special case of active streams
273 // pertaining to sonification strategy see handleIncallSonification()
275 ALOGV("setPhoneState() in call state management: new state is %d", state);
276 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
277 handleIncallSonification(stream, false, true);
281 // store previous phone state for management of sonification strategy below
282 int oldState = mPhoneState;
286 // are we entering or starting a call
287 if (!isStateInCall(oldState) && isStateInCall(state)) {
288 ALOGV(" Entering call in setPhoneState()");
289 // force routing command to audio hardware when starting a call
290 // even if no device change is needed
292 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
293 ALOGV(" Exiting call in setPhoneState()");
294 // force routing command to audio hardware when exiting a call
295 // even if no device change is needed
297 } else if (isStateInCall(state) && (state != oldState)) {
298 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
299 // force routing command to audio hardware when switching between telephony and VoIP
300 // even if no device change is needed
304 // check for device and output changes triggered by new phone state
305 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
307 checkOutputForAllStrategies();
308 updateDevicesAndOutputs();
310 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
312 // force routing command to audio hardware when ending call
313 // even if no device change is needed
314 if (isStateInCall(oldState) && newDevice == APM_AUDIO_DEVICE_NONE) {
315 newDevice = hwOutputDesc->device();
318 // when changing from ring tone to in call mode, mute the ringing tone
319 // immediately and delay the route change to avoid sending the ring tone
320 // tail into the earpiece or headset.
322 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
323 // delay the device change command by twice the output latency to have some margin
324 // and be sure that audio buffers not yet affected by the mute are out when
325 // we actually apply the route change
326 delayMs = hwOutputDesc->mLatency*2;
327 setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
330 // change routing is necessary
331 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
333 // if entering in call state, handle special case of active streams
334 // pertaining to sonification strategy see handleIncallSonification()
335 if (isStateInCall(state)) {
336 ALOGV("setPhoneState() in call state management: new state is %d", state);
337 // unmute the ringing tone after a sufficient delay if it was muted before
338 // setting output device above
339 if (oldState == AudioSystem::MODE_RINGTONE) {
340 setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
342 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
343 handleIncallSonification(stream, true, true);
347 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
348 if (state == AudioSystem::MODE_RINGTONE &&
349 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
350 mLimitRingtoneVolume = true;
352 mLimitRingtoneVolume = false;
356 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
358 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
360 bool forceVolumeReeval = false;
362 case AudioSystem::FOR_COMMUNICATION:
363 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
364 config != AudioSystem::FORCE_NONE) {
365 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
368 forceVolumeReeval = true;
369 mForceUse[usage] = config;
371 case AudioSystem::FOR_MEDIA:
372 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
373 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
374 config != AudioSystem::FORCE_ANALOG_DOCK &&
375 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
376 config != AudioSystem::FORCE_NO_BT_A2DP) {
377 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
380 mForceUse[usage] = config;
382 case AudioSystem::FOR_RECORD:
383 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
384 config != AudioSystem::FORCE_NONE) {
385 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
388 mForceUse[usage] = config;
390 case AudioSystem::FOR_DOCK:
391 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
392 config != AudioSystem::FORCE_BT_DESK_DOCK &&
393 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
394 config != AudioSystem::FORCE_ANALOG_DOCK &&
395 config != AudioSystem::FORCE_DIGITAL_DOCK) {
396 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
398 forceVolumeReeval = true;
399 mForceUse[usage] = config;
402 ALOGW("setForceUse() invalid usage %d", usage);
406 // check for device and output changes triggered by new force usage
408 checkOutputForAllStrategies();
409 updateDevicesAndOutputs();
410 for (size_t i = 0; i < mOutputs.size(); i++) {
411 audio_io_handle_t output = mOutputs.keyAt(i);
412 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
413 setOutputDevice(output, newDevice, (newDevice != APM_AUDIO_DEVICE_NONE));
414 if (forceVolumeReeval && (newDevice != APM_AUDIO_DEVICE_NONE)) {
415 applyStreamVolumes(output, newDevice, 0, true);
419 audio_io_handle_t activeInput = getActiveInput();
420 if (activeInput != 0) {
421 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
422 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
423 if ((newDevice != APM_AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
424 ALOGV("setForceUse() changing device from %x to %x for input %d",
425 inputDesc->mDevice, newDevice, activeInput);
426 inputDesc->mDevice = newDevice;
427 AudioParameter param = AudioParameter();
428 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
429 mpClientInterface->setParameters(activeInput, param.toString());
435 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
437 return mForceUse[usage];
440 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
442 ALOGV("setSystemProperty() property %s, value %s", property, value);
443 if (strcmp(property, "ro.camera.sound.forced") == 0) {
445 ALOGV("ENFORCED_AUDIBLE cannot be muted");
446 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
448 ALOGV("ENFORCED_AUDIBLE can be muted");
449 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
454 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
455 audio_devices_t device,
456 uint32_t samplingRate,
458 uint32_t channelMask,
459 audio_output_flags_t flags)
461 for (size_t i = 0; i < mHwModules.size(); i++) {
462 if (mHwModules[i]->mHandle == 0) {
465 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
466 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
467 if (profile->isCompatibleProfile(device, samplingRate, format,
469 AUDIO_OUTPUT_FLAG_DIRECT)) {
470 if (mAvailableOutputDevices & profile->mSupportedDevices) {
471 return mHwModules[i]->mOutputProfiles[j];
479 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
480 uint32_t samplingRate,
482 uint32_t channelMask,
483 AudioSystem::output_flags flags)
485 audio_io_handle_t output = 0;
486 uint32_t latency = 0;
487 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
488 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
489 ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
490 stream, samplingRate, format, channelMask, flags);
492 #ifdef AUDIO_POLICY_TEST
493 if (mCurOutput != 0) {
494 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
495 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
497 if (mTestOutputs[mCurOutput] == 0) {
498 ALOGV("getOutput() opening test output");
499 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
500 outputDesc->mDevice = mTestDevice;
501 outputDesc->mSamplingRate = mTestSamplingRate;
502 outputDesc->mFormat = mTestFormat;
503 outputDesc->mChannelMask = mTestChannels;
504 outputDesc->mLatency = mTestLatencyMs;
505 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
506 outputDesc->mRefCount[stream] = 0;
507 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
508 &outputDesc->mSamplingRate,
509 &outputDesc->mFormat,
510 &outputDesc->mChannelMask,
511 &outputDesc->mLatency,
513 if (mTestOutputs[mCurOutput]) {
514 AudioParameter outputCmd = AudioParameter();
515 outputCmd.addInt(String8("set_id"),mCurOutput);
516 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
517 addOutput(mTestOutputs[mCurOutput], outputDesc);
520 return mTestOutputs[mCurOutput];
522 #endif //AUDIO_POLICY_TEST
524 // open a direct output if required by specified parameters
525 IOProfile *profile = getProfileForDirectOutput(device,
529 (audio_output_flags_t)flags);
530 if (profile != NULL) {
532 ALOGV("getOutput() opening direct output device %x", device);
534 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(profile);
535 outputDesc->mDevice = device;
536 outputDesc->mSamplingRate = samplingRate;
537 outputDesc->mFormat = (audio_format_t)format;
538 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
539 outputDesc->mLatency = 0;
540 outputDesc->mFlags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);;
541 outputDesc->mRefCount[stream] = 0;
542 outputDesc->mStopTime[stream] = 0;
543 output = mpClientInterface->openOutput(profile->mModule->mHandle,
544 &outputDesc->mDevice,
545 &outputDesc->mSamplingRate,
546 &outputDesc->mFormat,
547 &outputDesc->mChannelMask,
548 &outputDesc->mLatency,
551 // only accept an output with the requested parameters
553 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
554 (format != 0 && format != outputDesc->mFormat) ||
555 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
556 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
557 "format %d %d, channelMask %04x %04x", output, samplingRate,
558 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
559 outputDesc->mChannelMask);
561 mpClientInterface->closeOutput(output);
566 addOutput(output, outputDesc);
567 ALOGV("getOutput() returns direct output %d", output);
571 // ignoring channel mask due to downmix capability in mixer
573 // open a non direct output
575 // get which output is suitable for the specified stream. The actual routing change will happen
576 // when startOutput() will be called
577 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
579 output = selectOutput(outputs, flags);
581 ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
582 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
584 ALOGV("getOutput() returns output %d", output);
589 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
590 AudioSystem::output_flags flags)
592 // select one output among several that provide a path to a particular device or set of
593 // devices (the list was previously build by getOutputsForDevice()).
594 // The priority is as follows:
595 // 1: the output with the highest number of requested policy flags
596 // 2: the primary output
597 // 3: the first output in the list
599 if (outputs.size() == 0) {
602 if (outputs.size() == 1) {
606 int maxCommonFlags = 0;
607 audio_io_handle_t outputFlags = 0;
608 audio_io_handle_t outputPrimary = 0;
610 for (size_t i = 0; i < outputs.size(); i++) {
611 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
612 if (!outputDesc->isDuplicated()) {
613 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
614 if (commonFlags > maxCommonFlags) {
615 outputFlags = outputs[i];
616 maxCommonFlags = commonFlags;
617 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
619 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
620 outputPrimary = outputs[i];
625 if (outputFlags != 0) {
628 if (outputPrimary != 0) {
629 return outputPrimary;
635 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
636 AudioSystem::stream_type stream,
639 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
640 ssize_t index = mOutputs.indexOfKey(output);
642 ALOGW("startOutput() unknow output %d", output);
646 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
648 // increment usage count for this stream on the requested output:
649 // NOTE that the usage count is the same for duplicated output and hardware output which is
650 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
651 outputDesc->changeRefCount(stream, 1);
653 if (outputDesc->mRefCount[stream] == 1) {
654 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
655 routing_strategy strategy = getStrategy(stream);
656 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
657 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
660 for (size_t i = 0; i < mOutputs.size(); i++) {
661 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
662 if (desc != outputDesc) {
663 // force a device change if any other output is managed by the same hw
664 // module and has a current device selection that differs from selected device.
665 // In this case, the audio HAL must receive the new device selection so that it can
666 // change the device currently selected by the other active output.
667 if (outputDesc->sharesHwModuleWith(desc) &&
668 desc->device() != newDevice) {
671 // wait for audio on other active outputs to be presented when starting
672 // a notification so that audio focus effect can propagate.
673 if (shouldWait && (desc->refCount() != 0) && (waitMs < desc->latency())) {
674 waitMs = desc->latency();
678 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
680 // handle special case for sonification while in call
682 handleIncallSonification(stream, true, false);
685 // apply volume rules for current stream and device if necessary
686 checkAndSetVolume(stream,
687 mStreams[stream].getVolumeIndex(newDevice),
691 // update the outputs if starting an output with a stream that can affect notification
693 handleNotificationRoutingForStream(stream);
694 if (waitMs > muteWaitMs) {
695 usleep((waitMs - muteWaitMs) * 2 * 1000);
702 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
703 AudioSystem::stream_type stream,
706 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
707 ssize_t index = mOutputs.indexOfKey(output);
709 ALOGW("stopOutput() unknow output %d", output);
713 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
715 // handle special case for sonification while in call
717 handleIncallSonification(stream, false, false);
720 if (outputDesc->mRefCount[stream] > 0) {
721 // decrement usage count of this stream on the output
722 outputDesc->changeRefCount(stream, -1);
723 // store time at which the stream was stopped - see isStreamActive()
724 if (outputDesc->mRefCount[stream] == 0) {
725 outputDesc->mStopTime[stream] = systemTime();
726 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
727 // delay the device switch by twice the latency because stopOutput() is executed when
728 // the track stop() command is received and at that time the audio track buffer can
729 // still contain data that needs to be drained. The latency only covers the audio HAL
730 // and kernel buffers. Also the latency does not always include additional delay in the
731 // audio path (audio DSP, CODEC ...)
732 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
734 // force restoring the device selection on other active outputs if it differs from the
735 // one being selected for this output
736 for (size_t i = 0; i < mOutputs.size(); i++) {
737 audio_io_handle_t curOutput = mOutputs.keyAt(i);
738 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
739 if (curOutput != output &&
740 desc->refCount() != 0 &&
741 outputDesc->sharesHwModuleWith(desc) &&
742 newDevice != desc->device()) {
743 setOutputDevice(curOutput,
744 getNewDevice(curOutput, false /*fromCache*/),
746 outputDesc->mLatency*2);
749 // update the outputs if stopping one with a stream that can affect notification routing
750 handleNotificationRoutingForStream(stream);
754 ALOGW("stopOutput() refcount is already 0 for output %d", output);
755 return INVALID_OPERATION;
759 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
761 ALOGV("releaseOutput() %d", output);
762 ssize_t index = mOutputs.indexOfKey(output);
764 ALOGW("releaseOutput() releasing unknown output %d", output);
768 #ifdef AUDIO_POLICY_TEST
769 int testIndex = testOutputIndex(output);
770 if (testIndex != 0) {
771 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
772 if (outputDesc->refCount() == 0) {
773 mpClientInterface->closeOutput(output);
774 delete mOutputs.valueAt(index);
775 mOutputs.removeItem(output);
776 mTestOutputs[testIndex] = 0;
780 #endif //AUDIO_POLICY_TEST
782 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
783 mpClientInterface->closeOutput(output);
784 delete mOutputs.valueAt(index);
785 mOutputs.removeItem(output);
790 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
791 uint32_t samplingRate,
793 uint32_t channelMask,
794 AudioSystem::audio_in_acoustics acoustics)
796 audio_io_handle_t input = 0;
797 audio_devices_t device = getDeviceForInputSource(inputSource);
799 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
800 inputSource, samplingRate, format, channelMask, acoustics);
802 if (device == APM_AUDIO_DEVICE_NONE) {
803 ALOGW("getInput() could not find device for inputSource %d", inputSource);
807 // adapt channel selection to input source
808 switch(inputSource) {
809 case AUDIO_SOURCE_VOICE_UPLINK:
810 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
812 case AUDIO_SOURCE_VOICE_DOWNLINK:
813 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
815 case AUDIO_SOURCE_VOICE_CALL:
816 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
822 IOProfile *profile = getInputProfile(device,
826 if (profile == NULL) {
827 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
829 device, samplingRate, format, channelMask);
833 if (profile->mModule->mHandle == 0) {
834 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
838 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
840 inputDesc->mInputSource = inputSource;
841 inputDesc->mDevice = device;
842 inputDesc->mSamplingRate = samplingRate;
843 inputDesc->mFormat = (audio_format_t)format;
844 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
845 inputDesc->mRefCount = 0;
846 input = mpClientInterface->openInput(profile->mModule->mHandle,
848 &inputDesc->mSamplingRate,
850 &inputDesc->mChannelMask);
852 // only accept input with the exact requested set of parameters
854 (samplingRate != inputDesc->mSamplingRate) ||
855 (format != inputDesc->mFormat) ||
856 (channelMask != inputDesc->mChannelMask)) {
857 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
858 samplingRate, format, channelMask);
860 mpClientInterface->closeInput(input);
865 mInputs.add(input, inputDesc);
869 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
871 ALOGV("startInput() input %d", input);
872 ssize_t index = mInputs.indexOfKey(input);
874 ALOGW("startInput() unknow input %d", input);
877 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
879 #ifdef AUDIO_POLICY_TEST
881 #endif //AUDIO_POLICY_TEST
883 // refuse 2 active AudioRecord clients at the same time
884 if (getActiveInput() != 0) {
885 ALOGW("startInput() input %d failed: other input already started", input);
886 return INVALID_OPERATION;
890 AudioParameter param = AudioParameter();
891 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
893 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
894 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
896 mpClientInterface->setParameters(input, param.toString());
898 inputDesc->mRefCount = 1;
902 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
904 ALOGV("stopInput() input %d", input);
905 ssize_t index = mInputs.indexOfKey(input);
907 ALOGW("stopInput() unknow input %d", input);
910 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
912 if (inputDesc->mRefCount == 0) {
913 ALOGW("stopInput() input %d already stopped", input);
914 return INVALID_OPERATION;
916 AudioParameter param = AudioParameter();
917 param.addInt(String8(AudioParameter::keyRouting), 0);
918 mpClientInterface->setParameters(input, param.toString());
919 inputDesc->mRefCount = 0;
924 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
926 ALOGV("releaseInput() %d", input);
927 ssize_t index = mInputs.indexOfKey(input);
929 ALOGW("releaseInput() releasing unknown input %d", input);
932 mpClientInterface->closeInput(input);
933 delete mInputs.valueAt(index);
934 mInputs.removeItem(input);
935 ALOGV("releaseInput() exit");
938 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
942 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
943 if (indexMin < 0 || indexMin >= indexMax) {
944 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
947 mStreams[stream].mIndexMin = indexMin;
948 mStreams[stream].mIndexMax = indexMax;
951 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
953 audio_devices_t device)
956 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
959 if (!audio_is_output_device(device)) {
963 // Force max volume if stream cannot be muted
964 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
966 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
967 stream, device, index);
969 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
970 // clear all device specific values
971 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
972 mStreams[stream].mIndexCur.clear();
974 mStreams[stream].mIndexCur.add(device, index);
976 // compute and apply stream volume on all outputs according to connected device
977 status_t status = NO_ERROR;
978 for (size_t i = 0; i < mOutputs.size(); i++) {
979 audio_devices_t curDevice =
980 getDeviceForVolume(mOutputs.valueAt(i)->device());
981 if (device == curDevice) {
982 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
983 if (volStatus != NO_ERROR) {
991 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
993 audio_devices_t device)
998 if (!audio_is_output_device(device)) {
1001 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1002 // the strategy the stream belongs to.
1003 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1004 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1006 device = getDeviceForVolume(device);
1008 *index = mStreams[stream].getVolumeIndex(device);
1009 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1013 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1015 ALOGV("getOutputForEffect()");
1016 // apply simple rule where global effects are attached to the same output as MUSIC streams
1018 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1019 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1020 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1022 for (size_t i = 0; i < dstOutputs.size(); i++) {
1023 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1024 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1028 return dstOutputs[outIdx];
1031 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1032 audio_io_handle_t io,
1037 ssize_t index = mOutputs.indexOfKey(io);
1039 index = mInputs.indexOfKey(io);
1041 ALOGW("registerEffect() unknown io %d", io);
1042 return INVALID_OPERATION;
1046 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1047 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1048 desc->name, desc->memoryUsage);
1049 return INVALID_OPERATION;
1051 mTotalEffectsMemory += desc->memoryUsage;
1052 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1053 desc->name, io, strategy, session, id);
1054 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1056 EffectDescriptor *pDesc = new EffectDescriptor();
1057 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1059 pDesc->mStrategy = (routing_strategy)strategy;
1060 pDesc->mSession = session;
1061 pDesc->mEnabled = false;
1063 mEffects.add(id, pDesc);
1068 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1070 ssize_t index = mEffects.indexOfKey(id);
1072 ALOGW("unregisterEffect() unknown effect ID %d", id);
1073 return INVALID_OPERATION;
1076 EffectDescriptor *pDesc = mEffects.valueAt(index);
1078 setEffectEnabled(pDesc, false);
1080 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1081 ALOGW("unregisterEffect() memory %d too big for total %d",
1082 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1083 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1085 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1086 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1087 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1089 mEffects.removeItem(id);
1095 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1097 ssize_t index = mEffects.indexOfKey(id);
1099 ALOGW("unregisterEffect() unknown effect ID %d", id);
1100 return INVALID_OPERATION;
1103 return setEffectEnabled(mEffects.valueAt(index), enabled);
1106 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1108 if (enabled == pDesc->mEnabled) {
1109 ALOGV("setEffectEnabled(%s) effect already %s",
1110 enabled?"true":"false", enabled?"enabled":"disabled");
1111 return INVALID_OPERATION;
1115 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1116 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1117 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1118 return INVALID_OPERATION;
1120 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1121 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1123 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1124 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1125 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1126 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1128 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1129 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1131 pDesc->mEnabled = enabled;
1135 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1137 nsecs_t sysTime = systemTime();
1138 for (size_t i = 0; i < mOutputs.size(); i++) {
1139 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
1140 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
1148 status_t AudioPolicyManagerBase::dump(int fd)
1150 const size_t SIZE = 256;
1154 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1155 result.append(buffer);
1157 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1158 result.append(buffer);
1159 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1160 result.append(buffer);
1161 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1162 result.append(buffer);
1163 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1164 result.append(buffer);
1165 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1166 result.append(buffer);
1167 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1168 result.append(buffer);
1169 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1170 result.append(buffer);
1171 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1172 result.append(buffer);
1173 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1174 result.append(buffer);
1175 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1176 result.append(buffer);
1177 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1178 result.append(buffer);
1179 write(fd, result.string(), result.size());
1182 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1183 write(fd, buffer, strlen(buffer));
1184 for (size_t i = 0; i < mHwModules.size(); i++) {
1185 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1186 write(fd, buffer, strlen(buffer));
1187 mHwModules[i]->dump(fd);
1190 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1191 write(fd, buffer, strlen(buffer));
1192 for (size_t i = 0; i < mOutputs.size(); i++) {
1193 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1194 write(fd, buffer, strlen(buffer));
1195 mOutputs.valueAt(i)->dump(fd);
1198 snprintf(buffer, SIZE, "\nInputs dump:\n");
1199 write(fd, buffer, strlen(buffer));
1200 for (size_t i = 0; i < mInputs.size(); i++) {
1201 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1202 write(fd, buffer, strlen(buffer));
1203 mInputs.valueAt(i)->dump(fd);
1206 snprintf(buffer, SIZE, "\nStreams dump:\n");
1207 write(fd, buffer, strlen(buffer));
1208 snprintf(buffer, SIZE,
1209 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1210 write(fd, buffer, strlen(buffer));
1211 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1212 snprintf(buffer, SIZE, " %02d ", i);
1213 write(fd, buffer, strlen(buffer));
1214 mStreams[i].dump(fd);
1217 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1218 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1219 write(fd, buffer, strlen(buffer));
1221 snprintf(buffer, SIZE, "Registered effects:\n");
1222 write(fd, buffer, strlen(buffer));
1223 for (size_t i = 0; i < mEffects.size(); i++) {
1224 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1225 write(fd, buffer, strlen(buffer));
1226 mEffects.valueAt(i)->dump(fd);
1233 // ----------------------------------------------------------------------------
1234 // AudioPolicyManagerBase
1235 // ----------------------------------------------------------------------------
1237 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1239 #ifdef AUDIO_POLICY_TEST
1241 #endif //AUDIO_POLICY_TEST
1242 mPrimaryOutput((audio_io_handle_t)0),
1243 mAvailableOutputDevices(APM_AUDIO_DEVICE_NONE),
1244 mPhoneState(AudioSystem::MODE_NORMAL),
1245 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1246 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1247 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false)
1249 mpClientInterface = clientInterface;
1251 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1252 mForceUse[i] = AudioSystem::FORCE_NONE;
1255 initializeVolumeCurves();
1257 mA2dpDeviceAddress = String8("");
1258 mScoDeviceAddress = String8("");
1259 mUsbCardAndDevice = String8("");
1261 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1262 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1263 ALOGE("could not load audio policy configuration file, setting defaults");
1264 defaultAudioPolicyConfig();
1268 // open all output streams needed to access attached devices
1269 for (size_t i = 0; i < mHwModules.size(); i++) {
1270 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1271 if (mHwModules[i]->mHandle == 0) {
1272 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1275 // open all output streams needed to access attached devices
1276 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1278 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1280 if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1281 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1282 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1283 outProfile->mSupportedDevices);
1284 audio_io_handle_t output = mpClientInterface->openOutput(
1285 outProfile->mModule->mHandle,
1286 &outputDesc->mDevice,
1287 &outputDesc->mSamplingRate,
1288 &outputDesc->mFormat,
1289 &outputDesc->mChannelMask,
1290 &outputDesc->mLatency,
1291 outputDesc->mFlags);
1295 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1296 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1297 if (mPrimaryOutput == 0 &&
1298 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1299 mPrimaryOutput = output;
1301 addOutput(output, outputDesc);
1302 setOutputDevice(output,
1303 (audio_devices_t)(mDefaultOutputDevice &
1304 outProfile->mSupportedDevices),
1311 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1312 "Not output found for attached devices %08x",
1313 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1315 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1317 updateDevicesAndOutputs();
1319 #ifdef AUDIO_POLICY_TEST
1320 if (mPrimaryOutput != 0) {
1321 AudioParameter outputCmd = AudioParameter();
1322 outputCmd.addInt(String8("set_id"), 0);
1323 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1325 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1326 mTestSamplingRate = 44100;
1327 mTestFormat = AudioSystem::PCM_16_BIT;
1328 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1331 mDirectOutput = false;
1332 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1333 mTestOutputs[i] = 0;
1336 const size_t SIZE = 256;
1338 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1339 run(buffer, ANDROID_PRIORITY_AUDIO);
1341 #endif //AUDIO_POLICY_TEST
1344 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1346 #ifdef AUDIO_POLICY_TEST
1348 #endif //AUDIO_POLICY_TEST
1349 for (size_t i = 0; i < mOutputs.size(); i++) {
1350 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1351 delete mOutputs.valueAt(i);
1353 for (size_t i = 0; i < mInputs.size(); i++) {
1354 mpClientInterface->closeInput(mInputs.keyAt(i));
1355 delete mInputs.valueAt(i);
1357 for (size_t i = 0; i < mHwModules.size(); i++) {
1358 delete mHwModules[i];
1362 status_t AudioPolicyManagerBase::initCheck()
1364 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1367 #ifdef AUDIO_POLICY_TEST
1368 bool AudioPolicyManagerBase::threadLoop()
1370 ALOGV("entering threadLoop()");
1371 while (!exitPending())
1377 Mutex::Autolock _l(mLock);
1378 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1380 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1381 AudioParameter param = AudioParameter(command);
1383 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1385 ALOGV("Test command %s received", command.string());
1387 if (param.get(String8("target"), target) != NO_ERROR) {
1390 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1391 param.remove(String8("test_cmd_policy_output"));
1392 mCurOutput = valueInt;
1394 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1395 param.remove(String8("test_cmd_policy_direct"));
1396 if (value == "false") {
1397 mDirectOutput = false;
1398 } else if (value == "true") {
1399 mDirectOutput = true;
1402 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1403 param.remove(String8("test_cmd_policy_input"));
1404 mTestInput = valueInt;
1407 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1408 param.remove(String8("test_cmd_policy_format"));
1409 int format = AudioSystem::INVALID_FORMAT;
1410 if (value == "PCM 16 bits") {
1411 format = AudioSystem::PCM_16_BIT;
1412 } else if (value == "PCM 8 bits") {
1413 format = AudioSystem::PCM_8_BIT;
1414 } else if (value == "Compressed MP3") {
1415 format = AudioSystem::MP3;
1417 if (format != AudioSystem::INVALID_FORMAT) {
1418 if (target == "Manager") {
1419 mTestFormat = format;
1420 } else if (mTestOutputs[mCurOutput] != 0) {
1421 AudioParameter outputParam = AudioParameter();
1422 outputParam.addInt(String8("format"), format);
1423 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1427 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1428 param.remove(String8("test_cmd_policy_channels"));
1431 if (value == "Channels Stereo") {
1432 channels = AudioSystem::CHANNEL_OUT_STEREO;
1433 } else if (value == "Channels Mono") {
1434 channels = AudioSystem::CHANNEL_OUT_MONO;
1436 if (channels != 0) {
1437 if (target == "Manager") {
1438 mTestChannels = channels;
1439 } else if (mTestOutputs[mCurOutput] != 0) {
1440 AudioParameter outputParam = AudioParameter();
1441 outputParam.addInt(String8("channels"), channels);
1442 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1446 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1447 param.remove(String8("test_cmd_policy_sampleRate"));
1448 if (valueInt >= 0 && valueInt <= 96000) {
1449 int samplingRate = valueInt;
1450 if (target == "Manager") {
1451 mTestSamplingRate = samplingRate;
1452 } else if (mTestOutputs[mCurOutput] != 0) {
1453 AudioParameter outputParam = AudioParameter();
1454 outputParam.addInt(String8("sampling_rate"), samplingRate);
1455 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1460 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1461 param.remove(String8("test_cmd_policy_reopen"));
1463 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1464 mpClientInterface->closeOutput(mPrimaryOutput);
1466 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1468 delete mOutputs.valueFor(mPrimaryOutput);
1469 mOutputs.removeItem(mPrimaryOutput);
1471 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1472 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1473 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1474 &outputDesc->mDevice,
1475 &outputDesc->mSamplingRate,
1476 &outputDesc->mFormat,
1477 &outputDesc->mChannelMask,
1478 &outputDesc->mLatency,
1479 outputDesc->mFlags);
1480 if (mPrimaryOutput == 0) {
1481 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1482 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1484 AudioParameter outputCmd = AudioParameter();
1485 outputCmd.addInt(String8("set_id"), 0);
1486 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1487 addOutput(mPrimaryOutput, outputDesc);
1492 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1498 void AudioPolicyManagerBase::exit()
1501 AutoMutex _l(mLock);
1503 mWaitWorkCV.signal();
1505 requestExitAndWait();
1508 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1510 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1511 if (output == mTestOutputs[i]) return i;
1515 #endif //AUDIO_POLICY_TEST
1519 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1521 outputDesc->mId = id;
1522 mOutputs.add(id, outputDesc);
1526 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1527 AudioSystem::device_connection_state state,
1528 SortedVector<audio_io_handle_t>& outputs)
1530 AudioOutputDescriptor *desc;
1532 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1533 // first list already open outputs that can be routed to this device
1534 for (size_t i = 0; i < mOutputs.size(); i++) {
1535 desc = mOutputs.valueAt(i);
1536 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1537 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1538 outputs.add(mOutputs.keyAt(i));
1541 // then look for output profiles that can be routed to this device
1542 SortedVector<IOProfile *> profiles;
1543 for (size_t i = 0; i < mHwModules.size(); i++)
1545 if (mHwModules[i]->mHandle == 0) {
1548 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1550 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1551 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1552 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1557 if (profiles.isEmpty() && outputs.isEmpty()) {
1558 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1562 // open outputs for matching profiles if needed. Direct outputs are also opened to
1563 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1564 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1565 IOProfile *profile = profiles[profile_index];
1567 // nothing to do if one output is already opened for this profile
1569 for (j = 0; j < outputs.size(); j++) {
1570 desc = mOutputs.valueAt(j);
1571 if (!desc->isDuplicated() && desc->mProfile == profile) {
1575 if (j != outputs.size()) {
1579 ALOGV("opening output for device %08x", device);
1580 desc = new AudioOutputDescriptor(profile);
1581 desc->mDevice = device;
1582 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1584 &desc->mSamplingRate,
1586 &desc->mChannelMask,
1590 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1593 if (profile->mSamplingRates[0] == 0) {
1594 reply = mpClientInterface->getParameters(output,
1595 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1596 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1598 value = strpbrk((char *)reply.string(), "=");
1599 if (value != NULL) {
1600 loadSamplingRates(value, profile);
1603 if (profile->mFormats[0] == 0) {
1604 reply = mpClientInterface->getParameters(output,
1605 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1606 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1608 value = strpbrk((char *)reply.string(), "=");
1609 if (value != NULL) {
1610 loadFormats(value, profile);
1613 if (profile->mChannelMasks[0] == 0) {
1614 reply = mpClientInterface->getParameters(output,
1615 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1616 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1618 value = strpbrk((char *)reply.string(), "=");
1619 if (value != NULL) {
1620 loadOutChannels(value + 1, profile);
1623 if (((profile->mSamplingRates[0] == 0) &&
1624 (profile->mSamplingRates.size() < 2)) ||
1625 ((profile->mFormats[0] == 0) &&
1626 (profile->mFormats.size() < 2)) ||
1627 ((profile->mFormats[0] == 0) &&
1628 (profile->mChannelMasks.size() < 2))) {
1629 ALOGW("checkOutputsForDevice() direct output missing param");
1632 addOutput(output, desc);
1635 audio_io_handle_t duplicatedOutput = 0;
1636 // add output descriptor
1637 addOutput(output, desc);
1638 // set initial stream volume for device
1639 applyStreamVolumes(output, device, 0, true);
1641 //TODO: configure audio effect output stage here
1643 // open a duplicating output thread for the new output and the primary output
1644 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1646 if (duplicatedOutput != 0) {
1647 // add duplicated output descriptor
1648 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1649 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1650 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1651 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1652 dupOutputDesc->mFormat = desc->mFormat;
1653 dupOutputDesc->mChannelMask = desc->mChannelMask;
1654 dupOutputDesc->mLatency = desc->mLatency;
1655 addOutput(duplicatedOutput, dupOutputDesc);
1656 applyStreamVolumes(duplicatedOutput, device, 0, true);
1658 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1659 mPrimaryOutput, output);
1660 mpClientInterface->closeOutput(output);
1661 mOutputs.removeItem(output);
1667 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1669 profiles.removeAt(profile_index);
1672 outputs.add(output);
1673 ALOGV("checkOutputsForDevice(): adding output %d", output);
1677 if (profiles.isEmpty()) {
1678 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1682 // check if one opened output is not needed any more after disconnecting one device
1683 for (size_t i = 0; i < mOutputs.size(); i++) {
1684 desc = mOutputs.valueAt(i);
1685 if (!desc->isDuplicated() &&
1686 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1687 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1688 outputs.add(mOutputs.keyAt(i));
1691 for (size_t i = 0; i < mHwModules.size(); i++)
1693 if (mHwModules[i]->mHandle == 0) {
1696 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1698 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1699 if ((profile->mSupportedDevices & device) &&
1700 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1701 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1703 if (profile->mSamplingRates[0] == 0) {
1704 profile->mSamplingRates.clear();
1705 profile->mSamplingRates.add(0);
1707 if (profile->mFormats[0] == 0) {
1708 profile->mFormats.clear();
1709 profile->mFormats.add((audio_format_t)0);
1711 if (profile->mChannelMasks[0] == 0) {
1712 profile->mChannelMasks.clear();
1713 profile->mChannelMasks.add((audio_channel_mask_t)0);
1722 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1724 ALOGV("closeOutput(%d)", output);
1726 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1727 if (outputDesc == NULL) {
1728 ALOGW("closeOutput() unknown output %d", output);
1732 // look for duplicated outputs connected to the output being removed.
1733 for (size_t i = 0; i < mOutputs.size(); i++) {
1734 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1735 if (dupOutputDesc->isDuplicated() &&
1736 (dupOutputDesc->mOutput1 == outputDesc ||
1737 dupOutputDesc->mOutput2 == outputDesc)) {
1738 AudioOutputDescriptor *outputDesc2;
1739 if (dupOutputDesc->mOutput1 == outputDesc) {
1740 outputDesc2 = dupOutputDesc->mOutput2;
1742 outputDesc2 = dupOutputDesc->mOutput1;
1744 // As all active tracks on duplicated output will be deleted,
1745 // and as they were also referenced on the other output, the reference
1746 // count for their stream type must be adjusted accordingly on
1747 // the other output.
1748 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1749 int refCount = dupOutputDesc->mRefCount[j];
1750 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1752 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1753 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1755 mpClientInterface->closeOutput(duplicatedOutput);
1756 delete mOutputs.valueFor(duplicatedOutput);
1757 mOutputs.removeItem(duplicatedOutput);
1761 AudioParameter param;
1762 param.add(String8("closing"), String8("true"));
1763 mpClientInterface->setParameters(output, param.toString());
1765 mpClientInterface->closeOutput(output);
1766 delete mOutputs.valueFor(output);
1767 mOutputs.removeItem(output);
1770 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
1771 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
1773 SortedVector<audio_io_handle_t> outputs;
1775 ALOGVV("getOutputsForDevice() device %04x", device);
1776 for (size_t i = 0; i < openOutputs.size(); i++) {
1777 ALOGVV("output %d isDuplicated=%d device=%04x",
1778 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
1779 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
1780 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
1781 outputs.add(openOutputs.keyAt(i));
1787 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1788 SortedVector<audio_io_handle_t>& outputs2)
1790 if (outputs1.size() != outputs2.size()) {
1793 for (size_t i = 0; i < outputs1.size(); i++) {
1794 if (outputs1[i] != outputs2[i]) {
1801 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1803 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
1804 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
1805 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
1806 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
1808 if (!vectorsEqual(srcOutputs,dstOutputs)) {
1809 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1810 strategy, srcOutputs[0], dstOutputs[0]);
1811 // mute strategy while moving tracks from one output to another
1812 for (size_t i = 0; i < srcOutputs.size(); i++) {
1813 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
1814 if (desc->strategyRefCount(strategy) != 0) {
1815 setStrategyMute(strategy, true, srcOutputs[i]);
1816 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
1820 // Move effects associated to this strategy from previous output to new output
1821 if (strategy == STRATEGY_MEDIA) {
1823 for (size_t i = 0; i < dstOutputs.size(); i++) {
1824 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1825 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1829 SortedVector<audio_io_handle_t> moved;
1830 for (size_t i = 0; i < mEffects.size(); i++) {
1831 EffectDescriptor *desc = mEffects.valueAt(i);
1832 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
1833 desc->mIo != dstOutputs[outIdx]) {
1834 if (moved.indexOf(desc->mIo) < 0) {
1835 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1836 mEffects.keyAt(i), dstOutputs[outIdx]);
1837 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
1838 dstOutputs[outIdx]);
1839 moved.add(desc->mIo);
1841 desc->mIo = dstOutputs[outIdx];
1845 // Move tracks associated to this strategy from previous output to new output
1846 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1847 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1848 //FIXME see fixme on name change
1849 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
1850 dstOutputs[0] /* ignored */);
1856 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1858 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1859 checkOutputForStrategy(STRATEGY_PHONE);
1860 checkOutputForStrategy(STRATEGY_SONIFICATION);
1861 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1862 checkOutputForStrategy(STRATEGY_MEDIA);
1863 checkOutputForStrategy(STRATEGY_DTMF);
1866 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1872 for (size_t i = 0; i < mOutputs.size(); i++) {
1873 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1874 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1875 return mOutputs.keyAt(i);
1882 void AudioPolicyManagerBase::checkA2dpSuspend()
1887 audio_io_handle_t a2dpOutput = getA2dpOutput();
1888 if (a2dpOutput == 0) {
1892 // suspend A2DP output if:
1893 // (NOT already suspended) &&
1894 // ((SCO device is connected &&
1895 // (forced usage for communication || for record is SCO))) ||
1896 // (phone state is ringing || in call)
1898 // restore A2DP output if:
1899 // (Already suspended) &&
1900 // ((SCO device is NOT connected ||
1901 // (forced usage NOT for communication && NOT for record is SCO))) &&
1902 // (phone state is NOT ringing && NOT in call)
1904 if (mA2dpSuspended) {
1905 if (((mScoDeviceAddress == "") ||
1906 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1907 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1908 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1909 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1911 mpClientInterface->restoreOutput(a2dpOutput);
1912 mA2dpSuspended = false;
1915 if (((mScoDeviceAddress != "") &&
1916 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1917 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1918 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1919 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1921 mpClientInterface->suspendOutput(a2dpOutput);
1922 mA2dpSuspended = true;
1927 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1929 audio_devices_t device = APM_AUDIO_DEVICE_NONE;
1931 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1932 // check the following by order of priority to request a routing change if necessary:
1933 // 1: the strategy enforced audible is active on the output:
1934 // use device for strategy enforced audible
1935 // 2: we are in call or the strategy phone is active on the output:
1936 // use device for strategy phone
1937 // 3: the strategy sonification is active on the output:
1938 // use device for strategy sonification
1939 // 4: the strategy "respectful" sonification is active on the output:
1940 // use device for strategy "respectful" sonification
1941 // 5: the strategy media is active on the output:
1942 // use device for strategy media
1943 // 6: the strategy DTMF is active on the output:
1944 // use device for strategy DTMF
1945 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1946 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1947 } else if (isInCall() ||
1948 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1949 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1950 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1951 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1952 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
1953 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
1954 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1955 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1956 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1957 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1960 ALOGV("getNewDevice() selected device %x", device);
1964 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1965 return (uint32_t)getStrategy(stream);
1968 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1969 audio_devices_t devices;
1970 // By checking the range of stream before calling getStrategy, we avoid
1971 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
1972 // and then return STRATEGY_MEDIA, but we want to return the empty set.
1973 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1974 devices = APM_AUDIO_DEVICE_NONE;
1976 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1977 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
1982 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1983 AudioSystem::stream_type stream) {
1984 // stream to strategy mapping
1986 case AudioSystem::VOICE_CALL:
1987 case AudioSystem::BLUETOOTH_SCO:
1988 return STRATEGY_PHONE;
1989 case AudioSystem::RING:
1990 case AudioSystem::ALARM:
1991 return STRATEGY_SONIFICATION;
1992 case AudioSystem::NOTIFICATION:
1993 return STRATEGY_SONIFICATION_RESPECTFUL;
1994 case AudioSystem::DTMF:
1995 return STRATEGY_DTMF;
1997 ALOGE("unknown stream type");
1998 case AudioSystem::SYSTEM:
1999 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2000 // while key clicks are played produces a poor result
2001 case AudioSystem::TTS:
2002 case AudioSystem::MUSIC:
2003 return STRATEGY_MEDIA;
2004 case AudioSystem::ENFORCED_AUDIBLE:
2005 return STRATEGY_ENFORCED_AUDIBLE;
2009 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2011 case AudioSystem::MUSIC:
2012 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2013 updateDevicesAndOutputs();
2020 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2023 uint32_t device = APM_AUDIO_DEVICE_NONE;
2026 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2027 strategy, mDeviceForStrategy[strategy]);
2028 return mDeviceForStrategy[strategy];
2033 case STRATEGY_SONIFICATION_RESPECTFUL:
2035 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2036 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2037 // while media is playing (or has recently played), use the same device
2038 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2040 // when media is not playing anymore, fall back on the sonification behavior
2041 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2048 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2049 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2052 // when in call, DTMF and PHONE strategies follow the same rules
2055 case STRATEGY_PHONE:
2056 // for phone strategy, we first consider the forced use and then the available devices by order
2058 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2059 case AudioSystem::FORCE_BT_SCO:
2060 if (!isInCall() || strategy != STRATEGY_DTMF) {
2061 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2064 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2066 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2068 // if SCO device is requested but no SCO device is available, fall back to default case
2071 default: // FORCE_NONE
2072 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2073 if (mHasA2dp && !isInCall() &&
2074 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2075 (getA2dpOutput() != APM_AUDIO_DEVICE_NONE) && !mA2dpSuspended) {
2076 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2078 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2081 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2083 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2085 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2087 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2089 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2091 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2093 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2095 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2097 device = mDefaultOutputDevice;
2098 if (device == APM_AUDIO_DEVICE_NONE) {
2099 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2103 case AudioSystem::FORCE_SPEAKER:
2104 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2105 // A2DP speaker when forcing to speaker output
2106 if (mHasA2dp && !isInCall() &&
2107 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2108 (getA2dpOutput() != APM_AUDIO_DEVICE_NONE) && !mA2dpSuspended) {
2109 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2112 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2114 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2116 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2118 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2120 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2122 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2124 device = mDefaultOutputDevice;
2125 if (device == APM_AUDIO_DEVICE_NONE) {
2126 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2132 case STRATEGY_SONIFICATION:
2134 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2135 // handleIncallSonification().
2137 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2142 case STRATEGY_ENFORCED_AUDIBLE:
2143 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2145 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2146 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2148 if (strategy == STRATEGY_SONIFICATION ||
2149 !mStreams[AUDIO_STREAM_ENFORCED_AUDIBLE].mCanBeMuted) {
2150 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2151 if (device == APM_AUDIO_DEVICE_NONE) {
2152 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2155 // The second device used for sonification is the same as the device used by media strategy
2158 case STRATEGY_MEDIA: {
2159 uint32_t device2 = APM_AUDIO_DEVICE_NONE;
2160 if (mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2161 (getA2dpOutput() != APM_AUDIO_DEVICE_NONE) && !mA2dpSuspended) {
2162 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2163 if (device2 == APM_AUDIO_DEVICE_NONE) {
2164 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2166 if (device2 == APM_AUDIO_DEVICE_NONE) {
2167 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2170 if (device2 == APM_AUDIO_DEVICE_NONE) {
2171 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2173 if (device2 == APM_AUDIO_DEVICE_NONE) {
2174 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2176 if (device2 == APM_AUDIO_DEVICE_NONE) {
2177 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2179 if (device2 == APM_AUDIO_DEVICE_NONE) {
2180 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2182 if (device2 == APM_AUDIO_DEVICE_NONE) {
2183 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2185 if (device2 == APM_AUDIO_DEVICE_NONE) {
2186 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2188 if (device2 == APM_AUDIO_DEVICE_NONE) {
2189 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2191 if (device2 == APM_AUDIO_DEVICE_NONE) {
2192 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2195 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2196 // STRATEGY_ENFORCED_AUDIBLE, APM_AUDIO_DEVICE_NONE otherwise
2199 device = mDefaultOutputDevice;
2200 if (device == APM_AUDIO_DEVICE_NONE) {
2201 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2206 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2210 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2214 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2216 for (int i = 0; i < NUM_STRATEGIES; i++) {
2217 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2219 mPreviousOutputs = mOutputs;
2222 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2223 audio_devices_t prevDevice,
2226 // mute/unmute strategies using an incompatible device combination
2227 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2228 // if unmuting, unmute only after the specified delay
2229 if (outputDesc->isDuplicated()) {
2233 uint32_t muteWaitMs = 0;
2234 audio_devices_t device = outputDesc->device();
2235 bool shouldMute = (outputDesc->refCount() != 0) &&
2236 (AudioSystem::popCount(device) >= 2);
2237 // temporary mute output if device selection changes to avoid volume bursts due to
2238 // different per device volumes
2239 bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
2241 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2242 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2243 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2244 bool doMute = false;
2246 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2248 outputDesc->mStrategyMutedByDevice[i] = true;
2249 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2251 outputDesc->mStrategyMutedByDevice[i] = false;
2253 if (doMute || tempMute) {
2254 for (size_t j = 0; j < mOutputs.size(); j++) {
2255 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2256 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2257 == APM_AUDIO_DEVICE_NONE) {
2260 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2261 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2262 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2263 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2264 if (desc->strategyRefCount((routing_strategy)i) != 0) {
2266 setStrategyMute((routing_strategy)i, true, curOutput);
2267 setStrategyMute((routing_strategy)i, false, curOutput,
2268 desc->latency() * 2, device);
2270 if (tempMute || mute) {
2271 if (muteWaitMs < desc->latency()) {
2272 muteWaitMs = desc->latency();
2280 // FIXME: should not need to double latency if volume could be applied immediately by the
2281 // audioflinger mixer. We must account for the delay between now and the next time
2282 // the audioflinger thread for this output will process a buffer (which corresponds to
2283 // one buffer size, usually 1/2 or 1/4 of the latency).
2285 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2286 if (muteWaitMs > delayMs) {
2287 muteWaitMs -= delayMs;
2288 usleep(muteWaitMs * 1000);
2294 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2295 audio_devices_t device,
2299 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2300 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2301 AudioParameter param;
2302 uint32_t muteWaitMs = 0;
2304 if (outputDesc->isDuplicated()) {
2305 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2306 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2309 // filter devices according to output selected
2310 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2312 audio_devices_t prevDevice = outputDesc->mDevice;
2314 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2316 if (device != APM_AUDIO_DEVICE_NONE) {
2317 outputDesc->mDevice = device;
2319 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2321 // Do not change the routing if:
2322 // - the requested device is APM_AUDIO_DEVICE_NONE
2323 // - the requested device is the same as current device and force is not specified.
2324 // Doing this check here allows the caller to call setOutputDevice() without conditions
2325 if ((device == APM_AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2326 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2330 ALOGV("setOutputDevice() changing device");
2332 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2333 mpClientInterface->setParameters(output, param.toString(), delayMs);
2335 // update stream volumes according to new device
2336 applyStreamVolumes(output, device, delayMs);
2341 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2342 uint32_t samplingRate,
2344 uint32_t channelMask)
2346 // Choose an input profile based on the requested capture parameters: select the first available
2347 // profile supporting all requested parameters.
2349 for (size_t i = 0; i < mHwModules.size(); i++)
2351 if (mHwModules[i]->mHandle == 0) {
2354 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2356 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2357 if (profile->isCompatibleProfile(device, samplingRate, format,
2358 channelMask,(audio_output_flags_t)0)) {
2366 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2368 uint32_t device = APM_AUDIO_DEVICE_NONE;
2370 switch(inputSource) {
2371 case AUDIO_SOURCE_DEFAULT:
2372 case AUDIO_SOURCE_MIC:
2373 case AUDIO_SOURCE_VOICE_RECOGNITION:
2374 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2375 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2376 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2377 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2378 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2379 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2380 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2381 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2384 case AUDIO_SOURCE_CAMCORDER:
2385 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2386 device = AUDIO_DEVICE_IN_BACK_MIC;
2387 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2388 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2391 case AUDIO_SOURCE_VOICE_UPLINK:
2392 case AUDIO_SOURCE_VOICE_DOWNLINK:
2393 case AUDIO_SOURCE_VOICE_CALL:
2394 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2395 device = AUDIO_DEVICE_IN_VOICE_CALL;
2399 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2402 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2406 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
2408 for (size_t i = 0; i < mInputs.size(); i++) {
2409 if (mInputs.valueAt(i)->mRefCount > 0) {
2410 return mInputs.keyAt(i);
2417 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2419 if (device == APM_AUDIO_DEVICE_NONE) {
2420 // this happens when forcing a route update and no track is active on an output.
2421 // In this case the returned category is not important.
2422 device = AUDIO_DEVICE_OUT_SPEAKER;
2423 } else if (AudioSystem::popCount(device) > 1) {
2424 // Multiple device selection is either:
2425 // - speaker + one other device: give priority to speaker in this case.
2426 // - one A2DP device + another device: happens with duplicated output. In this case
2427 // retain the device on the A2DP output as the other must not correspond to an active
2428 // selection if not the speaker.
2429 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2430 device = AUDIO_DEVICE_OUT_SPEAKER;
2432 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2436 ALOGW_IF(AudioSystem::popCount(device) != 1,
2437 "getDeviceForVolume() invalid device combination: %08x",
2443 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2445 switch(getDeviceForVolume(device)) {
2446 case AUDIO_DEVICE_OUT_EARPIECE:
2447 return DEVICE_CATEGORY_EARPIECE;
2448 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2449 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2450 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2451 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2452 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2453 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2454 return DEVICE_CATEGORY_HEADSET;
2455 case AUDIO_DEVICE_OUT_SPEAKER:
2456 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2457 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2458 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2459 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2460 case AUDIO_DEVICE_OUT_USB_DEVICE:
2462 return DEVICE_CATEGORY_SPEAKER;
2466 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2469 device_category deviceCategory = getDeviceCategory(device);
2470 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2472 // the volume index in the UI is relative to the min and max volume indices for this stream type
2473 int nbSteps = 1 + curve[VOLMAX].mIndex -
2474 curve[VOLMIN].mIndex;
2475 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2476 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2478 // find what part of the curve this index volume belongs to, or if it's out of bounds
2480 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2482 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2484 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2486 } else if (volIdx <= curve[VOLMAX].mIndex) {
2488 } else { // out of bounds
2492 // linear interpolation in the attenuation table in dB
2493 float decibels = curve[segment].mDBAttenuation +
2494 ((float)(volIdx - curve[segment].mIndex)) *
2495 ( (curve[segment+1].mDBAttenuation -
2496 curve[segment].mDBAttenuation) /
2497 ((float)(curve[segment+1].mIndex -
2498 curve[segment].mIndex)) );
2500 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2502 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2503 curve[segment].mIndex, volIdx,
2504 curve[segment+1].mIndex,
2505 curve[segment].mDBAttenuation,
2507 curve[segment+1].mDBAttenuation,
2510 return amplification;
2513 const AudioPolicyManagerBase::VolumeCurvePoint
2514 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2515 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2518 const AudioPolicyManagerBase::VolumeCurvePoint
2519 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2520 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2523 const AudioPolicyManagerBase::VolumeCurvePoint
2524 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2525 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2528 const AudioPolicyManagerBase::VolumeCurvePoint
2529 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2530 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2533 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2534 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2535 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2536 const AudioPolicyManagerBase::VolumeCurvePoint
2537 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2538 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2541 const AudioPolicyManagerBase::VolumeCurvePoint
2542 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2543 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2546 const AudioPolicyManagerBase::VolumeCurvePoint
2547 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2548 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2549 { // AUDIO_STREAM_VOICE_CALL
2550 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2551 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2552 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2554 { // AUDIO_STREAM_SYSTEM
2555 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2556 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2557 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2559 { // AUDIO_STREAM_RING
2560 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2561 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2562 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2564 { // AUDIO_STREAM_MUSIC
2565 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2566 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2567 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2569 { // AUDIO_STREAM_ALARM
2570 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2571 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2572 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2574 { // AUDIO_STREAM_NOTIFICATION
2575 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2576 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2577 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2579 { // AUDIO_STREAM_BLUETOOTH_SCO
2580 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2581 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2582 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2584 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2585 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2586 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2587 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2589 { // AUDIO_STREAM_DTMF
2590 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2591 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2592 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2594 { // AUDIO_STREAM_TTS
2595 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2596 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2597 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2601 void AudioPolicyManagerBase::initializeVolumeCurves()
2603 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2604 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2605 mStreams[i].mVolumeCurve[j] =
2606 sVolumeProfiles[i][j];
2611 float AudioPolicyManagerBase::computeVolume(int stream,
2613 audio_io_handle_t output,
2614 audio_devices_t device)
2617 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2618 StreamDescriptor &streamDesc = mStreams[stream];
2620 if (device == APM_AUDIO_DEVICE_NONE) {
2621 device = outputDesc->device();
2624 // if volume is not 0 (not muted), force media volume to max on digital output
2625 if (stream == AudioSystem::MUSIC &&
2626 index != mStreams[stream].mIndexMin &&
2627 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2628 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2629 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2630 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2634 volume = volIndexToAmpl(device, streamDesc, index);
2636 // if a headset is connected, apply the following rules to ring tones and notifications
2637 // to avoid sound level bursts in user's ears:
2638 // - always attenuate ring tones and notifications volume by 6dB
2639 // - if music is playing, always limit the volume to current music volume,
2640 // with a minimum threshold at -36dB so that notification is always perceived.
2641 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2642 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
2643 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2644 AUDIO_DEVICE_OUT_WIRED_HEADSET |
2645 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
2646 ((stream_strategy == STRATEGY_SONIFICATION)
2647 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2648 || (stream == AudioSystem::SYSTEM)) &&
2649 streamDesc.mCanBeMuted) {
2650 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2651 // when the phone is ringing we must consider that music could have been paused just before
2652 // by the music application and behave as if music was active if the last music track was
2654 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2655 mLimitRingtoneVolume) {
2656 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
2657 float musicVol = computeVolume(AudioSystem::MUSIC,
2658 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
2661 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2662 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2663 if (volume > minVol) {
2665 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2673 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2675 audio_io_handle_t output,
2676 audio_devices_t device,
2681 // do not change actual stream volume if the stream is muted
2682 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2683 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2684 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2688 // do not change in call volume if bluetooth is connected and vice versa
2689 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2690 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2691 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2692 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2693 return INVALID_OPERATION;
2696 float volume = computeVolume(stream, index, output, device);
2697 // We actually change the volume if:
2698 // - the float value returned by computeVolume() changed
2699 // - the force flag is set
2700 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2702 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2703 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2704 if (stream == AudioSystem::VOICE_CALL ||
2705 stream == AudioSystem::DTMF ||
2706 stream == AudioSystem::BLUETOOTH_SCO) {
2707 // offset value to reflect actual hardware volume that never reaches 0
2708 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2709 volume = 0.01 + 0.99 * volume;
2710 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2712 if (stream == AudioSystem::BLUETOOTH_SCO) {
2713 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2717 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2720 if (stream == AudioSystem::VOICE_CALL ||
2721 stream == AudioSystem::BLUETOOTH_SCO) {
2723 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2724 if (stream == AudioSystem::VOICE_CALL) {
2725 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2730 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2731 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2732 mLastVoiceVolume = voiceVolume;
2739 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2740 audio_devices_t device,
2744 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2746 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2747 checkAndSetVolume(stream,
2748 mStreams[stream].getVolumeIndex(device),
2756 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2758 audio_io_handle_t output,
2760 audio_devices_t device)
2762 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2763 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2764 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2765 setStreamMute(stream, on, output, delayMs, device);
2770 void AudioPolicyManagerBase::setStreamMute(int stream,
2772 audio_io_handle_t output,
2774 audio_devices_t device)
2776 StreamDescriptor &streamDesc = mStreams[stream];
2777 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2778 if (device == APM_AUDIO_DEVICE_NONE) {
2779 device = outputDesc->device();
2782 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
2783 stream, on, output, outputDesc->mMuteCount[stream], device);
2786 if (outputDesc->mMuteCount[stream] == 0) {
2787 if (streamDesc.mCanBeMuted) {
2788 checkAndSetVolume(stream, 0, output, device, delayMs);
2791 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2792 outputDesc->mMuteCount[stream]++;
2794 if (outputDesc->mMuteCount[stream] == 0) {
2795 ALOGV("setStreamMute() unmuting non muted stream!");
2798 if (--outputDesc->mMuteCount[stream] == 0) {
2799 checkAndSetVolume(stream,
2800 streamDesc.getVolumeIndex(device),
2808 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2810 // if the stream pertains to sonification strategy and we are in call we must
2811 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2812 // in the device used for phone strategy and play the tone if the selected device does not
2813 // interfere with the device used for phone strategy
2814 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2815 // many times as there are active tracks on the output
2816 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2817 if ((stream_strategy == STRATEGY_SONIFICATION) ||
2818 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2819 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2820 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2821 stream, starting, outputDesc->mDevice, stateChange);
2822 if (outputDesc->mRefCount[stream]) {
2825 muteCount = outputDesc->mRefCount[stream];
2827 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2828 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2829 for (int i = 0; i < muteCount; i++) {
2830 setStreamMute(stream, starting, mPrimaryOutput);
2833 ALOGV("handleIncallSonification() high visibility");
2834 if (outputDesc->device() &
2835 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2836 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2837 for (int i = 0; i < muteCount; i++) {
2838 setStreamMute(stream, starting, mPrimaryOutput);
2842 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2844 mpClientInterface->stopTone();
2851 bool AudioPolicyManagerBase::isInCall()
2853 return isStateInCall(mPhoneState);
2856 bool AudioPolicyManagerBase::isStateInCall(int state) {
2857 return ((state == AudioSystem::MODE_IN_CALL) ||
2858 (state == AudioSystem::MODE_IN_COMMUNICATION));
2861 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
2862 uint32_t samplingRate,
2863 audio_format_t format,
2864 audio_channel_mask_t channelMask,
2865 audio_output_flags_t flags,
2866 audio_devices_t device)
2868 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2869 (format != 0 && !AudioSystem::isLinearPCM(format)));
2872 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2874 return MAX_EFFECTS_CPU_LOAD;
2877 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2879 return MAX_EFFECTS_MEMORY;
2882 // --- AudioOutputDescriptor class implementation
2884 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2885 const IOProfile *profile)
2886 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
2887 mChannelMask((audio_channel_mask_t)0), mLatency(0),
2888 mFlags((audio_output_flags_t)0), mDevice(APM_AUDIO_DEVICE_NONE),
2889 mOutput1(0), mOutput2(0), mProfile(profile)
2891 // clear usage count for all stream types
2892 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2894 mCurVolume[i] = -1.0;
2898 if (profile != NULL) {
2899 mSamplingRate = profile->mSamplingRates[0];
2900 mFormat = profile->mFormats[0];
2901 mChannelMask = profile->mChannelMasks[0];
2902 mFlags = profile->mFlags;
2906 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2908 if (isDuplicated()) {
2909 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
2915 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
2917 if (isDuplicated()) {
2918 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
2924 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
2925 const AudioOutputDescriptor *outputDesc)
2927 if (isDuplicated()) {
2928 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
2929 } else if (outputDesc->isDuplicated()){
2930 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
2932 return (mProfile->mModule == outputDesc->mProfile->mModule);
2936 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2938 // forward usage count change to attached outputs
2939 if (isDuplicated()) {
2940 mOutput1->changeRefCount(stream, delta);
2941 mOutput2->changeRefCount(stream, delta);
2943 if ((delta + (int)mRefCount[stream]) < 0) {
2944 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2945 mRefCount[stream] = 0;
2948 mRefCount[stream] += delta;
2949 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2952 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2954 uint32_t refcount = 0;
2955 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2956 refcount += mRefCount[i];
2961 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2963 uint32_t refCount = 0;
2964 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2965 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2966 refCount += mRefCount[i];
2972 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
2974 if (isDuplicated()) {
2975 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
2977 return mProfile->mSupportedDevices ;
2981 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2983 const size_t SIZE = 256;
2987 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2988 result.append(buffer);
2989 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2990 result.append(buffer);
2991 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
2992 result.append(buffer);
2993 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2994 result.append(buffer);
2995 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2996 result.append(buffer);
2997 snprintf(buffer, SIZE, " Devices %08x\n", device());
2998 result.append(buffer);
2999 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3000 result.append(buffer);
3001 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3002 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3003 result.append(buffer);
3005 write(fd, result.string(), result.size());
3010 // --- AudioInputDescriptor class implementation
3012 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3013 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3014 mDevice(APM_AUDIO_DEVICE_NONE), mRefCount(0),
3015 mInputSource(0), mProfile(profile)
3019 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3021 const size_t SIZE = 256;
3025 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3026 result.append(buffer);
3027 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3028 result.append(buffer);
3029 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3030 result.append(buffer);
3031 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3032 result.append(buffer);
3033 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3034 result.append(buffer);
3035 write(fd, result.string(), result.size());
3040 // --- StreamDescriptor class implementation
3042 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3043 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3045 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3048 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3050 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3051 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3052 if (mIndexCur.indexOfKey(device) < 0) {
3053 device = AUDIO_DEVICE_OUT_DEFAULT;
3055 return mIndexCur.valueFor(device);
3058 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3060 const size_t SIZE = 256;
3064 snprintf(buffer, SIZE, "%s %02d %02d ",
3065 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3066 result.append(buffer);
3067 for (size_t i = 0; i < mIndexCur.size(); i++) {
3068 snprintf(buffer, SIZE, "%04x : %02d, ",
3070 mIndexCur.valueAt(i));
3071 result.append(buffer);
3073 result.append("\n");
3075 write(fd, result.string(), result.size());
3078 // --- EffectDescriptor class implementation
3080 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3082 const size_t SIZE = 256;
3086 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3087 result.append(buffer);
3088 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3089 result.append(buffer);
3090 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3091 result.append(buffer);
3092 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3093 result.append(buffer);
3094 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3095 result.append(buffer);
3096 write(fd, result.string(), result.size());
3101 // --- IOProfile class implementation
3103 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3104 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3108 AudioPolicyManagerBase::HwModule::~HwModule()
3110 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3111 delete mOutputProfiles[i];
3113 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3114 delete mInputProfiles[i];
3116 free((void *)mName);
3119 void AudioPolicyManagerBase::HwModule::dump(int fd)
3121 const size_t SIZE = 256;
3125 snprintf(buffer, SIZE, " - name: %s\n", mName);
3126 result.append(buffer);
3127 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3128 result.append(buffer);
3129 write(fd, result.string(), result.size());
3130 if (mOutputProfiles.size()) {
3131 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3132 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3133 snprintf(buffer, SIZE, " output %d:\n", i);
3134 write(fd, buffer, strlen(buffer));
3135 mOutputProfiles[i]->dump(fd);
3138 if (mInputProfiles.size()) {
3139 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3140 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3141 snprintf(buffer, SIZE, " input %d:\n", i);
3142 write(fd, buffer, strlen(buffer));
3143 mInputProfiles[i]->dump(fd);
3148 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3149 : mFlags((audio_output_flags_t)0), mModule(module)
3153 AudioPolicyManagerBase::IOProfile::~IOProfile()
3157 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3158 // means a parameter is don't care
3159 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3160 uint32_t samplingRate,
3162 uint32_t channelMask,
3163 audio_output_flags_t flags) const
3165 if ((mSupportedDevices & device) != device) {
3168 if ((mFlags & flags) != flags) {
3171 if (samplingRate != 0) {
3173 for (i = 0; i < mSamplingRates.size(); i++)
3175 if (mSamplingRates[i] == samplingRate) {
3179 if (i == mSamplingRates.size()) {
3185 for (i = 0; i < mFormats.size(); i++)
3187 if (mFormats[i] == format) {
3191 if (i == mFormats.size()) {
3195 if (channelMask != 0) {
3197 for (i = 0; i < mChannelMasks.size(); i++)
3199 if (mChannelMasks[i] == channelMask) {
3203 if (i == mChannelMasks.size()) {
3210 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3212 const size_t SIZE = 256;
3216 snprintf(buffer, SIZE, " - sampling rates: ");
3217 result.append(buffer);
3218 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3219 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3220 result.append(buffer);
3221 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3224 snprintf(buffer, SIZE, " - channel masks: ");
3225 result.append(buffer);
3226 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3227 snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3228 result.append(buffer);
3229 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3232 snprintf(buffer, SIZE, " - formats: ");
3233 result.append(buffer);
3234 for (size_t i = 0; i < mFormats.size(); i++) {
3235 snprintf(buffer, SIZE, "%d", mFormats[i]);
3236 result.append(buffer);
3237 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3240 snprintf(buffer, SIZE, " - devices: %04x\n", mSupportedDevices);
3241 result.append(buffer);
3242 snprintf(buffer, SIZE, " - flags: %04x\n", mFlags);
3243 result.append(buffer);
3245 write(fd, result.string(), result.size());
3248 // --- audio_policy.conf file parsing
3250 struct StringToEnum {
3255 #define STRING_TO_ENUM(string) { #string, string }
3256 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3258 const struct StringToEnum sDeviceNameToEnumTable[] = {
3259 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3260 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3261 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3262 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3263 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3264 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3265 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3266 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3267 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3268 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3269 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3270 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3271 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3272 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3273 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3274 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3275 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3276 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3279 const struct StringToEnum sFlagNameToEnumTable[] = {
3280 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3281 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3282 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3283 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3286 const struct StringToEnum sFormatNameToEnumTable[] = {
3287 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3288 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3289 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3290 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3291 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3294 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3295 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3296 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3297 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3298 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3301 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3302 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3303 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3307 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3311 for (size_t i = 0; i < size; i++) {
3312 if (strcmp(table[i].name, name) == 0) {
3313 ALOGV("stringToEnum() found %s", table[i].name);
3314 return table[i].value;
3320 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3324 // it is OK to cast name to non const here as we are not going to use it after
3325 // strtok() modifies it
3326 char *flagName = strtok(name, "|");
3327 while (flagName != NULL) {
3328 if (strlen(flagName) != 0) {
3329 flag |= stringToEnum(sFlagNameToEnumTable,
3330 ARRAY_SIZE(sFlagNameToEnumTable),
3333 flagName = strtok(NULL, "|");
3335 return (audio_output_flags_t)flag;
3338 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3340 uint32_t device = 0;
3342 char *devName = strtok(name, "|");
3343 while (devName != NULL) {
3344 if (strlen(devName) != 0) {
3345 device |= stringToEnum(sDeviceNameToEnumTable,
3346 ARRAY_SIZE(sDeviceNameToEnumTable),
3349 devName = strtok(NULL, "|");
3354 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3356 char *str = strtok(name, "|");
3358 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3359 // rates should be read from the output stream after it is opened for the first time
3360 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3361 profile->mSamplingRates.add(0);
3365 while (str != NULL) {
3366 uint32_t rate = atoi(str);
3368 ALOGV("loadSamplingRates() adding rate %d", rate);
3369 profile->mSamplingRates.add(rate);
3371 str = strtok(NULL, "|");
3376 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3378 char *str = strtok(name, "|");
3380 // by convention, "0' in the first entry in mFormats indicates the supported formats
3381 // should be read from the output stream after it is opened for the first time
3382 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3383 profile->mFormats.add((audio_format_t)0);
3387 while (str != NULL) {
3388 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3389 ARRAY_SIZE(sFormatNameToEnumTable),
3392 profile->mFormats.add(format);
3394 str = strtok(NULL, "|");
3399 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3401 const char *str = strtok(name, "|");
3403 ALOGV("loadInChannels() %s", name);
3405 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3406 profile->mChannelMasks.add((audio_channel_mask_t)0);
3410 while (str != NULL) {
3411 audio_channel_mask_t channelMask =
3412 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3413 ARRAY_SIZE(sInChannelsNameToEnumTable),
3415 if (channelMask != 0) {
3416 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3417 profile->mChannelMasks.add(channelMask);
3419 str = strtok(NULL, "|");
3424 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3426 const char *str = strtok(name, "|");
3428 ALOGV("loadOutChannels() %s", name);
3430 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3431 // masks should be read from the output stream after it is opened for the first time
3432 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3433 profile->mChannelMasks.add((audio_channel_mask_t)0);
3437 while (str != NULL) {
3438 audio_channel_mask_t channelMask =
3439 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3440 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3442 if (channelMask != 0) {
3443 profile->mChannelMasks.add(channelMask);
3445 str = strtok(NULL, "|");
3450 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3452 cnode *node = root->first_child;
3454 IOProfile *profile = new IOProfile(module);
3457 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3458 loadSamplingRates((char *)node->value, profile);
3459 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3460 loadFormats((char *)node->value, profile);
3461 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3462 loadInChannels((char *)node->value, profile);
3463 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3464 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3468 ALOGW_IF(profile->mSupportedDevices == APM_AUDIO_DEVICE_NONE,
3469 "loadInput() invalid supported devices");
3470 ALOGW_IF(profile->mChannelMasks.size() == 0,
3471 "loadInput() invalid supported channel masks");
3472 ALOGW_IF(profile->mSamplingRates.size() == 0,
3473 "loadInput() invalid supported sampling rates");
3474 ALOGW_IF(profile->mFormats.size() == 0,
3475 "loadInput() invalid supported formats");
3476 if ((profile->mSupportedDevices != APM_AUDIO_DEVICE_NONE) &&
3477 (profile->mChannelMasks.size() != 0) &&
3478 (profile->mSamplingRates.size() != 0) &&
3479 (profile->mFormats.size() != 0)) {
3481 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3483 module->mInputProfiles.add(profile);
3491 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3493 cnode *node = root->first_child;
3495 IOProfile *profile = new IOProfile(module);
3498 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3499 loadSamplingRates((char *)node->value, profile);
3500 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3501 loadFormats((char *)node->value, profile);
3502 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3503 loadOutChannels((char *)node->value, profile);
3504 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3505 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3506 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3507 profile->mFlags = parseFlagNames((char *)node->value);
3511 ALOGW_IF(profile->mSupportedDevices == APM_AUDIO_DEVICE_NONE,
3512 "loadOutput() invalid supported devices");
3513 ALOGW_IF(profile->mChannelMasks.size() == 0,
3514 "loadOutput() invalid supported channel masks");
3515 ALOGW_IF(profile->mSamplingRates.size() == 0,
3516 "loadOutput() invalid supported sampling rates");
3517 ALOGW_IF(profile->mFormats.size() == 0,
3518 "loadOutput() invalid supported formats");
3519 if ((profile->mSupportedDevices != APM_AUDIO_DEVICE_NONE) &&
3520 (profile->mChannelMasks.size() != 0) &&
3521 (profile->mSamplingRates.size() != 0) &&
3522 (profile->mFormats.size() != 0)) {
3524 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3525 profile->mSupportedDevices, profile->mFlags);
3527 module->mOutputProfiles.add(profile);
3535 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3537 cnode *node = config_find(root, OUTPUTS_TAG);
3538 status_t status = NAME_NOT_FOUND;
3540 HwModule *module = new HwModule(root->name);
3543 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3545 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3549 node = node->first_child;
3551 ALOGV("loadHwModule() loading output %s", node->name);
3552 status_t tmpStatus = loadOutput(node, module);
3553 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3559 node = config_find(root, INPUTS_TAG);
3561 node = node->first_child;
3563 ALOGV("loadHwModule() loading input %s", node->name);
3564 status_t tmpStatus = loadInput(node, module);
3565 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3571 if (status == NO_ERROR) {
3572 mHwModules.add(module);
3578 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3580 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3585 node = node->first_child;
3587 ALOGV("loadHwModules() loading module %s", node->name);
3593 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3595 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3599 node = node->first_child;
3601 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3602 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3603 ALOGW_IF(mAttachedOutputDevices == APM_AUDIO_DEVICE_NONE,
3604 "loadGlobalConfig() no attached output devices");
3605 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3606 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3607 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3608 ARRAY_SIZE(sDeviceNameToEnumTable),
3609 (char *)node->value);
3610 ALOGW_IF(mDefaultOutputDevice == APM_AUDIO_DEVICE_NONE,
3611 "loadGlobalConfig() default device not specified");
3612 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3613 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3614 mAvailableInputDevices = parseDeviceNames((char *)node->value);
3615 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3621 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3626 data = (char *)load_file(path, NULL);
3630 root = config_node("", "");
3631 config_load(root, data);
3633 loadGlobalConfig(root);
3634 loadHwModules(root);
3640 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3645 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3650 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3651 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3652 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3654 module = new HwModule("primary");
3656 profile = new IOProfile(module);
3657 profile->mSamplingRates.add(44100);
3658 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3659 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3660 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3661 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3662 module->mOutputProfiles.add(profile);
3664 profile = new IOProfile(module);
3665 profile->mSamplingRates.add(8000);
3666 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3667 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3668 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3669 module->mInputProfiles.add(profile);
3671 mHwModules.add(module);
3674 }; // namespace android