2 * Copyright (C) 2009 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define LOG_TAG "AudioPolicyManagerBase"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20 #include <hardware_legacy/AudioPolicyManagerBase.h>
21 #include <hardware/audio_effect.h>
24 namespace android_audio_legacy {
26 // ----------------------------------------------------------------------------
27 // AudioPolicyInterface implementation
28 // ----------------------------------------------------------------------------
31 status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
32 AudioSystem::device_connection_state state,
33 const char *device_address)
36 LOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
38 // connect/disconnect only 1 device at a time
39 if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
41 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
42 LOGE("setDeviceConnectionState() invalid address: %s", device_address);
46 // handle output devices
47 if (AudioSystem::isOutputDevice(device)) {
50 if (AudioSystem::isA2dpDevice(device)) {
51 LOGE("setDeviceConnectionState() invalid device: %x", device);
58 // handle output device connection
59 case AudioSystem::DEVICE_STATE_AVAILABLE:
60 if (mAvailableOutputDevices & device) {
61 LOGW("setDeviceConnectionState() device already connected: %x", device);
62 return INVALID_OPERATION;
64 LOGV("setDeviceConnectionState() connecting device %x", device);
66 // register new device as available
67 mAvailableOutputDevices |= device;
70 // handle A2DP device connection
71 if (AudioSystem::isA2dpDevice(device)) {
72 status_t status = handleA2dpConnection(device, device_address);
73 if (status != NO_ERROR) {
74 mAvailableOutputDevices &= ~device;
80 if (AudioSystem::isBluetoothScoDevice(device)) {
81 LOGV("setDeviceConnectionState() BT SCO device, address %s", device_address);
82 // keep track of SCO device address
83 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
87 // handle output device disconnection
88 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
89 if (!(mAvailableOutputDevices & device)) {
90 LOGW("setDeviceConnectionState() device not connected: %x", device);
91 return INVALID_OPERATION;
95 LOGV("setDeviceConnectionState() disconnecting device %x", device);
96 // remove device from available output devices
97 mAvailableOutputDevices &= ~device;
100 // handle A2DP device disconnection
101 if (AudioSystem::isA2dpDevice(device)) {
102 status_t status = handleA2dpDisconnection(device, device_address);
103 if (status != NO_ERROR) {
104 mAvailableOutputDevices |= device;
110 if (AudioSystem::isBluetoothScoDevice(device)) {
111 mScoDeviceAddress = "";
117 LOGE("setDeviceConnectionState() invalid state: %x", state);
121 // request routing change if necessary
122 uint32_t newDevice = getNewDevice(mHardwareOutput, false);
125 checkOutputForAllStrategies();
126 // A2DP outputs must be closed after checkOutputForAllStrategies() is executed
127 if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) {
131 updateDeviceForStrategy();
132 setOutputDevice(mHardwareOutput, newDevice);
134 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
135 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
136 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
137 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
138 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
139 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
144 // handle input devices
145 if (AudioSystem::isInputDevice(device)) {
149 // handle input device connection
150 case AudioSystem::DEVICE_STATE_AVAILABLE: {
151 if (mAvailableInputDevices & device) {
152 LOGW("setDeviceConnectionState() device already connected: %d", device);
153 return INVALID_OPERATION;
155 mAvailableInputDevices |= device;
159 // handle input device disconnection
160 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
161 if (!(mAvailableInputDevices & device)) {
162 LOGW("setDeviceConnectionState() device not connected: %d", device);
163 return INVALID_OPERATION;
165 mAvailableInputDevices &= ~device;
169 LOGE("setDeviceConnectionState() invalid state: %x", state);
173 audio_io_handle_t activeInput = getActiveInput();
174 if (activeInput != 0) {
175 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
176 uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
177 if (newDevice != inputDesc->mDevice) {
178 LOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
179 inputDesc->mDevice, newDevice, activeInput);
180 inputDesc->mDevice = newDevice;
181 AudioParameter param = AudioParameter();
182 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
183 mpClientInterface->setParameters(activeInput, param.toString());
190 LOGW("setDeviceConnectionState() invalid device: %x", device);
194 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
195 const char *device_address)
197 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
198 String8 address = String8(device_address);
199 if (AudioSystem::isOutputDevice(device)) {
200 if (device & mAvailableOutputDevices) {
202 if (AudioSystem::isA2dpDevice(device) &&
203 address != "" && mA2dpDeviceAddress != address) {
207 if (AudioSystem::isBluetoothScoDevice(device) &&
208 address != "" && mScoDeviceAddress != address) {
211 state = AudioSystem::DEVICE_STATE_AVAILABLE;
213 } else if (AudioSystem::isInputDevice(device)) {
214 if (device & mAvailableInputDevices) {
215 state = AudioSystem::DEVICE_STATE_AVAILABLE;
222 void AudioPolicyManagerBase::setPhoneState(int state)
224 LOGV("setPhoneState() state %d", state);
225 uint32_t newDevice = 0;
226 if (state < 0 || state >= AudioSystem::NUM_MODES) {
227 LOGW("setPhoneState() invalid state %d", state);
231 if (state == mPhoneState ) {
232 LOGW("setPhoneState() setting same state %d", state);
236 // if leaving call state, handle special case of active streams
237 // pertaining to sonification strategy see handleIncallSonification()
239 LOGV("setPhoneState() in call state management: new state is %d", state);
240 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
241 handleIncallSonification(stream, false, true);
245 // store previous phone state for management of sonification strategy below
246 int oldState = mPhoneState;
250 // are we entering or starting a call
251 if (!isStateInCall(oldState) && isStateInCall(state)) {
252 LOGV(" Entering call in setPhoneState()");
253 // force routing command to audio hardware when starting a call
254 // even if no device change is needed
256 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
257 LOGV(" Exiting call in setPhoneState()");
258 // force routing command to audio hardware when exiting a call
259 // even if no device change is needed
261 } else if (isStateInCall(state) && (state != oldState)) {
262 LOGV(" Switching between telephony and VoIP in setPhoneState()");
263 // force routing command to audio hardware when switching between telephony and VoIP
264 // even if no device change is needed
268 // check for device and output changes triggered by new phone state
269 newDevice = getNewDevice(mHardwareOutput, false);
272 checkOutputForAllStrategies();
274 updateDeviceForStrategy();
276 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
278 // force routing command to audio hardware when ending call
279 // even if no device change is needed
280 if (isStateInCall(oldState) && newDevice == 0) {
281 newDevice = hwOutputDesc->device();
284 // when changing from ring tone to in call mode, mute the ringing tone
285 // immediately and delay the route change to avoid sending the ring tone
286 // tail into the earpiece or headset.
288 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
289 // delay the device change command by twice the output latency to have some margin
290 // and be sure that audio buffers not yet affected by the mute are out when
291 // we actually apply the route change
292 delayMs = hwOutputDesc->mLatency*2;
293 setStreamMute(AudioSystem::RING, true, mHardwareOutput);
296 // change routing is necessary
297 setOutputDevice(mHardwareOutput, newDevice, force, delayMs);
299 // if entering in call state, handle special case of active streams
300 // pertaining to sonification strategy see handleIncallSonification()
301 if (isStateInCall(state)) {
302 LOGV("setPhoneState() in call state management: new state is %d", state);
303 // unmute the ringing tone after a sufficient delay if it was muted before
304 // setting output device above
305 if (oldState == AudioSystem::MODE_RINGTONE) {
306 setStreamMute(AudioSystem::RING, false, mHardwareOutput, MUTE_TIME_MS);
308 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
309 handleIncallSonification(stream, true, true);
313 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
314 if (state == AudioSystem::MODE_RINGTONE &&
315 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
316 mLimitRingtoneVolume = true;
318 mLimitRingtoneVolume = false;
322 void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask)
324 LOGV("setRingerMode() mode %x, mask %x", mode, mask);
329 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
331 LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
333 bool forceVolumeReeval = false;
335 case AudioSystem::FOR_COMMUNICATION:
336 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
337 config != AudioSystem::FORCE_NONE) {
338 LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
341 forceVolumeReeval = true;
342 mForceUse[usage] = config;
344 case AudioSystem::FOR_MEDIA:
345 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
346 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
347 config != AudioSystem::FORCE_ANALOG_DOCK &&
348 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE) {
349 LOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
352 mForceUse[usage] = config;
354 case AudioSystem::FOR_RECORD:
355 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
356 config != AudioSystem::FORCE_NONE) {
357 LOGW("setForceUse() invalid config %d for FOR_RECORD", config);
360 mForceUse[usage] = config;
362 case AudioSystem::FOR_DOCK:
363 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
364 config != AudioSystem::FORCE_BT_DESK_DOCK &&
365 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
366 config != AudioSystem::FORCE_ANALOG_DOCK &&
367 config != AudioSystem::FORCE_DIGITAL_DOCK) {
368 LOGW("setForceUse() invalid config %d for FOR_DOCK", config);
370 forceVolumeReeval = true;
371 mForceUse[usage] = config;
374 LOGW("setForceUse() invalid usage %d", usage);
378 // check for device and output changes triggered by new phone state
379 uint32_t newDevice = getNewDevice(mHardwareOutput, false);
382 checkOutputForAllStrategies();
384 updateDeviceForStrategy();
385 setOutputDevice(mHardwareOutput, newDevice);
386 if (forceVolumeReeval) {
387 applyStreamVolumes(mHardwareOutput, newDevice, 0, true);
390 audio_io_handle_t activeInput = getActiveInput();
391 if (activeInput != 0) {
392 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
393 newDevice = getDeviceForInputSource(inputDesc->mInputSource);
394 if (newDevice != inputDesc->mDevice) {
395 LOGV("setForceUse() changing device from %x to %x for input %d",
396 inputDesc->mDevice, newDevice, activeInput);
397 inputDesc->mDevice = newDevice;
398 AudioParameter param = AudioParameter();
399 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
400 mpClientInterface->setParameters(activeInput, param.toString());
406 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
408 return mForceUse[usage];
411 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
413 LOGV("setSystemProperty() property %s, value %s", property, value);
414 if (strcmp(property, "ro.camera.sound.forced") == 0) {
416 LOGV("ENFORCED_AUDIBLE cannot be muted");
417 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
419 LOGV("ENFORCED_AUDIBLE can be muted");
420 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
425 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
426 uint32_t samplingRate,
429 AudioSystem::output_flags flags)
431 audio_io_handle_t output = 0;
432 uint32_t latency = 0;
433 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
434 uint32_t device = getDeviceForStrategy(strategy);
435 LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
437 #ifdef AUDIO_POLICY_TEST
438 if (mCurOutput != 0) {
439 LOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d",
440 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
442 if (mTestOutputs[mCurOutput] == 0) {
443 LOGV("getOutput() opening test output");
444 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
445 outputDesc->mDevice = mTestDevice;
446 outputDesc->mSamplingRate = mTestSamplingRate;
447 outputDesc->mFormat = mTestFormat;
448 outputDesc->mChannels = mTestChannels;
449 outputDesc->mLatency = mTestLatencyMs;
450 outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
451 outputDesc->mRefCount[stream] = 0;
452 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice,
453 &outputDesc->mSamplingRate,
454 &outputDesc->mFormat,
455 &outputDesc->mChannels,
456 &outputDesc->mLatency,
458 if (mTestOutputs[mCurOutput]) {
459 AudioParameter outputCmd = AudioParameter();
460 outputCmd.addInt(String8("set_id"),mCurOutput);
461 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
462 addOutput(mTestOutputs[mCurOutput], outputDesc);
465 return mTestOutputs[mCurOutput];
467 #endif //AUDIO_POLICY_TEST
469 // open a direct output if required by specified parameters
470 if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) {
472 LOGV("getOutput() opening direct output device %x", device);
473 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
474 outputDesc->mDevice = device;
475 outputDesc->mSamplingRate = samplingRate;
476 outputDesc->mFormat = format;
477 outputDesc->mChannels = channels;
478 outputDesc->mLatency = 0;
479 outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
480 outputDesc->mRefCount[stream] = 0;
481 outputDesc->mStopTime[stream] = 0;
482 output = mpClientInterface->openOutput(&outputDesc->mDevice,
483 &outputDesc->mSamplingRate,
484 &outputDesc->mFormat,
485 &outputDesc->mChannels,
486 &outputDesc->mLatency,
489 // only accept an output with the requeted parameters
491 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
492 (format != 0 && format != outputDesc->mFormat) ||
493 (channels != 0 && channels != outputDesc->mChannels)) {
494 LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
495 samplingRate, format, channels);
497 mpClientInterface->closeOutput(output);
502 addOutput(output, outputDesc);
506 if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
507 channels != AudioSystem::CHANNEL_OUT_STEREO) {
510 // open a non direct output
512 // get which output is suitable for the specified stream. The actual routing change will happen
513 // when startOutput() will be called
514 uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP;
515 if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
517 if (a2dpUsedForSonification() && a2dpDevice != 0) {
518 // if playing on 2 devices among which one is A2DP, use duplicated output
519 LOGV("getOutput() using duplicated output");
520 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device);
521 output = mDuplicatedOutput;
525 // if playing on 2 devices among which none is A2DP, use hardware output
526 output = mHardwareOutput;
528 LOGV("getOutput() using output %d for 2 devices %x", output, device);
531 if (a2dpDevice != 0) {
532 // if playing on A2DP device, use a2dp output
533 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device);
534 output = mA2dpOutput;
538 // if playing on not A2DP device, use hardware output
539 output = mHardwareOutput;
544 LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
545 stream, samplingRate, format, channels, flags);
550 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
551 AudioSystem::stream_type stream,
554 LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
555 ssize_t index = mOutputs.indexOfKey(output);
557 LOGW("startOutput() unknow output %d", output);
561 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
562 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
565 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) {
566 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
570 // incremenent usage count for this stream on the requested output:
571 // NOTE that the usage count is the same for duplicated output and hardware output which is
572 // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
573 outputDesc->changeRefCount(stream, 1);
575 setOutputDevice(output, getNewDevice(output));
577 // handle special case for sonification while in call
579 handleIncallSonification(stream, true, false);
582 // apply volume rules for current stream and device if necessary
583 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
588 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
589 AudioSystem::stream_type stream,
592 LOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
593 ssize_t index = mOutputs.indexOfKey(output);
595 LOGW("stopOutput() unknow output %d", output);
599 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
600 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
602 // handle special case for sonification while in call
604 handleIncallSonification(stream, false, false);
607 if (outputDesc->mRefCount[stream] > 0) {
608 // decrement usage count of this stream on the output
609 outputDesc->changeRefCount(stream, -1);
610 // store time at which the stream was stopped - see isStreamActive()
611 outputDesc->mStopTime[stream] = systemTime();
613 setOutputDevice(output, getNewDevice(output), false, outputDesc->mLatency*2);
616 if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
617 strategy == STRATEGY_SONIFICATION) {
618 setStrategyMute(STRATEGY_MEDIA,
621 mOutputs.valueFor(mHardwareOutput)->mLatency*2);
624 if (output != mHardwareOutput) {
625 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
629 LOGW("stopOutput() refcount is already 0 for output %d", output);
630 return INVALID_OPERATION;
634 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
636 LOGV("releaseOutput() %d", output);
637 ssize_t index = mOutputs.indexOfKey(output);
639 LOGW("releaseOutput() releasing unknown output %d", output);
643 #ifdef AUDIO_POLICY_TEST
644 int testIndex = testOutputIndex(output);
645 if (testIndex != 0) {
646 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
647 if (outputDesc->refCount() == 0) {
648 mpClientInterface->closeOutput(output);
649 delete mOutputs.valueAt(index);
650 mOutputs.removeItem(output);
651 mTestOutputs[testIndex] = 0;
655 #endif //AUDIO_POLICY_TEST
657 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
658 mpClientInterface->closeOutput(output);
659 delete mOutputs.valueAt(index);
660 mOutputs.removeItem(output);
664 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
665 uint32_t samplingRate,
668 AudioSystem::audio_in_acoustics acoustics)
670 audio_io_handle_t input = 0;
671 uint32_t device = getDeviceForInputSource(inputSource);
673 LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
679 // adapt channel selection to input source
680 switch(inputSource) {
681 case AUDIO_SOURCE_VOICE_UPLINK:
682 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
684 case AUDIO_SOURCE_VOICE_DOWNLINK:
685 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
687 case AUDIO_SOURCE_VOICE_CALL:
688 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
694 AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
696 inputDesc->mInputSource = inputSource;
697 inputDesc->mDevice = device;
698 inputDesc->mSamplingRate = samplingRate;
699 inputDesc->mFormat = format;
700 inputDesc->mChannels = channels;
701 inputDesc->mAcoustics = acoustics;
702 inputDesc->mRefCount = 0;
703 input = mpClientInterface->openInput(&inputDesc->mDevice,
704 &inputDesc->mSamplingRate,
706 &inputDesc->mChannels,
707 inputDesc->mAcoustics);
709 // only accept input with the exact requested set of parameters
711 (samplingRate != inputDesc->mSamplingRate) ||
712 (format != inputDesc->mFormat) ||
713 (channels != inputDesc->mChannels)) {
714 LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
715 samplingRate, format, channels);
717 mpClientInterface->closeInput(input);
722 mInputs.add(input, inputDesc);
726 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
728 LOGV("startInput() input %d", input);
729 ssize_t index = mInputs.indexOfKey(input);
731 LOGW("startInput() unknow input %d", input);
734 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
736 #ifdef AUDIO_POLICY_TEST
738 #endif //AUDIO_POLICY_TEST
740 // refuse 2 active AudioRecord clients at the same time
741 if (getActiveInput() != 0) {
742 LOGW("startInput() input %d failed: other input already started", input);
743 return INVALID_OPERATION;
747 AudioParameter param = AudioParameter();
748 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
750 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
751 LOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
753 mpClientInterface->setParameters(input, param.toString());
755 inputDesc->mRefCount = 1;
759 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
761 LOGV("stopInput() input %d", input);
762 ssize_t index = mInputs.indexOfKey(input);
764 LOGW("stopInput() unknow input %d", input);
767 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
769 if (inputDesc->mRefCount == 0) {
770 LOGW("stopInput() input %d already stopped", input);
771 return INVALID_OPERATION;
773 AudioParameter param = AudioParameter();
774 param.addInt(String8(AudioParameter::keyRouting), 0);
775 mpClientInterface->setParameters(input, param.toString());
776 inputDesc->mRefCount = 0;
781 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
783 LOGV("releaseInput() %d", input);
784 ssize_t index = mInputs.indexOfKey(input);
786 LOGW("releaseInput() releasing unknown input %d", input);
789 mpClientInterface->closeInput(input);
790 delete mInputs.valueAt(index);
791 mInputs.removeItem(input);
792 LOGV("releaseInput() exit");
795 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
799 LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
800 if (indexMin < 0 || indexMin >= indexMax) {
801 LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
804 mStreams[stream].mIndexMin = indexMin;
805 mStreams[stream].mIndexMax = indexMax;
808 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
811 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
815 // Force max volume if stream cannot be muted
816 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
818 LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
819 mStreams[stream].mIndexCur = index;
821 // compute and apply stream volume on all outputs according to connected device
822 status_t status = NO_ERROR;
823 for (size_t i = 0; i < mOutputs.size(); i++) {
824 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
825 if (volStatus != NO_ERROR) {
832 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
837 LOGV("getStreamVolumeIndex() stream %d", stream);
838 *index = mStreams[stream].mIndexCur;
842 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
844 LOGV("getOutputForEffect()");
845 // apply simple rule where global effects are attached to the same output as MUSIC streams
846 return getOutput(AudioSystem::MUSIC);
849 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
850 audio_io_handle_t io,
855 ssize_t index = mOutputs.indexOfKey(io);
857 index = mInputs.indexOfKey(io);
859 LOGW("registerEffect() unknown io %d", io);
860 return INVALID_OPERATION;
864 if (mTotalEffectsCpuLoad + desc->cpuLoad > getMaxEffectsCpuLoad()) {
865 LOGW("registerEffect() CPU Load limit exceeded for Fx %s, CPU %f MIPS",
866 desc->name, (float)desc->cpuLoad/10);
867 return INVALID_OPERATION;
869 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
870 LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
871 desc->name, desc->memoryUsage);
872 return INVALID_OPERATION;
874 mTotalEffectsCpuLoad += desc->cpuLoad;
875 mTotalEffectsMemory += desc->memoryUsage;
876 LOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
877 desc->name, io, strategy, session, id);
879 LOGV("registerEffect() CPU %d, memory %d", desc->cpuLoad, desc->memoryUsage);
880 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
882 EffectDescriptor *pDesc = new EffectDescriptor();
883 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
885 pDesc->mStrategy = (routing_strategy)strategy;
886 pDesc->mSession = session;
887 mEffects.add(id, pDesc);
892 status_t AudioPolicyManagerBase::unregisterEffect(int id)
894 ssize_t index = mEffects.indexOfKey(id);
896 LOGW("unregisterEffect() unknown effect ID %d", id);
897 return INVALID_OPERATION;
900 EffectDescriptor *pDesc = mEffects.valueAt(index);
902 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
903 LOGW("unregisterEffect() CPU load %d too high for total %d",
904 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
905 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
907 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
908 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
909 LOGW("unregisterEffect() memory %d too big for total %d",
910 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
911 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
913 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
914 LOGV("unregisterEffect() effect %s, ID %d, CPU %d, memory %d",
915 pDesc->mDesc.name, id, pDesc->mDesc.cpuLoad, pDesc->mDesc.memoryUsage);
916 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
918 mEffects.removeItem(id);
924 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
926 nsecs_t sysTime = systemTime();
927 for (size_t i = 0; i < mOutputs.size(); i++) {
928 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
929 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
937 status_t AudioPolicyManagerBase::dump(int fd)
939 const size_t SIZE = 256;
943 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
944 result.append(buffer);
945 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
946 result.append(buffer);
948 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
949 result.append(buffer);
950 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
951 result.append(buffer);
952 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
953 result.append(buffer);
955 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
956 result.append(buffer);
957 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
958 result.append(buffer);
959 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
960 result.append(buffer);
961 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
962 result.append(buffer);
963 snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
964 result.append(buffer);
965 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
966 result.append(buffer);
967 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
968 result.append(buffer);
969 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
970 result.append(buffer);
971 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
972 result.append(buffer);
973 write(fd, result.string(), result.size());
975 snprintf(buffer, SIZE, "\nOutputs dump:\n");
976 write(fd, buffer, strlen(buffer));
977 for (size_t i = 0; i < mOutputs.size(); i++) {
978 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
979 write(fd, buffer, strlen(buffer));
980 mOutputs.valueAt(i)->dump(fd);
983 snprintf(buffer, SIZE, "\nInputs dump:\n");
984 write(fd, buffer, strlen(buffer));
985 for (size_t i = 0; i < mInputs.size(); i++) {
986 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
987 write(fd, buffer, strlen(buffer));
988 mInputs.valueAt(i)->dump(fd);
991 snprintf(buffer, SIZE, "\nStreams dump:\n");
992 write(fd, buffer, strlen(buffer));
993 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Can be muted\n");
994 write(fd, buffer, strlen(buffer));
995 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
996 snprintf(buffer, SIZE, " %02d", i);
997 mStreams[i].dump(buffer + 3, SIZE);
998 write(fd, buffer, strlen(buffer));
1001 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1002 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1003 write(fd, buffer, strlen(buffer));
1005 snprintf(buffer, SIZE, "Registered effects:\n");
1006 write(fd, buffer, strlen(buffer));
1007 for (size_t i = 0; i < mEffects.size(); i++) {
1008 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1009 write(fd, buffer, strlen(buffer));
1010 mEffects.valueAt(i)->dump(fd);
1017 // ----------------------------------------------------------------------------
1018 // AudioPolicyManagerBase
1019 // ----------------------------------------------------------------------------
1021 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1023 #ifdef AUDIO_POLICY_TEST
1025 #endif //AUDIO_POLICY_TEST
1026 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0),
1027 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1028 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1029 mA2dpSuspended(false)
1031 mpClientInterface = clientInterface;
1033 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1034 mForceUse[i] = AudioSystem::FORCE_NONE;
1037 initializeVolumeCurves();
1039 // devices available by default are speaker, ear piece and microphone
1040 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1041 AudioSystem::DEVICE_OUT_SPEAKER;
1042 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1046 mDuplicatedOutput = 0;
1047 mA2dpDeviceAddress = String8("");
1049 mScoDeviceAddress = String8("");
1051 // open hardware output
1052 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1053 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1054 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1055 &outputDesc->mSamplingRate,
1056 &outputDesc->mFormat,
1057 &outputDesc->mChannels,
1058 &outputDesc->mLatency,
1059 outputDesc->mFlags);
1061 if (mHardwareOutput == 0) {
1062 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1063 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1065 addOutput(mHardwareOutput, outputDesc);
1066 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
1067 //TODO: configure audio effect output stage here
1070 updateDeviceForStrategy();
1071 #ifdef AUDIO_POLICY_TEST
1072 if (mHardwareOutput != 0) {
1073 AudioParameter outputCmd = AudioParameter();
1074 outputCmd.addInt(String8("set_id"), 0);
1075 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1077 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1078 mTestSamplingRate = 44100;
1079 mTestFormat = AudioSystem::PCM_16_BIT;
1080 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1083 mDirectOutput = false;
1084 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1085 mTestOutputs[i] = 0;
1088 const size_t SIZE = 256;
1090 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1091 run(buffer, ANDROID_PRIORITY_AUDIO);
1093 #endif //AUDIO_POLICY_TEST
1096 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1098 #ifdef AUDIO_POLICY_TEST
1100 #endif //AUDIO_POLICY_TEST
1101 for (size_t i = 0; i < mOutputs.size(); i++) {
1102 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1103 delete mOutputs.valueAt(i);
1106 for (size_t i = 0; i < mInputs.size(); i++) {
1107 mpClientInterface->closeInput(mInputs.keyAt(i));
1108 delete mInputs.valueAt(i);
1113 status_t AudioPolicyManagerBase::initCheck()
1115 return (mHardwareOutput == 0) ? NO_INIT : NO_ERROR;
1118 #ifdef AUDIO_POLICY_TEST
1119 bool AudioPolicyManagerBase::threadLoop()
1121 LOGV("entering threadLoop()");
1122 while (!exitPending())
1128 Mutex::Autolock _l(mLock);
1129 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1131 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1132 AudioParameter param = AudioParameter(command);
1134 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1136 LOGV("Test command %s received", command.string());
1138 if (param.get(String8("target"), target) != NO_ERROR) {
1141 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1142 param.remove(String8("test_cmd_policy_output"));
1143 mCurOutput = valueInt;
1145 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1146 param.remove(String8("test_cmd_policy_direct"));
1147 if (value == "false") {
1148 mDirectOutput = false;
1149 } else if (value == "true") {
1150 mDirectOutput = true;
1153 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1154 param.remove(String8("test_cmd_policy_input"));
1155 mTestInput = valueInt;
1158 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1159 param.remove(String8("test_cmd_policy_format"));
1160 int format = AudioSystem::INVALID_FORMAT;
1161 if (value == "PCM 16 bits") {
1162 format = AudioSystem::PCM_16_BIT;
1163 } else if (value == "PCM 8 bits") {
1164 format = AudioSystem::PCM_8_BIT;
1165 } else if (value == "Compressed MP3") {
1166 format = AudioSystem::MP3;
1168 if (format != AudioSystem::INVALID_FORMAT) {
1169 if (target == "Manager") {
1170 mTestFormat = format;
1171 } else if (mTestOutputs[mCurOutput] != 0) {
1172 AudioParameter outputParam = AudioParameter();
1173 outputParam.addInt(String8("format"), format);
1174 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1178 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1179 param.remove(String8("test_cmd_policy_channels"));
1182 if (value == "Channels Stereo") {
1183 channels = AudioSystem::CHANNEL_OUT_STEREO;
1184 } else if (value == "Channels Mono") {
1185 channels = AudioSystem::CHANNEL_OUT_MONO;
1187 if (channels != 0) {
1188 if (target == "Manager") {
1189 mTestChannels = channels;
1190 } else if (mTestOutputs[mCurOutput] != 0) {
1191 AudioParameter outputParam = AudioParameter();
1192 outputParam.addInt(String8("channels"), channels);
1193 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1197 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1198 param.remove(String8("test_cmd_policy_sampleRate"));
1199 if (valueInt >= 0 && valueInt <= 96000) {
1200 int samplingRate = valueInt;
1201 if (target == "Manager") {
1202 mTestSamplingRate = samplingRate;
1203 } else if (mTestOutputs[mCurOutput] != 0) {
1204 AudioParameter outputParam = AudioParameter();
1205 outputParam.addInt(String8("sampling_rate"), samplingRate);
1206 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1211 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1212 param.remove(String8("test_cmd_policy_reopen"));
1214 mpClientInterface->closeOutput(mHardwareOutput);
1215 delete mOutputs.valueFor(mHardwareOutput);
1216 mOutputs.removeItem(mHardwareOutput);
1218 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1219 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1220 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1221 &outputDesc->mSamplingRate,
1222 &outputDesc->mFormat,
1223 &outputDesc->mChannels,
1224 &outputDesc->mLatency,
1225 outputDesc->mFlags);
1226 if (mHardwareOutput == 0) {
1227 LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1228 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1230 AudioParameter outputCmd = AudioParameter();
1231 outputCmd.addInt(String8("set_id"), 0);
1232 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1233 addOutput(mHardwareOutput, outputDesc);
1238 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1244 void AudioPolicyManagerBase::exit()
1247 AutoMutex _l(mLock);
1249 mWaitWorkCV.signal();
1251 requestExitAndWait();
1254 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1256 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1257 if (output == mTestOutputs[i]) return i;
1261 #endif //AUDIO_POLICY_TEST
1265 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1267 outputDesc->mId = id;
1268 mOutputs.add(id, outputDesc);
1273 status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1274 const char *device_address)
1276 // when an A2DP device is connected, open an A2DP and a duplicated output
1277 LOGV("opening A2DP output for device %s", device_address);
1278 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1279 outputDesc->mDevice = device;
1280 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1281 &outputDesc->mSamplingRate,
1282 &outputDesc->mFormat,
1283 &outputDesc->mChannels,
1284 &outputDesc->mLatency,
1285 outputDesc->mFlags);
1287 // add A2DP output descriptor
1288 addOutput(mA2dpOutput, outputDesc);
1290 //TODO: configure audio effect output stage here
1292 // set initial stream volume for A2DP device
1293 applyStreamVolumes(mA2dpOutput, device);
1294 if (a2dpUsedForSonification()) {
1295 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1297 if (mDuplicatedOutput != 0 ||
1298 !a2dpUsedForSonification()) {
1299 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1301 AudioParameter param;
1302 param.add(String8("a2dp_sink_address"), String8(device_address));
1303 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1304 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1306 if (a2dpUsedForSonification()) {
1307 // add duplicated output descriptor
1308 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1309 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1310 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1311 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1312 dupOutputDesc->mFormat = outputDesc->mFormat;
1313 dupOutputDesc->mChannels = outputDesc->mChannels;
1314 dupOutputDesc->mLatency = outputDesc->mLatency;
1315 addOutput(mDuplicatedOutput, dupOutputDesc);
1316 applyStreamVolumes(mDuplicatedOutput, device);
1319 LOGW("getOutput() could not open duplicated output for %d and %d",
1320 mHardwareOutput, mA2dpOutput);
1321 mpClientInterface->closeOutput(mA2dpOutput);
1322 mOutputs.removeItem(mA2dpOutput);
1328 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1332 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1334 if (!a2dpUsedForSonification()) {
1335 // mute music on A2DP output if a notification or ringtone is playing
1336 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1337 for (uint32_t i = 0; i < refCount; i++) {
1338 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1342 mA2dpSuspended = false;
1347 status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1348 const char *device_address)
1350 if (mA2dpOutput == 0) {
1351 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1352 return INVALID_OPERATION;
1355 if (mA2dpDeviceAddress != device_address) {
1356 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1357 return INVALID_OPERATION;
1360 // mute media strategy to avoid outputting sound on hardware output while music stream
1361 // is switched from A2DP output and before music is paused by music application
1362 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
1363 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
1365 if (!a2dpUsedForSonification()) {
1366 // unmute music on A2DP output if a notification or ringtone is playing
1367 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1368 for (uint32_t i = 0; i < refCount; i++) {
1369 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1372 mA2dpDeviceAddress = "";
1373 mA2dpSuspended = false;
1377 void AudioPolicyManagerBase::closeA2dpOutputs()
1380 LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1382 if (mDuplicatedOutput != 0) {
1383 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1384 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1385 // As all active tracks on duplicated output will be deleted,
1386 // and as they were also referenced on hardware output, the reference
1387 // count for their stream type must be adjusted accordingly on
1389 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1390 int refCount = dupOutputDesc->mRefCount[i];
1391 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1394 mpClientInterface->closeOutput(mDuplicatedOutput);
1395 delete mOutputs.valueFor(mDuplicatedOutput);
1396 mOutputs.removeItem(mDuplicatedOutput);
1397 mDuplicatedOutput = 0;
1399 if (mA2dpOutput != 0) {
1400 AudioParameter param;
1401 param.add(String8("closing"), String8("true"));
1402 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1404 mpClientInterface->closeOutput(mA2dpOutput);
1405 delete mOutputs.valueFor(mA2dpOutput);
1406 mOutputs.removeItem(mA2dpOutput);
1411 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1413 uint32_t prevDevice = getDeviceForStrategy(strategy);
1414 uint32_t curDevice = getDeviceForStrategy(strategy, false);
1415 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1416 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1417 audio_io_handle_t srcOutput = 0;
1418 audio_io_handle_t dstOutput = 0;
1420 if (a2dpWasUsed && !a2dpIsUsed) {
1421 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
1422 dstOutput = mHardwareOutput;
1424 LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1425 srcOutput = mDuplicatedOutput;
1427 LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1428 srcOutput = mA2dpOutput;
1431 if (a2dpIsUsed && !a2dpWasUsed) {
1432 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
1433 srcOutput = mHardwareOutput;
1435 LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1436 dstOutput = mDuplicatedOutput;
1438 LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1439 dstOutput = mA2dpOutput;
1443 if (srcOutput != 0 && dstOutput != 0) {
1444 // Move effects associated to this strategy from previous output to new output
1445 for (size_t i = 0; i < mEffects.size(); i++) {
1446 EffectDescriptor *desc = mEffects.valueAt(i);
1447 if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1448 desc->mStrategy == strategy &&
1449 desc->mIo == srcOutput) {
1450 LOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
1451 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
1452 desc->mIo = dstOutput;
1455 // Move tracks associated to this strategy from previous output to new output
1456 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1457 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1458 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
1464 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1466 checkOutputForStrategy(STRATEGY_PHONE);
1467 checkOutputForStrategy(STRATEGY_SONIFICATION);
1468 checkOutputForStrategy(STRATEGY_MEDIA);
1469 checkOutputForStrategy(STRATEGY_DTMF);
1472 void AudioPolicyManagerBase::checkA2dpSuspend()
1474 // suspend A2DP output if:
1475 // (NOT already suspended) &&
1476 // ((SCO device is connected &&
1477 // (forced usage for communication || for record is SCO))) ||
1478 // (phone state is ringing || in call)
1480 // restore A2DP output if:
1481 // (Already suspended) &&
1482 // ((SCO device is NOT connected ||
1483 // (forced usage NOT for communication && NOT for record is SCO))) &&
1484 // (phone state is NOT ringing && NOT in call)
1486 if (mA2dpOutput == 0) {
1490 if (mA2dpSuspended) {
1491 if (((mScoDeviceAddress == "") ||
1492 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1493 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1494 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1495 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1497 mpClientInterface->restoreOutput(mA2dpOutput);
1498 mA2dpSuspended = false;
1501 if (((mScoDeviceAddress != "") &&
1502 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1503 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1504 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1505 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1507 mpClientInterface->suspendOutput(mA2dpOutput);
1508 mA2dpSuspended = true;
1516 uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1518 uint32_t device = 0;
1520 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1521 // check the following by order of priority to request a routing change if necessary:
1522 // 1: we are in call or the strategy phone is active on the hardware output:
1523 // use device for strategy phone
1524 // 2: the strategy sonification is active on the hardware output:
1525 // use device for strategy sonification
1526 // 3: the strategy media is active on the hardware output:
1527 // use device for strategy media
1528 // 4: the strategy DTMF is active on the hardware output:
1529 // use device for strategy DTMF
1531 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1532 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1533 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1534 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1535 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1536 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1537 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1538 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1541 LOGV("getNewDevice() selected device %x", device);
1545 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1546 return (uint32_t)getStrategy(stream);
1549 uint32_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1551 // By checking the range of stream before calling getStrategy, we avoid
1552 // getStrategy's behavior for invalid streams. getStrategy would do a LOGE
1553 // and then return STRATEGY_MEDIA, but we want to return the empty set.
1554 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1557 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1558 devices = getDeviceForStrategy(strategy, true);
1563 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1564 AudioSystem::stream_type stream) {
1565 // stream to strategy mapping
1567 case AudioSystem::VOICE_CALL:
1568 case AudioSystem::BLUETOOTH_SCO:
1569 return STRATEGY_PHONE;
1570 case AudioSystem::RING:
1571 case AudioSystem::NOTIFICATION:
1572 case AudioSystem::ALARM:
1573 case AudioSystem::ENFORCED_AUDIBLE:
1574 return STRATEGY_SONIFICATION;
1575 case AudioSystem::DTMF:
1576 return STRATEGY_DTMF;
1578 LOGE("unknown stream type");
1579 case AudioSystem::SYSTEM:
1580 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1581 // while key clicks are played produces a poor result
1582 case AudioSystem::TTS:
1583 case AudioSystem::MUSIC:
1584 return STRATEGY_MEDIA;
1588 uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1590 uint32_t device = 0;
1593 LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1594 return mDeviceForStrategy[strategy];
1600 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1601 device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1604 // when in call, DTMF and PHONE strategies follow the same rules
1607 case STRATEGY_PHONE:
1608 // for phone strategy, we first consider the forced use and then the available devices by order
1610 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1611 case AudioSystem::FORCE_BT_SCO:
1612 if (!isInCall() || strategy != STRATEGY_DTMF) {
1613 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1616 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1618 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1620 // if SCO device is requested but no SCO device is available, fall back to default case
1623 default: // FORCE_NONE
1624 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1626 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1629 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
1630 if (!isInCall() && !mA2dpSuspended) {
1631 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1633 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1637 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1639 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1641 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1643 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1645 LOGE("getDeviceForStrategy() earpiece device not found");
1649 case AudioSystem::FORCE_SPEAKER:
1651 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1652 // A2DP speaker when forcing to speaker output
1653 if (!isInCall() && !mA2dpSuspended) {
1654 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1658 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1660 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1662 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1664 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1666 LOGE("getDeviceForStrategy() speaker device not found");
1672 case STRATEGY_SONIFICATION:
1674 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1675 // handleIncallSonification().
1677 device = getDeviceForStrategy(STRATEGY_PHONE, false);
1680 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1682 LOGE("getDeviceForStrategy() speaker device not found");
1684 // The second device used for sonification is the same as the device used by media strategy
1687 case STRATEGY_MEDIA: {
1688 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1690 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1693 if ((mA2dpOutput != 0) && !mA2dpSuspended &&
1694 (strategy != STRATEGY_SONIFICATION || a2dpUsedForSonification())) {
1696 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1699 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1702 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1707 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1710 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1713 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1716 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1719 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
1722 LOGE("getDeviceForStrategy() speaker device not found");
1727 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1731 LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1735 void AudioPolicyManagerBase::updateDeviceForStrategy()
1737 for (int i = 0; i < NUM_STRATEGIES; i++) {
1738 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1742 void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1744 LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1745 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1748 if (outputDesc->isDuplicated()) {
1749 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1750 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1754 // filter devices according to output selected
1755 if (output == mA2dpOutput) {
1756 device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
1758 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
1762 uint32_t prevDevice = (uint32_t)outputDesc->device();
1763 // Do not change the routing if:
1764 // - the requestede device is 0
1765 // - the requested device is the same as current device and force is not specified.
1766 // Doing this check here allows the caller to call setOutputDevice() without conditions
1767 if ((device == 0 || device == prevDevice) && !force) {
1768 LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1772 outputDesc->mDevice = device;
1773 // mute media streams if both speaker and headset are selected
1774 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1775 setStrategyMute(STRATEGY_MEDIA, true, output);
1776 // wait for the PCM output buffers to empty before proceeding with the rest of the command
1777 usleep(outputDesc->mLatency*2*1000);
1781 AudioParameter param = AudioParameter();
1782 param.addInt(String8(AudioParameter::keyRouting), (int)device);
1783 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1784 // update stream volumes according to new device
1785 applyStreamVolumes(output, device, delayMs);
1787 // if changing from a combined headset + speaker route, unmute media streams
1788 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1789 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1793 uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1797 switch(inputSource) {
1798 case AUDIO_SOURCE_DEFAULT:
1799 case AUDIO_SOURCE_MIC:
1800 case AUDIO_SOURCE_VOICE_RECOGNITION:
1801 case AUDIO_SOURCE_VOICE_COMMUNICATION:
1802 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1803 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1804 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1805 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1806 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1808 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1811 case AUDIO_SOURCE_CAMCORDER:
1812 if (hasBackMicrophone()) {
1813 device = AudioSystem::DEVICE_IN_BACK_MIC;
1815 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1818 case AUDIO_SOURCE_VOICE_UPLINK:
1819 case AUDIO_SOURCE_VOICE_DOWNLINK:
1820 case AUDIO_SOURCE_VOICE_CALL:
1821 device = AudioSystem::DEVICE_IN_VOICE_CALL;
1824 LOGW("getDeviceForInputSource() invalid input source %d", inputSource);
1828 LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1832 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1834 for (size_t i = 0; i < mInputs.size(); i++) {
1835 if (mInputs.valueAt(i)->mRefCount > 0) {
1836 return mInputs.keyAt(i);
1842 float AudioPolicyManagerBase::volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc,
1844 // the volume index in the UI is relative to the min and max volume indices for this stream type
1845 int nbSteps = 1 + streamDesc.mVolIndex[StreamDescriptor::VOLMAX] -
1846 streamDesc.mVolIndex[StreamDescriptor::VOLMIN];
1847 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
1848 (streamDesc.mIndexMax - streamDesc.mIndexMin);
1850 // find what part of the curve this index volume belongs to, or if it's out of bounds
1852 if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLMIN]) { // out of bounds
1854 } else if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLKNEE1]) {
1856 } else if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLKNEE2]) {
1858 } else if (volIdx <= streamDesc.mVolIndex[StreamDescriptor::VOLMAX]) {
1860 } else { // out of bounds
1864 // linear interpolation in the attenuation table in dB
1865 float decibels = streamDesc.mVolDbAtt[segment] +
1866 ((float)(volIdx - streamDesc.mVolIndex[segment])) *
1867 ( (streamDesc.mVolDbAtt[segment+1] - streamDesc.mVolDbAtt[segment]) /
1868 ((float)(streamDesc.mVolIndex[segment+1] - streamDesc.mVolIndex[segment])) );
1870 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
1872 LOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
1873 streamDesc.mVolIndex[segment], volIdx, streamDesc.mVolIndex[segment+1],
1874 streamDesc.mVolDbAtt[segment], decibels, streamDesc.mVolDbAtt[segment+1],
1877 return amplification;
1880 void AudioPolicyManagerBase::initializeVolumeCurves() {
1881 // initialize the volume curves to a (-49.5 - 0 dB) attenuation in 0.5dB steps
1882 for (int i=0 ; i< AudioSystem::NUM_STREAM_TYPES ; i++) {
1883 mStreams[i].mVolIndex[StreamDescriptor::VOLMIN] = 1;
1884 mStreams[i].mVolDbAtt[StreamDescriptor::VOLMIN] = -49.5f;
1885 mStreams[i].mVolIndex[StreamDescriptor::VOLKNEE1] = 33;
1886 mStreams[i].mVolDbAtt[StreamDescriptor::VOLKNEE1] = -33.5f;
1887 mStreams[i].mVolIndex[StreamDescriptor::VOLKNEE2] = 66;
1888 mStreams[i].mVolDbAtt[StreamDescriptor::VOLKNEE2] = -17.0f;
1889 // here we use 100 steps to avoid rounding errors
1890 // when computing the volume in volIndexToAmpl()
1891 mStreams[i].mVolIndex[StreamDescriptor::VOLMAX] = 100;
1892 mStreams[i].mVolDbAtt[StreamDescriptor::VOLMAX] = 0.0f;
1895 // Modification for music: more attenuation for lower volumes, finer steps at high volumes
1896 mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLMIN] = 1;
1897 mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLMIN] = -58.0f;
1898 mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLKNEE1] = 20;
1899 mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLKNEE1] = -40.0f;
1900 mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLKNEE2] = 60;
1901 mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLKNEE2] = -17.0f;
1902 mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLMAX] = 100;
1903 mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLMAX] = 0.0f;
1906 float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
1909 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1910 StreamDescriptor &streamDesc = mStreams[stream];
1913 device = outputDesc->device();
1916 // if volume is not 0 (not muted), force media volume to max on digital output
1917 if (stream == AudioSystem::MUSIC &&
1918 index != mStreams[stream].mIndexMin &&
1919 device == AudioSystem::DEVICE_OUT_AUX_DIGITAL) {
1923 volume = volIndexToAmpl(device, streamDesc, index);
1925 // if a headset is connected, apply the following rules to ring tones and notifications
1926 // to avoid sound level bursts in user's ears:
1927 // - always attenuate ring tones and notifications volume by 6dB
1928 // - if music is playing, always limit the volume to current music volume,
1929 // with a minimum threshold at -36dB so that notification is always perceived.
1931 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
1932 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
1933 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
1934 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
1935 ((getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) ||
1936 (stream == AudioSystem::SYSTEM)) &&
1937 streamDesc.mCanBeMuted) {
1938 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
1939 // when the phone is ringing we must consider that music could have been paused just before
1940 // by the music application and behave as if music was active if the last music track was
1942 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
1943 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
1944 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
1945 if (volume > minVol) {
1947 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
1955 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
1958 // do not change actual stream volume if the stream is muted
1959 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
1960 LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
1964 // do not change in call volume if bluetooth is connected and vice versa
1965 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1966 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
1967 LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1968 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
1969 return INVALID_OPERATION;
1972 float volume = computeVolume(stream, index, output, device);
1973 // We actually change the volume if:
1974 // - the float value returned by computeVolume() changed
1975 // - the force flag is set
1976 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
1978 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
1979 LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
1980 if (stream == AudioSystem::VOICE_CALL ||
1981 stream == AudioSystem::DTMF ||
1982 stream == AudioSystem::BLUETOOTH_SCO) {
1983 // offset value to reflect actual hardware volume that never reaches 0
1984 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
1985 volume = 0.01 + 0.99 * volume;
1986 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
1988 if (stream == AudioSystem::BLUETOOTH_SCO) {
1989 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
1993 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
1996 if (stream == AudioSystem::VOICE_CALL ||
1997 stream == AudioSystem::BLUETOOTH_SCO) {
1999 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2000 if (stream == AudioSystem::VOICE_CALL) {
2001 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2006 if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {
2007 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2008 mLastVoiceVolume = voiceVolume;
2015 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs, bool force)
2017 LOGV("applyStreamVolumes() for output %d and device %x", output, device);
2019 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2020 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs, force);
2024 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
2026 LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2027 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2028 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2029 setStreamMute(stream, on, output, delayMs);
2034 void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
2036 StreamDescriptor &streamDesc = mStreams[stream];
2037 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2039 LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
2042 if (outputDesc->mMuteCount[stream] == 0) {
2043 if (streamDesc.mCanBeMuted) {
2044 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
2047 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2048 outputDesc->mMuteCount[stream]++;
2050 if (outputDesc->mMuteCount[stream] == 0) {
2051 LOGW("setStreamMute() unmuting non muted stream!");
2054 if (--outputDesc->mMuteCount[stream] == 0) {
2055 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
2060 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2062 // if the stream pertains to sonification strategy and we are in call we must
2063 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2064 // in the device used for phone strategy and play the tone if the selected device does not
2065 // interfere with the device used for phone strategy
2066 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2067 // many times as there are active tracks on the output
2069 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
2070 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
2071 LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2072 stream, starting, outputDesc->mDevice, stateChange);
2073 if (outputDesc->mRefCount[stream]) {
2076 muteCount = outputDesc->mRefCount[stream];
2078 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2079 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2080 for (int i = 0; i < muteCount; i++) {
2081 setStreamMute(stream, starting, mHardwareOutput);
2084 LOGV("handleIncallSonification() high visibility");
2085 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
2086 LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2087 for (int i = 0; i < muteCount; i++) {
2088 setStreamMute(stream, starting, mHardwareOutput);
2092 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2094 mpClientInterface->stopTone();
2101 bool AudioPolicyManagerBase::isInCall()
2103 return isStateInCall(mPhoneState);
2106 bool AudioPolicyManagerBase::isStateInCall(int state) {
2107 return ((state == AudioSystem::MODE_IN_CALL) ||
2108 (state == AudioSystem::MODE_IN_COMMUNICATION));
2111 bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
2112 uint32_t samplingRate,
2115 AudioSystem::output_flags flags,
2118 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2119 (format !=0 && !AudioSystem::isLinearPCM(format)));
2122 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2124 return MAX_EFFECTS_CPU_LOAD;
2127 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2129 return MAX_EFFECTS_MEMORY;
2132 // --- AudioOutputDescriptor class implementation
2134 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
2135 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
2136 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
2138 // clear usage count for all stream types
2139 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2141 mCurVolume[i] = -1.0;
2147 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2149 uint32_t device = 0;
2150 if (isDuplicated()) {
2151 device = mOutput1->mDevice | mOutput2->mDevice;
2158 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2160 // forward usage count change to attached outputs
2161 if (isDuplicated()) {
2162 mOutput1->changeRefCount(stream, delta);
2163 mOutput2->changeRefCount(stream, delta);
2165 if ((delta + (int)mRefCount[stream]) < 0) {
2166 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2167 mRefCount[stream] = 0;
2170 mRefCount[stream] += delta;
2171 LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2174 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2176 uint32_t refcount = 0;
2177 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2178 refcount += mRefCount[i];
2183 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2185 uint32_t refCount = 0;
2186 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2187 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2188 refCount += mRefCount[i];
2194 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2196 const size_t SIZE = 256;
2200 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2201 result.append(buffer);
2202 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2203 result.append(buffer);
2204 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2205 result.append(buffer);
2206 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2207 result.append(buffer);
2208 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2209 result.append(buffer);
2210 snprintf(buffer, SIZE, " Devices %08x\n", device());
2211 result.append(buffer);
2212 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2213 result.append(buffer);
2214 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2215 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2216 result.append(buffer);
2218 write(fd, result.string(), result.size());
2223 // --- AudioInputDescriptor class implementation
2225 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
2226 : mSamplingRate(0), mFormat(0), mChannels(0),
2227 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0),
2232 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2234 const size_t SIZE = 256;
2238 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2239 result.append(buffer);
2240 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2241 result.append(buffer);
2242 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2243 result.append(buffer);
2244 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2245 result.append(buffer);
2246 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2247 result.append(buffer);
2248 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2249 result.append(buffer);
2250 write(fd, result.string(), result.size());
2255 // --- StreamDescriptor class implementation
2257 void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
2259 snprintf(buffer, size, " %02d %02d %02d %d\n",
2266 // --- EffectDescriptor class implementation
2268 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2270 const size_t SIZE = 256;
2274 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
2275 result.append(buffer);
2276 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2277 result.append(buffer);
2278 snprintf(buffer, SIZE, " Session: %d\n", mSession);
2279 result.append(buffer);
2280 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
2281 result.append(buffer);
2282 write(fd, result.string(), result.size());
2289 }; // namespace android