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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV(" 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 ALOGV(" 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 ALOGV(" 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 ALOGV("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 ALOGV("setRingerMode() mode %x, mask %x", mode, mask);
329 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
331 ALOGV("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 ALOGV("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 ALOGV("setSystemProperty() property %s, value %s", property, value);
414 if (strcmp(property, "ro.camera.sound.forced") == 0) {
416 ALOGV("ENFORCED_AUDIBLE cannot be muted");
417 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
419 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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 ALOGV("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() &&
566 (strategy == STRATEGY_SONIFICATION || strategy == STRATEGY_ENFORCED_AUDIBLE)) {
567 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
571 // incremenent usage count for this stream on the requested output:
572 // NOTE that the usage count is the same for duplicated output and hardware output which is
573 // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
574 outputDesc->changeRefCount(stream, 1);
576 uint32_t prevDevice = outputDesc->mDevice;
577 setOutputDevice(output, getNewDevice(output));
579 // handle special case for sonification while in call
581 handleIncallSonification(stream, true, false);
584 // apply volume rules for current stream and device if necessary
585 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
587 // FIXME: need a delay to make sure that audio path switches to speaker before sound
588 // starts. Should be platform specific?
589 if (stream == AudioSystem::ENFORCED_AUDIBLE &&
590 prevDevice != outputDesc->mDevice) {
591 usleep(outputDesc->mLatency*4*1000);
597 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
598 AudioSystem::stream_type stream,
601 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
602 ssize_t index = mOutputs.indexOfKey(output);
604 LOGW("stopOutput() unknow output %d", output);
608 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
609 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
611 // handle special case for sonification while in call
613 handleIncallSonification(stream, false, false);
616 if (outputDesc->mRefCount[stream] > 0) {
617 // decrement usage count of this stream on the output
618 outputDesc->changeRefCount(stream, -1);
619 // store time at which the stream was stopped - see isStreamActive()
620 outputDesc->mStopTime[stream] = systemTime();
622 setOutputDevice(output, getNewDevice(output), false, outputDesc->mLatency*2);
625 if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
626 (strategy == STRATEGY_SONIFICATION || strategy == STRATEGY_ENFORCED_AUDIBLE)) {
627 setStrategyMute(STRATEGY_MEDIA,
630 mOutputs.valueFor(mHardwareOutput)->mLatency*2);
633 if (output != mHardwareOutput) {
634 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
638 LOGW("stopOutput() refcount is already 0 for output %d", output);
639 return INVALID_OPERATION;
643 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
645 ALOGV("releaseOutput() %d", output);
646 ssize_t index = mOutputs.indexOfKey(output);
648 LOGW("releaseOutput() releasing unknown output %d", output);
652 #ifdef AUDIO_POLICY_TEST
653 int testIndex = testOutputIndex(output);
654 if (testIndex != 0) {
655 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
656 if (outputDesc->refCount() == 0) {
657 mpClientInterface->closeOutput(output);
658 delete mOutputs.valueAt(index);
659 mOutputs.removeItem(output);
660 mTestOutputs[testIndex] = 0;
664 #endif //AUDIO_POLICY_TEST
666 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
667 mpClientInterface->closeOutput(output);
668 delete mOutputs.valueAt(index);
669 mOutputs.removeItem(output);
673 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
674 uint32_t samplingRate,
677 AudioSystem::audio_in_acoustics acoustics)
679 audio_io_handle_t input = 0;
680 uint32_t device = getDeviceForInputSource(inputSource);
682 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
688 // adapt channel selection to input source
689 switch(inputSource) {
690 case AUDIO_SOURCE_VOICE_UPLINK:
691 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
693 case AUDIO_SOURCE_VOICE_DOWNLINK:
694 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
696 case AUDIO_SOURCE_VOICE_CALL:
697 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
703 AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
705 inputDesc->mInputSource = inputSource;
706 inputDesc->mDevice = device;
707 inputDesc->mSamplingRate = samplingRate;
708 inputDesc->mFormat = format;
709 inputDesc->mChannels = channels;
710 inputDesc->mAcoustics = acoustics;
711 inputDesc->mRefCount = 0;
712 input = mpClientInterface->openInput(&inputDesc->mDevice,
713 &inputDesc->mSamplingRate,
715 &inputDesc->mChannels,
716 inputDesc->mAcoustics);
718 // only accept input with the exact requested set of parameters
720 (samplingRate != inputDesc->mSamplingRate) ||
721 (format != inputDesc->mFormat) ||
722 (channels != inputDesc->mChannels)) {
723 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
724 samplingRate, format, channels);
726 mpClientInterface->closeInput(input);
731 mInputs.add(input, inputDesc);
735 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
737 ALOGV("startInput() input %d", input);
738 ssize_t index = mInputs.indexOfKey(input);
740 LOGW("startInput() unknow input %d", input);
743 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
745 #ifdef AUDIO_POLICY_TEST
747 #endif //AUDIO_POLICY_TEST
749 // refuse 2 active AudioRecord clients at the same time
750 if (getActiveInput() != 0) {
751 LOGW("startInput() input %d failed: other input already started", input);
752 return INVALID_OPERATION;
756 AudioParameter param = AudioParameter();
757 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
759 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
760 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
762 mpClientInterface->setParameters(input, param.toString());
764 inputDesc->mRefCount = 1;
768 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
770 ALOGV("stopInput() input %d", input);
771 ssize_t index = mInputs.indexOfKey(input);
773 LOGW("stopInput() unknow input %d", input);
776 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
778 if (inputDesc->mRefCount == 0) {
779 LOGW("stopInput() input %d already stopped", input);
780 return INVALID_OPERATION;
782 AudioParameter param = AudioParameter();
783 param.addInt(String8(AudioParameter::keyRouting), 0);
784 mpClientInterface->setParameters(input, param.toString());
785 inputDesc->mRefCount = 0;
790 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
792 ALOGV("releaseInput() %d", input);
793 ssize_t index = mInputs.indexOfKey(input);
795 LOGW("releaseInput() releasing unknown input %d", input);
798 mpClientInterface->closeInput(input);
799 delete mInputs.valueAt(index);
800 mInputs.removeItem(input);
801 ALOGV("releaseInput() exit");
804 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
808 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
809 if (indexMin < 0 || indexMin >= indexMax) {
810 LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
813 mStreams[stream].mIndexMin = indexMin;
814 mStreams[stream].mIndexMax = indexMax;
817 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
820 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
824 // Force max volume if stream cannot be muted
825 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
827 ALOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
828 mStreams[stream].mIndexCur = index;
830 // compute and apply stream volume on all outputs according to connected device
831 status_t status = NO_ERROR;
832 for (size_t i = 0; i < mOutputs.size(); i++) {
833 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
834 if (volStatus != NO_ERROR) {
841 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
846 ALOGV("getStreamVolumeIndex() stream %d", stream);
847 *index = mStreams[stream].mIndexCur;
851 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
853 ALOGV("getOutputForEffect()");
854 // apply simple rule where global effects are attached to the same output as MUSIC streams
855 return getOutput(AudioSystem::MUSIC);
858 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
859 audio_io_handle_t io,
864 ssize_t index = mOutputs.indexOfKey(io);
866 index = mInputs.indexOfKey(io);
868 LOGW("registerEffect() unknown io %d", io);
869 return INVALID_OPERATION;
873 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
874 LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
875 desc->name, desc->memoryUsage);
876 return INVALID_OPERATION;
878 mTotalEffectsMemory += desc->memoryUsage;
879 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
880 desc->name, io, strategy, session, id);
881 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
883 EffectDescriptor *pDesc = new EffectDescriptor();
884 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
886 pDesc->mStrategy = (routing_strategy)strategy;
887 pDesc->mSession = session;
888 pDesc->mEnabled = false;
890 mEffects.add(id, pDesc);
895 status_t AudioPolicyManagerBase::unregisterEffect(int id)
897 ssize_t index = mEffects.indexOfKey(id);
899 LOGW("unregisterEffect() unknown effect ID %d", id);
900 return INVALID_OPERATION;
903 EffectDescriptor *pDesc = mEffects.valueAt(index);
905 setEffectEnabled(pDesc, false);
907 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
908 LOGW("unregisterEffect() memory %d too big for total %d",
909 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
910 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
912 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
913 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
914 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
916 mEffects.removeItem(id);
922 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
924 ssize_t index = mEffects.indexOfKey(id);
926 LOGW("unregisterEffect() unknown effect ID %d", id);
927 return INVALID_OPERATION;
930 return setEffectEnabled(mEffects.valueAt(index), enabled);
933 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
935 if (enabled == pDesc->mEnabled) {
936 ALOGV("setEffectEnabled(%s) effect already %s",
937 enabled?"true":"false", enabled?"enabled":"disabled");
938 return INVALID_OPERATION;
942 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
943 LOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
944 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
945 return INVALID_OPERATION;
947 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
948 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
950 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
951 LOGW("setEffectEnabled(false) CPU load %d too high for total %d",
952 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
953 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
955 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
956 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
958 pDesc->mEnabled = enabled;
962 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
964 nsecs_t sysTime = systemTime();
965 for (size_t i = 0; i < mOutputs.size(); i++) {
966 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
967 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
975 status_t AudioPolicyManagerBase::dump(int fd)
977 const size_t SIZE = 256;
981 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
982 result.append(buffer);
983 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
984 result.append(buffer);
986 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
987 result.append(buffer);
988 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
989 result.append(buffer);
990 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
991 result.append(buffer);
993 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
994 result.append(buffer);
995 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
996 result.append(buffer);
997 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
998 result.append(buffer);
999 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1000 result.append(buffer);
1001 // disable ringer mode dump until it is actually passed by AudioService when needed.
1002 // snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
1003 // result.append(buffer);
1004 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1005 result.append(buffer);
1006 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1007 result.append(buffer);
1008 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1009 result.append(buffer);
1010 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1011 result.append(buffer);
1012 write(fd, result.string(), result.size());
1014 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1015 write(fd, buffer, strlen(buffer));
1016 for (size_t i = 0; i < mOutputs.size(); i++) {
1017 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1018 write(fd, buffer, strlen(buffer));
1019 mOutputs.valueAt(i)->dump(fd);
1022 snprintf(buffer, SIZE, "\nInputs dump:\n");
1023 write(fd, buffer, strlen(buffer));
1024 for (size_t i = 0; i < mInputs.size(); i++) {
1025 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1026 write(fd, buffer, strlen(buffer));
1027 mInputs.valueAt(i)->dump(fd);
1030 snprintf(buffer, SIZE, "\nStreams dump:\n");
1031 write(fd, buffer, strlen(buffer));
1032 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Can be muted\n");
1033 write(fd, buffer, strlen(buffer));
1034 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1035 snprintf(buffer, SIZE, " %02d", i);
1036 mStreams[i].dump(buffer + 3, SIZE);
1037 write(fd, buffer, strlen(buffer));
1040 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1041 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1042 write(fd, buffer, strlen(buffer));
1044 snprintf(buffer, SIZE, "Registered effects:\n");
1045 write(fd, buffer, strlen(buffer));
1046 for (size_t i = 0; i < mEffects.size(); i++) {
1047 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1048 write(fd, buffer, strlen(buffer));
1049 mEffects.valueAt(i)->dump(fd);
1056 // ----------------------------------------------------------------------------
1057 // AudioPolicyManagerBase
1058 // ----------------------------------------------------------------------------
1060 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1062 #ifdef AUDIO_POLICY_TEST
1064 #endif //AUDIO_POLICY_TEST
1065 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0),
1066 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1067 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1068 mA2dpSuspended(false)
1070 mpClientInterface = clientInterface;
1072 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1073 mForceUse[i] = AudioSystem::FORCE_NONE;
1076 initializeVolumeCurves();
1078 // devices available by default are speaker, ear piece and microphone
1079 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1080 AudioSystem::DEVICE_OUT_SPEAKER;
1081 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1085 mDuplicatedOutput = 0;
1086 mA2dpDeviceAddress = String8("");
1088 mScoDeviceAddress = String8("");
1090 // open hardware output
1091 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1092 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1093 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1094 &outputDesc->mSamplingRate,
1095 &outputDesc->mFormat,
1096 &outputDesc->mChannels,
1097 &outputDesc->mLatency,
1098 outputDesc->mFlags);
1100 if (mHardwareOutput == 0) {
1101 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1102 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1104 addOutput(mHardwareOutput, outputDesc);
1105 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
1106 //TODO: configure audio effect output stage here
1109 updateDeviceForStrategy();
1110 #ifdef AUDIO_POLICY_TEST
1111 if (mHardwareOutput != 0) {
1112 AudioParameter outputCmd = AudioParameter();
1113 outputCmd.addInt(String8("set_id"), 0);
1114 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1116 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1117 mTestSamplingRate = 44100;
1118 mTestFormat = AudioSystem::PCM_16_BIT;
1119 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1122 mDirectOutput = false;
1123 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1124 mTestOutputs[i] = 0;
1127 const size_t SIZE = 256;
1129 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1130 run(buffer, ANDROID_PRIORITY_AUDIO);
1132 #endif //AUDIO_POLICY_TEST
1135 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1137 #ifdef AUDIO_POLICY_TEST
1139 #endif //AUDIO_POLICY_TEST
1140 for (size_t i = 0; i < mOutputs.size(); i++) {
1141 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1142 delete mOutputs.valueAt(i);
1145 for (size_t i = 0; i < mInputs.size(); i++) {
1146 mpClientInterface->closeInput(mInputs.keyAt(i));
1147 delete mInputs.valueAt(i);
1152 status_t AudioPolicyManagerBase::initCheck()
1154 return (mHardwareOutput == 0) ? NO_INIT : NO_ERROR;
1157 #ifdef AUDIO_POLICY_TEST
1158 bool AudioPolicyManagerBase::threadLoop()
1160 ALOGV("entering threadLoop()");
1161 while (!exitPending())
1167 Mutex::Autolock _l(mLock);
1168 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1170 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1171 AudioParameter param = AudioParameter(command);
1173 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1175 ALOGV("Test command %s received", command.string());
1177 if (param.get(String8("target"), target) != NO_ERROR) {
1180 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1181 param.remove(String8("test_cmd_policy_output"));
1182 mCurOutput = valueInt;
1184 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1185 param.remove(String8("test_cmd_policy_direct"));
1186 if (value == "false") {
1187 mDirectOutput = false;
1188 } else if (value == "true") {
1189 mDirectOutput = true;
1192 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1193 param.remove(String8("test_cmd_policy_input"));
1194 mTestInput = valueInt;
1197 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1198 param.remove(String8("test_cmd_policy_format"));
1199 int format = AudioSystem::INVALID_FORMAT;
1200 if (value == "PCM 16 bits") {
1201 format = AudioSystem::PCM_16_BIT;
1202 } else if (value == "PCM 8 bits") {
1203 format = AudioSystem::PCM_8_BIT;
1204 } else if (value == "Compressed MP3") {
1205 format = AudioSystem::MP3;
1207 if (format != AudioSystem::INVALID_FORMAT) {
1208 if (target == "Manager") {
1209 mTestFormat = format;
1210 } else if (mTestOutputs[mCurOutput] != 0) {
1211 AudioParameter outputParam = AudioParameter();
1212 outputParam.addInt(String8("format"), format);
1213 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1217 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1218 param.remove(String8("test_cmd_policy_channels"));
1221 if (value == "Channels Stereo") {
1222 channels = AudioSystem::CHANNEL_OUT_STEREO;
1223 } else if (value == "Channels Mono") {
1224 channels = AudioSystem::CHANNEL_OUT_MONO;
1226 if (channels != 0) {
1227 if (target == "Manager") {
1228 mTestChannels = channels;
1229 } else if (mTestOutputs[mCurOutput] != 0) {
1230 AudioParameter outputParam = AudioParameter();
1231 outputParam.addInt(String8("channels"), channels);
1232 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1236 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1237 param.remove(String8("test_cmd_policy_sampleRate"));
1238 if (valueInt >= 0 && valueInt <= 96000) {
1239 int samplingRate = valueInt;
1240 if (target == "Manager") {
1241 mTestSamplingRate = samplingRate;
1242 } else if (mTestOutputs[mCurOutput] != 0) {
1243 AudioParameter outputParam = AudioParameter();
1244 outputParam.addInt(String8("sampling_rate"), samplingRate);
1245 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1250 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1251 param.remove(String8("test_cmd_policy_reopen"));
1253 mpClientInterface->closeOutput(mHardwareOutput);
1254 delete mOutputs.valueFor(mHardwareOutput);
1255 mOutputs.removeItem(mHardwareOutput);
1257 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1258 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1259 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1260 &outputDesc->mSamplingRate,
1261 &outputDesc->mFormat,
1262 &outputDesc->mChannels,
1263 &outputDesc->mLatency,
1264 outputDesc->mFlags);
1265 if (mHardwareOutput == 0) {
1266 LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1267 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1269 AudioParameter outputCmd = AudioParameter();
1270 outputCmd.addInt(String8("set_id"), 0);
1271 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1272 addOutput(mHardwareOutput, outputDesc);
1277 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1283 void AudioPolicyManagerBase::exit()
1286 AutoMutex _l(mLock);
1288 mWaitWorkCV.signal();
1290 requestExitAndWait();
1293 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1295 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1296 if (output == mTestOutputs[i]) return i;
1300 #endif //AUDIO_POLICY_TEST
1304 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1306 outputDesc->mId = id;
1307 mOutputs.add(id, outputDesc);
1312 status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1313 const char *device_address)
1315 // when an A2DP device is connected, open an A2DP and a duplicated output
1316 ALOGV("opening A2DP output for device %s", device_address);
1317 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1318 outputDesc->mDevice = device;
1319 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1320 &outputDesc->mSamplingRate,
1321 &outputDesc->mFormat,
1322 &outputDesc->mChannels,
1323 &outputDesc->mLatency,
1324 outputDesc->mFlags);
1326 // add A2DP output descriptor
1327 addOutput(mA2dpOutput, outputDesc);
1329 //TODO: configure audio effect output stage here
1331 // set initial stream volume for A2DP device
1332 applyStreamVolumes(mA2dpOutput, device);
1333 if (a2dpUsedForSonification()) {
1334 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1336 if (mDuplicatedOutput != 0 ||
1337 !a2dpUsedForSonification()) {
1338 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1340 AudioParameter param;
1341 param.add(String8("a2dp_sink_address"), String8(device_address));
1342 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1343 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1345 if (a2dpUsedForSonification()) {
1346 // add duplicated output descriptor
1347 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1348 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1349 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1350 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1351 dupOutputDesc->mFormat = outputDesc->mFormat;
1352 dupOutputDesc->mChannels = outputDesc->mChannels;
1353 dupOutputDesc->mLatency = outputDesc->mLatency;
1354 addOutput(mDuplicatedOutput, dupOutputDesc);
1355 applyStreamVolumes(mDuplicatedOutput, device);
1358 LOGW("getOutput() could not open duplicated output for %d and %d",
1359 mHardwareOutput, mA2dpOutput);
1360 mpClientInterface->closeOutput(mA2dpOutput);
1361 mOutputs.removeItem(mA2dpOutput);
1367 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1371 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1373 if (!a2dpUsedForSonification()) {
1374 // mute music on A2DP output if a notification or ringtone is playing
1375 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1376 refCount += hwOutputDesc->strategyRefCount(STRATEGY_ENFORCED_AUDIBLE);
1377 for (uint32_t i = 0; i < refCount; i++) {
1378 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1382 mA2dpSuspended = false;
1387 status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1388 const char *device_address)
1390 if (mA2dpOutput == 0) {
1391 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1392 return INVALID_OPERATION;
1395 if (mA2dpDeviceAddress != device_address) {
1396 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1397 return INVALID_OPERATION;
1400 // mute media strategy to avoid outputting sound on hardware output while music stream
1401 // is switched from A2DP output and before music is paused by music application
1402 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
1403 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
1405 if (!a2dpUsedForSonification()) {
1406 // unmute music on A2DP output if a notification or ringtone is playing
1407 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1408 refCount += mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_ENFORCED_AUDIBLE);
1409 for (uint32_t i = 0; i < refCount; i++) {
1410 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1413 mA2dpDeviceAddress = "";
1414 mA2dpSuspended = false;
1418 void AudioPolicyManagerBase::closeA2dpOutputs()
1421 ALOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1423 if (mDuplicatedOutput != 0) {
1424 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1425 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1426 // As all active tracks on duplicated output will be deleted,
1427 // and as they were also referenced on hardware output, the reference
1428 // count for their stream type must be adjusted accordingly on
1430 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1431 int refCount = dupOutputDesc->mRefCount[i];
1432 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1435 mpClientInterface->closeOutput(mDuplicatedOutput);
1436 delete mOutputs.valueFor(mDuplicatedOutput);
1437 mOutputs.removeItem(mDuplicatedOutput);
1438 mDuplicatedOutput = 0;
1440 if (mA2dpOutput != 0) {
1441 AudioParameter param;
1442 param.add(String8("closing"), String8("true"));
1443 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1445 mpClientInterface->closeOutput(mA2dpOutput);
1446 delete mOutputs.valueFor(mA2dpOutput);
1447 mOutputs.removeItem(mA2dpOutput);
1452 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1454 uint32_t prevDevice = getDeviceForStrategy(strategy);
1455 uint32_t curDevice = getDeviceForStrategy(strategy, false);
1456 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1457 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1458 audio_io_handle_t srcOutput = 0;
1459 audio_io_handle_t dstOutput = 0;
1461 if (a2dpWasUsed && !a2dpIsUsed) {
1462 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
1463 dstOutput = mHardwareOutput;
1465 ALOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1466 srcOutput = mDuplicatedOutput;
1468 ALOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1469 srcOutput = mA2dpOutput;
1472 if (a2dpIsUsed && !a2dpWasUsed) {
1473 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
1474 srcOutput = mHardwareOutput;
1476 ALOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1477 dstOutput = mDuplicatedOutput;
1479 ALOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1480 dstOutput = mA2dpOutput;
1484 if (srcOutput != 0 && dstOutput != 0) {
1485 // Move effects associated to this strategy from previous output to new output
1486 for (size_t i = 0; i < mEffects.size(); i++) {
1487 EffectDescriptor *desc = mEffects.valueAt(i);
1488 if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1489 desc->mStrategy == strategy &&
1490 desc->mIo == srcOutput) {
1491 ALOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
1492 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
1493 desc->mIo = dstOutput;
1496 // Move tracks associated to this strategy from previous output to new output
1497 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1498 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1499 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
1505 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1507 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1508 checkOutputForStrategy(STRATEGY_PHONE);
1509 checkOutputForStrategy(STRATEGY_SONIFICATION);
1510 checkOutputForStrategy(STRATEGY_MEDIA);
1511 checkOutputForStrategy(STRATEGY_DTMF);
1514 void AudioPolicyManagerBase::checkA2dpSuspend()
1516 // suspend A2DP output if:
1517 // (NOT already suspended) &&
1518 // ((SCO device is connected &&
1519 // (forced usage for communication || for record is SCO))) ||
1520 // (phone state is ringing || in call)
1522 // restore A2DP output if:
1523 // (Already suspended) &&
1524 // ((SCO device is NOT connected ||
1525 // (forced usage NOT for communication && NOT for record is SCO))) &&
1526 // (phone state is NOT ringing && NOT in call)
1528 if (mA2dpOutput == 0) {
1532 if (mA2dpSuspended) {
1533 if (((mScoDeviceAddress == "") ||
1534 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1535 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1536 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1537 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1539 mpClientInterface->restoreOutput(mA2dpOutput);
1540 mA2dpSuspended = false;
1543 if (((mScoDeviceAddress != "") &&
1544 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1545 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1546 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1547 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1549 mpClientInterface->suspendOutput(mA2dpOutput);
1550 mA2dpSuspended = true;
1558 uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1560 uint32_t device = 0;
1562 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1563 // check the following by order of priority to request a routing change if necessary:
1564 // 1: the strategy enforced audible is active on the output:
1565 // use device for strategy enforced audible
1566 // 2: we are in call or the strategy phone is active on the output:
1567 // use device for strategy phone
1568 // 3: the strategy sonification is active on the output:
1569 // use device for strategy sonification
1570 // 4: the strategy media is active on the output:
1571 // use device for strategy media
1572 // 5: the strategy DTMF is active on the output:
1573 // use device for strategy DTMF
1574 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1575 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1576 } else if (isInCall() ||
1577 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1578 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1579 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1580 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1581 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1582 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1583 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1584 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1587 ALOGV("getNewDevice() selected device %x", device);
1591 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1592 return (uint32_t)getStrategy(stream);
1595 uint32_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1597 // By checking the range of stream before calling getStrategy, we avoid
1598 // getStrategy's behavior for invalid streams. getStrategy would do a LOGE
1599 // and then return STRATEGY_MEDIA, but we want to return the empty set.
1600 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1603 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1604 devices = getDeviceForStrategy(strategy, true);
1609 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1610 AudioSystem::stream_type stream) {
1611 // stream to strategy mapping
1613 case AudioSystem::VOICE_CALL:
1614 case AudioSystem::BLUETOOTH_SCO:
1615 return STRATEGY_PHONE;
1616 case AudioSystem::RING:
1617 case AudioSystem::NOTIFICATION:
1618 case AudioSystem::ALARM:
1619 return STRATEGY_SONIFICATION;
1620 case AudioSystem::DTMF:
1621 return STRATEGY_DTMF;
1623 LOGE("unknown stream type");
1624 case AudioSystem::SYSTEM:
1625 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1626 // while key clicks are played produces a poor result
1627 case AudioSystem::TTS:
1628 case AudioSystem::MUSIC:
1629 return STRATEGY_MEDIA;
1630 case AudioSystem::ENFORCED_AUDIBLE:
1631 return STRATEGY_ENFORCED_AUDIBLE;
1635 uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1637 uint32_t device = 0;
1640 ALOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1641 return mDeviceForStrategy[strategy];
1647 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1648 device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1651 // when in call, DTMF and PHONE strategies follow the same rules
1654 case STRATEGY_PHONE:
1655 // for phone strategy, we first consider the forced use and then the available devices by order
1657 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1658 case AudioSystem::FORCE_BT_SCO:
1659 if (!isInCall() || strategy != STRATEGY_DTMF) {
1660 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1663 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1665 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1667 // if SCO device is requested but no SCO device is available, fall back to default case
1670 default: // FORCE_NONE
1671 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1673 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1676 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
1677 if (!isInCall() && !mA2dpSuspended) {
1678 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1680 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1684 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1686 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1688 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1690 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1692 LOGE("getDeviceForStrategy() earpiece device not found");
1696 case AudioSystem::FORCE_SPEAKER:
1698 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1699 // A2DP speaker when forcing to speaker output
1700 if (!isInCall() && !mA2dpSuspended) {
1701 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1705 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1707 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1709 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1711 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1713 LOGE("getDeviceForStrategy() speaker device not found");
1719 case STRATEGY_SONIFICATION:
1721 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1722 // handleIncallSonification().
1724 device = getDeviceForStrategy(STRATEGY_PHONE, false);
1729 case STRATEGY_ENFORCED_AUDIBLE:
1730 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
1731 // except when in call where it doesn't default to STRATEGY_PHONE behavior
1733 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1735 LOGE("getDeviceForStrategy() speaker device not found");
1737 // The second device used for sonification is the same as the device used by media strategy
1740 case STRATEGY_MEDIA: {
1741 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1743 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1746 if ((mA2dpOutput != 0) && !mA2dpSuspended &&
1747 (strategy == STRATEGY_MEDIA || a2dpUsedForSonification())) {
1749 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1752 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1755 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1760 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1763 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1766 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1769 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1772 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
1773 // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise
1776 LOGE("getDeviceForStrategy() speaker device not found");
1781 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1785 ALOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1789 void AudioPolicyManagerBase::updateDeviceForStrategy()
1791 for (int i = 0; i < NUM_STRATEGIES; i++) {
1792 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1796 void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1798 ALOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1799 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1802 if (outputDesc->isDuplicated()) {
1803 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1804 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1808 // filter devices according to output selected
1809 if (output == mA2dpOutput) {
1810 device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
1812 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
1816 uint32_t prevDevice = (uint32_t)outputDesc->device();
1817 // Do not change the routing if:
1818 // - the requestede device is 0
1819 // - the requested device is the same as current device and force is not specified.
1820 // Doing this check here allows the caller to call setOutputDevice() without conditions
1821 if ((device == 0 || device == prevDevice) && !force) {
1822 ALOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1826 outputDesc->mDevice = device;
1827 // mute media streams if both speaker and headset are selected
1828 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1829 setStrategyMute(STRATEGY_MEDIA, true, output);
1830 // wait for the PCM output buffers to empty before proceeding with the rest of the command
1831 // FIXME: increased delay due to larger buffers used for low power audio mode.
1832 // remove when low power audio is controlled by policy manager.
1833 usleep(outputDesc->mLatency*8*1000);
1837 AudioParameter param = AudioParameter();
1838 param.addInt(String8(AudioParameter::keyRouting), (int)device);
1839 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1840 // update stream volumes according to new device
1841 applyStreamVolumes(output, device, delayMs);
1843 // if changing from a combined headset + speaker route, unmute media streams
1844 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1845 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1849 uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1853 switch(inputSource) {
1854 case AUDIO_SOURCE_DEFAULT:
1855 case AUDIO_SOURCE_MIC:
1856 case AUDIO_SOURCE_VOICE_RECOGNITION:
1857 case AUDIO_SOURCE_VOICE_COMMUNICATION:
1858 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1859 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1860 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1861 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1862 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1864 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1867 case AUDIO_SOURCE_CAMCORDER:
1868 if (hasBackMicrophone()) {
1869 device = AudioSystem::DEVICE_IN_BACK_MIC;
1871 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1874 case AUDIO_SOURCE_VOICE_UPLINK:
1875 case AUDIO_SOURCE_VOICE_DOWNLINK:
1876 case AUDIO_SOURCE_VOICE_CALL:
1877 device = AudioSystem::DEVICE_IN_VOICE_CALL;
1880 LOGW("getDeviceForInputSource() invalid input source %d", inputSource);
1884 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1888 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1890 for (size_t i = 0; i < mInputs.size(); i++) {
1891 if (mInputs.valueAt(i)->mRefCount > 0) {
1892 return mInputs.keyAt(i);
1899 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(uint32_t device)
1902 // this happens when forcing a route update and no track is active on an output.
1903 // In this case the returned category is not important.
1904 return DEVICE_CATEGORY_SPEAKER;
1907 if (AudioSystem::popCount(device) > 1) {
1908 // Multiple device selection is either:
1909 // - speaker + one other device: give priority to speaker in this case.
1910 // - one A2DP device + another device: happens with duplicated output. In this case
1911 // retain the device on the A2DP output as the other must not correspond to an active
1912 // selection if not the speaker.
1913 if (device & AUDIO_DEVICE_OUT_SPEAKER)
1914 return DEVICE_CATEGORY_SPEAKER;
1916 device &= AUDIO_DEVICE_OUT_ALL_A2DP;
1919 LOGW_IF(AudioSystem::popCount(device) != 1,
1920 "getDeviceCategory() invalid device combination: %08x",
1924 case AUDIO_DEVICE_OUT_EARPIECE:
1925 return DEVICE_CATEGORY_EARPIECE;
1926 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
1927 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
1928 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
1929 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
1930 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
1931 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
1932 return DEVICE_CATEGORY_HEADSET;
1933 case AUDIO_DEVICE_OUT_SPEAKER:
1934 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
1935 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
1937 return DEVICE_CATEGORY_SPEAKER;
1941 float AudioPolicyManagerBase::volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc,
1944 device_category deviceCategory = getDeviceCategory(device);
1945 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
1947 // the volume index in the UI is relative to the min and max volume indices for this stream type
1948 int nbSteps = 1 + curve[VOLMAX].mIndex -
1949 curve[VOLMIN].mIndex;
1950 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
1951 (streamDesc.mIndexMax - streamDesc.mIndexMin);
1953 // find what part of the curve this index volume belongs to, or if it's out of bounds
1955 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
1957 } else if (volIdx < curve[VOLKNEE1].mIndex) {
1959 } else if (volIdx < curve[VOLKNEE2].mIndex) {
1961 } else if (volIdx <= curve[VOLMAX].mIndex) {
1963 } else { // out of bounds
1967 // linear interpolation in the attenuation table in dB
1968 float decibels = curve[segment].mDBAttenuation +
1969 ((float)(volIdx - curve[segment].mIndex)) *
1970 ( (curve[segment+1].mDBAttenuation -
1971 curve[segment].mDBAttenuation) /
1972 ((float)(curve[segment+1].mIndex -
1973 curve[segment].mIndex)) );
1975 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
1977 ALOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
1978 curve[segment].mIndex, volIdx,
1979 curve[segment+1].mIndex,
1980 curve[segment].mDBAttenuation,
1982 curve[segment+1].mDBAttenuation,
1985 return amplification;
1988 const AudioPolicyManagerBase::VolumeCurvePoint
1989 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
1990 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
1993 const AudioPolicyManagerBase::VolumeCurvePoint
1994 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
1995 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
1998 const AudioPolicyManagerBase::VolumeCurvePoint
1999 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2000 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2003 const AudioPolicyManagerBase::VolumeCurvePoint
2004 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2005 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2009 const AudioPolicyManagerBase::VolumeCurvePoint
2010 *AudioPolicyManagerBase::sVolumeProfiles[AudioPolicyManagerBase::NUM_STRATEGIES]
2011 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2013 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2014 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2015 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2018 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2019 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2020 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2022 { // STRATEGY_SONIFICATION
2023 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2024 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2025 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2028 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2029 sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2030 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2032 { // STRATEGY_ENFORCED_AUDIBLE
2033 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2034 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2035 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2039 void AudioPolicyManagerBase::initializeVolumeCurves()
2041 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2042 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2043 mStreams[i].mVolumeCurve[j] =
2044 sVolumeProfiles[getStrategy((AudioSystem::stream_type)i)][j];
2049 float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
2052 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2053 StreamDescriptor &streamDesc = mStreams[stream];
2056 device = outputDesc->device();
2059 // if volume is not 0 (not muted), force media volume to max on digital output
2060 if (stream == AudioSystem::MUSIC &&
2061 index != mStreams[stream].mIndexMin &&
2062 (device == AudioSystem::DEVICE_OUT_AUX_DIGITAL ||
2063 device == AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET)) {
2067 volume = volIndexToAmpl(device, streamDesc, index);
2069 // if a headset is connected, apply the following rules to ring tones and notifications
2070 // to avoid sound level bursts in user's ears:
2071 // - always attenuate ring tones and notifications volume by 6dB
2072 // - if music is playing, always limit the volume to current music volume,
2073 // with a minimum threshold at -36dB so that notification is always perceived.
2075 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
2076 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2077 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
2078 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
2079 ((getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) ||
2080 (stream == AudioSystem::SYSTEM)) &&
2081 streamDesc.mCanBeMuted) {
2082 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2083 // when the phone is ringing we must consider that music could have been paused just before
2084 // by the music application and behave as if music was active if the last music track was
2086 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
2087 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
2088 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2089 if (volume > minVol) {
2091 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2099 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
2102 // do not change actual stream volume if the stream is muted
2103 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2104 ALOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2108 // do not change in call volume if bluetooth is connected and vice versa
2109 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2110 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2111 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2112 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2113 return INVALID_OPERATION;
2116 float volume = computeVolume(stream, index, output, device);
2117 // We actually change the volume if:
2118 // - the float value returned by computeVolume() changed
2119 // - the force flag is set
2120 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2122 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2123 ALOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2124 if (stream == AudioSystem::VOICE_CALL ||
2125 stream == AudioSystem::DTMF ||
2126 stream == AudioSystem::BLUETOOTH_SCO) {
2127 // offset value to reflect actual hardware volume that never reaches 0
2128 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2129 volume = 0.01 + 0.99 * volume;
2130 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2132 if (stream == AudioSystem::BLUETOOTH_SCO) {
2133 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2137 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2140 if (stream == AudioSystem::VOICE_CALL ||
2141 stream == AudioSystem::BLUETOOTH_SCO) {
2143 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2144 if (stream == AudioSystem::VOICE_CALL) {
2145 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2150 if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {
2151 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2152 mLastVoiceVolume = voiceVolume;
2159 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs, bool force)
2161 ALOGV("applyStreamVolumes() for output %d and device %x", output, device);
2163 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2164 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs, force);
2168 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
2170 ALOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2171 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2172 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2173 setStreamMute(stream, on, output, delayMs);
2178 void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
2180 StreamDescriptor &streamDesc = mStreams[stream];
2181 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2183 ALOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
2186 if (outputDesc->mMuteCount[stream] == 0) {
2187 if (streamDesc.mCanBeMuted) {
2188 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
2191 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2192 outputDesc->mMuteCount[stream]++;
2194 if (outputDesc->mMuteCount[stream] == 0) {
2195 LOGW("setStreamMute() unmuting non muted stream!");
2198 if (--outputDesc->mMuteCount[stream] == 0) {
2199 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
2204 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2206 // if the stream pertains to sonification strategy and we are in call we must
2207 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2208 // in the device used for phone strategy and play the tone if the selected device does not
2209 // interfere with the device used for phone strategy
2210 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2211 // many times as there are active tracks on the output
2213 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
2214 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
2215 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2216 stream, starting, outputDesc->mDevice, stateChange);
2217 if (outputDesc->mRefCount[stream]) {
2220 muteCount = outputDesc->mRefCount[stream];
2222 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2223 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2224 for (int i = 0; i < muteCount; i++) {
2225 setStreamMute(stream, starting, mHardwareOutput);
2228 ALOGV("handleIncallSonification() high visibility");
2229 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
2230 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2231 for (int i = 0; i < muteCount; i++) {
2232 setStreamMute(stream, starting, mHardwareOutput);
2236 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2238 mpClientInterface->stopTone();
2245 bool AudioPolicyManagerBase::isInCall()
2247 return isStateInCall(mPhoneState);
2250 bool AudioPolicyManagerBase::isStateInCall(int state) {
2251 return ((state == AudioSystem::MODE_IN_CALL) ||
2252 (state == AudioSystem::MODE_IN_COMMUNICATION));
2255 bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
2256 uint32_t samplingRate,
2259 AudioSystem::output_flags flags,
2262 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2263 (format !=0 && !AudioSystem::isLinearPCM(format)));
2266 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2268 return MAX_EFFECTS_CPU_LOAD;
2271 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2273 return MAX_EFFECTS_MEMORY;
2276 // --- AudioOutputDescriptor class implementation
2278 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
2279 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
2280 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
2282 // clear usage count for all stream types
2283 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2285 mCurVolume[i] = -1.0;
2291 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2293 uint32_t device = 0;
2294 if (isDuplicated()) {
2295 device = mOutput1->mDevice | mOutput2->mDevice;
2302 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2304 // forward usage count change to attached outputs
2305 if (isDuplicated()) {
2306 mOutput1->changeRefCount(stream, delta);
2307 mOutput2->changeRefCount(stream, delta);
2309 if ((delta + (int)mRefCount[stream]) < 0) {
2310 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2311 mRefCount[stream] = 0;
2314 mRefCount[stream] += delta;
2315 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2318 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2320 uint32_t refcount = 0;
2321 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2322 refcount += mRefCount[i];
2327 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2329 uint32_t refCount = 0;
2330 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2331 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2332 refCount += mRefCount[i];
2338 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2340 const size_t SIZE = 256;
2344 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2345 result.append(buffer);
2346 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2347 result.append(buffer);
2348 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2349 result.append(buffer);
2350 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2351 result.append(buffer);
2352 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2353 result.append(buffer);
2354 snprintf(buffer, SIZE, " Devices %08x\n", device());
2355 result.append(buffer);
2356 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2357 result.append(buffer);
2358 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2359 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2360 result.append(buffer);
2362 write(fd, result.string(), result.size());
2367 // --- AudioInputDescriptor class implementation
2369 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
2370 : mSamplingRate(0), mFormat(0), mChannels(0),
2371 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0),
2376 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2378 const size_t SIZE = 256;
2382 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2383 result.append(buffer);
2384 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2385 result.append(buffer);
2386 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2387 result.append(buffer);
2388 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2389 result.append(buffer);
2390 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2391 result.append(buffer);
2392 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2393 result.append(buffer);
2394 write(fd, result.string(), result.size());
2399 // --- StreamDescriptor class implementation
2401 void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
2403 snprintf(buffer, size, " %02d %02d %02d %d\n",
2410 // --- EffectDescriptor class implementation
2412 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2414 const size_t SIZE = 256;
2418 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
2419 result.append(buffer);
2420 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2421 result.append(buffer);
2422 snprintf(buffer, SIZE, " Session: %d\n", mSession);
2423 result.append(buffer);
2424 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
2425 result.append(buffer);
2426 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
2427 result.append(buffer);
2428 write(fd, result.string(), result.size());
2435 }; // namespace android