2 * Copyright (C) 2009 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define LOG_TAG "AudioPolicyManagerBase"
18 //#define LOG_NDEBUG 0
20 //#define VERY_VERBOSE_LOGGING
21 #ifdef VERY_VERBOSE_LOGGING
24 #define ALOGVV(a...) do { } while(0)
27 // A device mask for all audio input devices that are considered "virtual" when evaluating
28 // active inputs in getActiveInput()
29 #define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30 // A device mask for all audio output devices that are considered "remote" when evaluating
31 // active output devices in isStreamActiveRemotely()
32 #define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
37 #include <cutils/properties.h>
38 #include <utils/Log.h>
39 #include <utils/Timers.h>
41 #include <hardware/audio.h>
42 #include <hardware/audio_effect.h>
43 #include <hardware_legacy/audio_policy_conf.h>
44 #include <hardware_legacy/AudioPolicyManagerBase.h>
46 namespace android_audio_legacy {
48 // ----------------------------------------------------------------------------
49 // AudioPolicyInterface implementation
50 // ----------------------------------------------------------------------------
53 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
54 AudioSystem::device_connection_state state,
55 const char *device_address)
57 // device_address can be NULL and should be handled as an empty string in this case,
58 // and it is not checked by AudioPolicyInterfaceImpl.cpp
59 if (device_address == NULL) {
62 ALOGV("setDeviceConnectionState() device: 0x%X, state %d, address %s", device, state, device_address);
64 // connect/disconnect only 1 device at a time
65 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
67 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
68 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
72 // handle output devices
73 if (audio_is_output_device(device)) {
74 SortedVector <audio_io_handle_t> outputs;
76 if (!mHasA2dp && audio_is_a2dp_out_device(device)) {
77 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
80 if (!mHasUsb && audio_is_usb_out_device(device)) {
81 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
84 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
85 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
89 // save a copy of the opened output descriptors before any output is opened or closed
90 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
91 mPreviousOutputs = mOutputs;
95 // handle output device connection
96 case AudioSystem::DEVICE_STATE_AVAILABLE:
97 if (mAvailableOutputDevices & device) {
98 ALOGW("setDeviceConnectionState() device already connected: %x", device);
99 return INVALID_OPERATION;
101 ALOGV("setDeviceConnectionState() connecting device %x", device);
103 if (mHasA2dp && audio_is_a2dp_out_device(device)) {
104 // handle A2DP device connection
105 AudioParameter param;
106 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
107 paramStr = param.toString();
108 } else if (mHasUsb && audio_is_usb_out_device(device)) {
109 // handle USB device connection
110 paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
113 if (checkOutputsForDevice(device, state, outputs, paramStr) != NO_ERROR) {
114 return INVALID_OPERATION;
116 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
118 // register new device as available
119 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
121 if (mHasA2dp && audio_is_a2dp_out_device(device)) {
122 // handle A2DP device connection
123 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
124 mA2dpSuspended = false;
125 } else if (audio_is_bluetooth_sco_device(device)) {
126 // handle SCO device connection
127 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
128 } else if (mHasUsb && audio_is_usb_out_device(device)) {
129 // handle USB device connection
130 mUsbOutCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
134 // handle output device disconnection
135 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
136 if (!(mAvailableOutputDevices & device)) {
137 ALOGW("setDeviceConnectionState() device not connected: %x", device);
138 return INVALID_OPERATION;
141 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
142 // remove device from available output devices
143 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
144 checkOutputsForDevice(device, state, outputs, paramStr);
146 if (mHasA2dp && audio_is_a2dp_out_device(device)) {
147 // handle A2DP device disconnection
148 mA2dpDeviceAddress = "";
149 mA2dpSuspended = false;
150 } else if (audio_is_bluetooth_sco_device(device)) {
151 // handle SCO device disconnection
152 mScoDeviceAddress = "";
153 } else if (mHasUsb && audio_is_usb_out_device(device)) {
154 // handle USB device disconnection
155 mUsbOutCardAndDevice = "";
157 // not currently handling multiple simultaneous submixes: ignoring remote submix
162 ALOGE("setDeviceConnectionState() invalid state: %x", state);
167 checkOutputForAllStrategies();
168 // outputs must be closed after checkOutputForAllStrategies() is executed
169 if (!outputs.isEmpty()) {
170 for (size_t i = 0; i < outputs.size(); i++) {
171 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
172 // close unused outputs after device disconnection or direct outputs that have been
173 // opened by checkOutputsForDevice() to query dynamic parameters
174 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
175 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
176 (desc->mDirectOpenCount == 0))) {
177 closeOutput(outputs[i]);
182 updateDevicesAndOutputs();
183 for (size_t i = 0; i < mOutputs.size(); i++) {
184 // do not force device change on duplicated output because if device is 0, it will
185 // also force a device 0 for the two outputs it is duplicated to which may override
186 // a valid device selection on those outputs.
187 setOutputDevice(mOutputs.keyAt(i),
188 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
189 !mOutputs.valueAt(i)->isDuplicated(),
194 } // end if is output device
196 // handle input devices
197 if (audio_is_input_device(device)) {
198 SortedVector <audio_io_handle_t> inputs;
203 // handle input device connection
204 case AudioSystem::DEVICE_STATE_AVAILABLE: {
205 if (mAvailableInputDevices & device) {
206 ALOGW("setDeviceConnectionState() device already connected: %d", device);
207 return INVALID_OPERATION;
210 if (mHasUsb && audio_is_usb_in_device(device)) {
211 // handle USB device connection
212 paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
213 } else if (mHasA2dp && audio_is_a2dp_in_device(device)) {
214 // handle A2DP device connection
215 AudioParameter param;
216 param.add(String8(AUDIO_PARAMETER_A2DP_SOURCE_ADDRESS), String8(device_address));
217 paramStr = param.toString();
220 if (checkInputsForDevice(device, state, inputs, paramStr) != NO_ERROR) {
221 return INVALID_OPERATION;
223 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
227 // handle input device disconnection
228 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
229 if (!(mAvailableInputDevices & device)) {
230 ALOGW("setDeviceConnectionState() device not connected: %d", device);
231 return INVALID_OPERATION;
233 checkInputsForDevice(device, state, inputs, paramStr);
234 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
238 ALOGE("setDeviceConnectionState() invalid state: %x", state);
245 } // end if is input device
247 ALOGW("setDeviceConnectionState() invalid device: %x", device);
251 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
252 const char *device_address)
254 // similar to setDeviceConnectionState
255 if (device_address == NULL) {
258 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
259 String8 address = String8(device_address);
260 if (audio_is_output_device(device)) {
261 if (device & mAvailableOutputDevices) {
262 if (audio_is_a2dp_out_device(device) &&
263 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
266 if (audio_is_bluetooth_sco_device(device) &&
267 address != "" && mScoDeviceAddress != address) {
270 if (audio_is_usb_out_device(device) &&
271 (!mHasUsb || (address != "" && mUsbOutCardAndDevice != address))) {
272 ALOGE("getDeviceConnectionState() invalid device: %x", device);
275 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
278 state = AudioSystem::DEVICE_STATE_AVAILABLE;
280 } else if (audio_is_input_device(device)) {
281 if (device & mAvailableInputDevices) {
282 state = AudioSystem::DEVICE_STATE_AVAILABLE;
289 void AudioPolicyManagerBase::setPhoneState(int state)
291 ALOGV("setPhoneState() state %d", state);
292 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
293 if (state < 0 || state >= AudioSystem::NUM_MODES) {
294 ALOGW("setPhoneState() invalid state %d", state);
298 if (state == mPhoneState ) {
299 ALOGW("setPhoneState() setting same state %d", state);
303 // if leaving call state, handle special case of active streams
304 // pertaining to sonification strategy see handleIncallSonification()
306 ALOGV("setPhoneState() in call state management: new state is %d", state);
307 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
308 handleIncallSonification(stream, false, true);
312 // store previous phone state for management of sonification strategy below
313 int oldState = mPhoneState;
317 // are we entering or starting a call
318 if (!isStateInCall(oldState) && isStateInCall(state)) {
319 ALOGV(" Entering call in setPhoneState()");
320 // force routing command to audio hardware when starting a call
321 // even if no device change is needed
323 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
324 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
325 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
327 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
328 ALOGV(" Exiting call in setPhoneState()");
329 // force routing command to audio hardware when exiting a call
330 // even if no device change is needed
332 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
333 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
334 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
336 } else if (isStateInCall(state) && (state != oldState)) {
337 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
338 // force routing command to audio hardware when switching between telephony and VoIP
339 // even if no device change is needed
343 // check for device and output changes triggered by new phone state
344 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
346 checkOutputForAllStrategies();
347 updateDevicesAndOutputs();
349 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
351 // force routing command to audio hardware when ending call
352 // even if no device change is needed
353 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
354 newDevice = hwOutputDesc->device();
358 if (isStateInCall(state)) {
359 nsecs_t sysTime = systemTime();
360 for (size_t i = 0; i < mOutputs.size(); i++) {
361 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
362 // mute media and sonification strategies and delay device switch by the largest
363 // latency of any output where either strategy is active.
364 // This avoid sending the ring tone or music tail into the earpiece or headset.
365 if ((desc->isStrategyActive(STRATEGY_MEDIA,
366 SONIFICATION_HEADSET_MUSIC_DELAY,
368 desc->isStrategyActive(STRATEGY_SONIFICATION,
369 SONIFICATION_HEADSET_MUSIC_DELAY,
371 (delayMs < (int)desc->mLatency*2)) {
372 delayMs = desc->mLatency*2;
374 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
375 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
376 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
377 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
378 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
379 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
383 // change routing is necessary
384 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
386 // if entering in call state, handle special case of active streams
387 // pertaining to sonification strategy see handleIncallSonification()
388 if (isStateInCall(state)) {
389 ALOGV("setPhoneState() in call state management: new state is %d", state);
390 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
391 handleIncallSonification(stream, true, true);
395 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
396 if (state == AudioSystem::MODE_RINGTONE &&
397 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
398 mLimitRingtoneVolume = true;
400 mLimitRingtoneVolume = false;
404 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
406 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
408 bool forceVolumeReeval = false;
410 case AudioSystem::FOR_COMMUNICATION:
411 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
412 config != AudioSystem::FORCE_NONE) {
413 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
416 forceVolumeReeval = true;
417 mForceUse[usage] = config;
419 case AudioSystem::FOR_MEDIA:
420 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
421 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
422 config != AudioSystem::FORCE_ANALOG_DOCK &&
423 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
424 config != AudioSystem::FORCE_NO_BT_A2DP) {
425 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
428 mForceUse[usage] = config;
430 case AudioSystem::FOR_RECORD:
431 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
432 config != AudioSystem::FORCE_NONE) {
433 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
436 mForceUse[usage] = config;
438 case AudioSystem::FOR_DOCK:
439 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
440 config != AudioSystem::FORCE_BT_DESK_DOCK &&
441 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
442 config != AudioSystem::FORCE_ANALOG_DOCK &&
443 config != AudioSystem::FORCE_DIGITAL_DOCK) {
444 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
446 forceVolumeReeval = true;
447 mForceUse[usage] = config;
449 case AudioSystem::FOR_SYSTEM:
450 if (config != AudioSystem::FORCE_NONE &&
451 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
452 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
454 forceVolumeReeval = true;
455 mForceUse[usage] = config;
458 ALOGW("setForceUse() invalid usage %d", usage);
462 // check for device and output changes triggered by new force usage
464 checkOutputForAllStrategies();
465 updateDevicesAndOutputs();
466 for (size_t i = 0; i < mOutputs.size(); i++) {
467 audio_io_handle_t output = mOutputs.keyAt(i);
468 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
469 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
470 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
471 applyStreamVolumes(output, newDevice, 0, true);
475 audio_io_handle_t activeInput = getActiveInput();
476 if (activeInput != 0) {
477 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
478 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
479 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
480 ALOGV("setForceUse() changing device from %x to %x for input %d",
481 inputDesc->mDevice, newDevice, activeInput);
482 inputDesc->mDevice = newDevice;
483 AudioParameter param = AudioParameter();
484 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
485 mpClientInterface->setParameters(activeInput, param.toString());
491 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
493 return mForceUse[usage];
496 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
498 ALOGV("setSystemProperty() property %s, value %s", property, value);
501 // Find a direct output profile compatible with the parameters passed, even if the input flags do
502 // not explicitly request a direct output
503 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
504 audio_devices_t device,
505 uint32_t samplingRate,
506 audio_format_t format,
507 audio_channel_mask_t channelMask,
508 audio_output_flags_t flags)
510 for (size_t i = 0; i < mHwModules.size(); i++) {
511 if (mHwModules[i]->mHandle == 0) {
514 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
515 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
516 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
517 if (profile->isCompatibleProfile(device, samplingRate, format,
519 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
520 if (mAvailableOutputDevices & profile->mSupportedDevices) {
521 return mHwModules[i]->mOutputProfiles[j];
525 if (profile->isCompatibleProfile(device, samplingRate, format,
527 AUDIO_OUTPUT_FLAG_DIRECT)) {
528 if (mAvailableOutputDevices & profile->mSupportedDevices) {
529 return mHwModules[i]->mOutputProfiles[j];
538 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
539 uint32_t samplingRate,
540 audio_format_t format,
541 audio_channel_mask_t channelMask,
542 AudioSystem::output_flags flags,
543 const audio_offload_info_t *offloadInfo)
545 audio_io_handle_t output = 0;
546 uint32_t latency = 0;
547 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
548 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
549 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
550 device, stream, samplingRate, format, channelMask, flags);
552 #ifdef AUDIO_POLICY_TEST
553 if (mCurOutput != 0) {
554 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
555 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
557 if (mTestOutputs[mCurOutput] == 0) {
558 ALOGV("getOutput() opening test output");
559 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
560 outputDesc->mDevice = mTestDevice;
561 outputDesc->mSamplingRate = mTestSamplingRate;
562 outputDesc->mFormat = mTestFormat;
563 outputDesc->mChannelMask = mTestChannels;
564 outputDesc->mLatency = mTestLatencyMs;
565 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
566 outputDesc->mRefCount[stream] = 0;
567 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
568 &outputDesc->mSamplingRate,
569 &outputDesc->mFormat,
570 &outputDesc->mChannelMask,
571 &outputDesc->mLatency,
574 if (mTestOutputs[mCurOutput]) {
575 AudioParameter outputCmd = AudioParameter();
576 outputCmd.addInt(String8("set_id"),mCurOutput);
577 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
578 addOutput(mTestOutputs[mCurOutput], outputDesc);
581 return mTestOutputs[mCurOutput];
583 #endif //AUDIO_POLICY_TEST
585 // open a direct output if required by specified parameters
586 //force direct flag if offload flag is set: offloading implies a direct output stream
587 // and all common behaviors are driven by checking only the direct flag
588 // this should normally be set appropriately in the policy configuration file
589 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
590 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
593 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
594 // creating an offloaded track and tearing it down immediately after start when audioflinger
595 // detects there is an active non offloadable effect.
596 // FIXME: We should check the audio session here but we do not have it in this context.
597 // This may prevent offloading in rare situations where effects are left active by apps
598 // in the background.
599 IOProfile *profile = NULL;
600 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
601 !isNonOffloadableEffectEnabled()) {
602 profile = getProfileForDirectOutput(device,
606 (audio_output_flags_t)flags);
609 if (profile != NULL) {
610 AudioOutputDescriptor *outputDesc = NULL;
612 for (size_t i = 0; i < mOutputs.size(); i++) {
613 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
614 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
616 // reuse direct output if currently open and configured with same parameters
617 if ((samplingRate == outputDesc->mSamplingRate) &&
618 (format == outputDesc->mFormat) &&
619 (channelMask == outputDesc->mChannelMask)) {
620 outputDesc->mDirectOpenCount++;
621 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
622 return mOutputs.keyAt(i);
626 // close direct output if currently open and configured with different parameters
627 if (outputDesc != NULL) {
628 closeOutput(outputDesc->mId);
630 outputDesc = new AudioOutputDescriptor(profile);
631 outputDesc->mDevice = device;
632 outputDesc->mSamplingRate = samplingRate;
633 outputDesc->mFormat = format;
634 outputDesc->mChannelMask = channelMask;
635 outputDesc->mLatency = 0;
636 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
637 outputDesc->mRefCount[stream] = 0;
638 outputDesc->mStopTime[stream] = 0;
639 outputDesc->mDirectOpenCount = 1;
640 output = mpClientInterface->openOutput(profile->mModule->mHandle,
641 &outputDesc->mDevice,
642 &outputDesc->mSamplingRate,
643 &outputDesc->mFormat,
644 &outputDesc->mChannelMask,
645 &outputDesc->mLatency,
649 // only accept an output with the requested parameters
651 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
652 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
653 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
654 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
655 "format %d %d, channelMask %04x %04x", output, samplingRate,
656 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
657 outputDesc->mChannelMask);
659 mpClientInterface->closeOutput(output);
664 audio_io_handle_t srcOutput = getOutputForEffect();
665 addOutput(output, outputDesc);
666 audio_io_handle_t dstOutput = getOutputForEffect();
667 if (dstOutput == output) {
668 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
670 mPreviousOutputs = mOutputs;
671 ALOGV("getOutput() returns new direct output %d", output);
675 // ignoring channel mask due to downmix capability in mixer
677 // open a non direct output
679 // for non direct outputs, only PCM is supported
680 if (audio_is_linear_pcm(format)) {
681 // get which output is suitable for the specified stream. The actual
682 // routing change will happen when startOutput() will be called
683 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
685 output = selectOutput(outputs, flags);
687 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
688 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
690 ALOGV("getOutput() returns output %d", output);
695 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
696 AudioSystem::output_flags flags)
698 // select one output among several that provide a path to a particular device or set of
699 // devices (the list was previously build by getOutputsForDevice()).
700 // The priority is as follows:
701 // 1: the output with the highest number of requested policy flags
702 // 2: the primary output
703 // 3: the first output in the list
705 if (outputs.size() == 0) {
708 if (outputs.size() == 1) {
712 int maxCommonFlags = 0;
713 audio_io_handle_t outputFlags = 0;
714 audio_io_handle_t outputPrimary = 0;
716 for (size_t i = 0; i < outputs.size(); i++) {
717 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
718 if (!outputDesc->isDuplicated()) {
719 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
720 if (commonFlags > maxCommonFlags) {
721 outputFlags = outputs[i];
722 maxCommonFlags = commonFlags;
723 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
725 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
726 outputPrimary = outputs[i];
731 if (outputFlags != 0) {
734 if (outputPrimary != 0) {
735 return outputPrimary;
741 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
742 AudioSystem::stream_type stream,
745 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
746 ssize_t index = mOutputs.indexOfKey(output);
748 ALOGW("startOutput() unknown output %d", output);
752 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
754 // increment usage count for this stream on the requested output:
755 // NOTE that the usage count is the same for duplicated output and hardware output which is
756 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
757 outputDesc->changeRefCount(stream, 1);
759 if (outputDesc->mRefCount[stream] == 1) {
760 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
761 routing_strategy strategy = getStrategy(stream);
762 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
763 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
766 for (size_t i = 0; i < mOutputs.size(); i++) {
767 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
768 if (desc != outputDesc) {
769 // force a device change if any other output is managed by the same hw
770 // module and has a current device selection that differs from selected device.
771 // In this case, the audio HAL must receive the new device selection so that it can
772 // change the device currently selected by the other active output.
773 if (outputDesc->sharesHwModuleWith(desc) &&
774 desc->device() != newDevice) {
777 // wait for audio on other active outputs to be presented when starting
778 // a notification so that audio focus effect can propagate.
779 uint32_t latency = desc->latency();
780 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
785 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
787 // handle special case for sonification while in call
789 handleIncallSonification(stream, true, false);
792 // apply volume rules for current stream and device if necessary
793 checkAndSetVolume(stream,
794 mStreams[stream].getVolumeIndex(newDevice),
798 // update the outputs if starting an output with a stream that can affect notification
800 handleNotificationRoutingForStream(stream);
801 if (waitMs > muteWaitMs) {
802 usleep((waitMs - muteWaitMs) * 2 * 1000);
809 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
810 AudioSystem::stream_type stream,
813 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
814 ssize_t index = mOutputs.indexOfKey(output);
816 ALOGW("stopOutput() unknown output %d", output);
820 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
822 // handle special case for sonification while in call
824 handleIncallSonification(stream, false, false);
827 if (outputDesc->mRefCount[stream] > 0) {
828 // decrement usage count of this stream on the output
829 outputDesc->changeRefCount(stream, -1);
830 // store time at which the stream was stopped - see isStreamActive()
831 if (outputDesc->mRefCount[stream] == 0) {
832 outputDesc->mStopTime[stream] = systemTime();
833 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
834 // delay the device switch by twice the latency because stopOutput() is executed when
835 // the track stop() command is received and at that time the audio track buffer can
836 // still contain data that needs to be drained. The latency only covers the audio HAL
837 // and kernel buffers. Also the latency does not always include additional delay in the
838 // audio path (audio DSP, CODEC ...)
839 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
841 // force restoring the device selection on other active outputs if it differs from the
842 // one being selected for this output
843 for (size_t i = 0; i < mOutputs.size(); i++) {
844 audio_io_handle_t curOutput = mOutputs.keyAt(i);
845 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
846 if (curOutput != output &&
848 outputDesc->sharesHwModuleWith(desc) &&
849 (newDevice != desc->device())) {
850 setOutputDevice(curOutput,
851 getNewDevice(curOutput, false /*fromCache*/),
853 outputDesc->mLatency*2);
856 // update the outputs if stopping one with a stream that can affect notification routing
857 handleNotificationRoutingForStream(stream);
861 ALOGW("stopOutput() refcount is already 0 for output %d", output);
862 return INVALID_OPERATION;
866 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
868 ALOGV("releaseOutput() %d", output);
869 ssize_t index = mOutputs.indexOfKey(output);
871 ALOGW("releaseOutput() releasing unknown output %d", output);
875 #ifdef AUDIO_POLICY_TEST
876 int testIndex = testOutputIndex(output);
877 if (testIndex != 0) {
878 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
879 if (outputDesc->isActive()) {
880 mpClientInterface->closeOutput(output);
881 delete mOutputs.valueAt(index);
882 mOutputs.removeItem(output);
883 mTestOutputs[testIndex] = 0;
887 #endif //AUDIO_POLICY_TEST
889 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
890 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
891 if (desc->mDirectOpenCount <= 0) {
892 ALOGW("releaseOutput() invalid open count %d for output %d",
893 desc->mDirectOpenCount, output);
896 if (--desc->mDirectOpenCount == 0) {
898 // If effects where present on the output, audioflinger moved them to the primary
899 // output by default: move them back to the appropriate output.
900 audio_io_handle_t dstOutput = getOutputForEffect();
901 if (dstOutput != mPrimaryOutput) {
902 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
909 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
910 uint32_t samplingRate,
911 audio_format_t format,
912 audio_channel_mask_t channelMask,
913 AudioSystem::audio_in_acoustics acoustics)
915 audio_io_handle_t input = 0;
916 audio_devices_t device = getDeviceForInputSource(inputSource);
918 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
919 inputSource, samplingRate, format, channelMask, acoustics);
921 if (device == AUDIO_DEVICE_NONE) {
922 ALOGW("getInput() could not find device for inputSource %d", inputSource);
926 // adapt channel selection to input source
927 switch(inputSource) {
928 case AUDIO_SOURCE_VOICE_UPLINK:
929 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
931 case AUDIO_SOURCE_VOICE_DOWNLINK:
932 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
934 case AUDIO_SOURCE_VOICE_CALL:
935 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
941 IOProfile *profile = getInputProfile(device,
945 if (profile == NULL) {
946 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %d, format %d, "
948 device, samplingRate, format, channelMask);
952 if (profile->mModule->mHandle == 0) {
953 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
957 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
959 inputDesc->mInputSource = inputSource;
960 inputDesc->mDevice = device;
961 inputDesc->mSamplingRate = samplingRate;
962 inputDesc->mFormat = format;
963 inputDesc->mChannelMask = channelMask;
964 inputDesc->mRefCount = 0;
966 input = mpClientInterface->openInput(profile->mModule->mHandle,
968 &inputDesc->mSamplingRate,
970 &inputDesc->mChannelMask);
972 // only accept input with the exact requested set of parameters
974 (samplingRate != inputDesc->mSamplingRate) ||
975 (format != inputDesc->mFormat) ||
976 (channelMask != inputDesc->mChannelMask)) {
977 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask 0x%X",
978 samplingRate, format, channelMask);
980 mpClientInterface->closeInput(input);
985 addInput(input, inputDesc);
990 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
992 ALOGV("startInput() input %d", input);
993 ssize_t index = mInputs.indexOfKey(input);
995 ALOGW("startInput() unknown input %d", input);
998 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1000 #ifdef AUDIO_POLICY_TEST
1001 if (mTestInput == 0)
1002 #endif //AUDIO_POLICY_TEST
1004 // refuse 2 active AudioRecord clients at the same time except if the active input
1005 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1006 audio_io_handle_t activeInput = getActiveInput();
1007 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1008 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1009 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1010 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1011 stopInput(activeInput);
1012 releaseInput(activeInput);
1014 ALOGW("startInput() input %d failed: other input already started", input);
1015 return INVALID_OPERATION;
1020 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1021 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1022 inputDesc->mDevice = newDevice;
1025 // automatically enable the remote submix output when input is started
1026 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1027 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1028 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1031 AudioParameter param = AudioParameter();
1032 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1034 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1035 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1037 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1038 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1040 mpClientInterface->setParameters(input, param.toString());
1042 inputDesc->mRefCount = 1;
1046 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
1048 ALOGV("stopInput() input %d", input);
1049 ssize_t index = mInputs.indexOfKey(input);
1051 ALOGW("stopInput() unknown input %d", input);
1054 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1056 if (inputDesc->mRefCount == 0) {
1057 ALOGW("stopInput() input %d already stopped", input);
1058 return INVALID_OPERATION;
1060 // automatically disable the remote submix output when input is stopped
1061 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1062 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1063 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1066 AudioParameter param = AudioParameter();
1067 param.addInt(String8(AudioParameter::keyRouting), 0);
1068 mpClientInterface->setParameters(input, param.toString());
1069 inputDesc->mRefCount = 0;
1074 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1076 ALOGV("releaseInput() %d", input);
1077 ssize_t index = mInputs.indexOfKey(input);
1079 ALOGW("releaseInput() releasing unknown input %d", input);
1082 mpClientInterface->closeInput(input);
1083 delete mInputs.valueAt(index);
1084 mInputs.removeItem(input);
1086 ALOGV("releaseInput() exit");
1089 void AudioPolicyManagerBase::closeAllInputs() {
1090 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1091 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1096 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1100 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1101 if (indexMin < 0 || indexMin >= indexMax) {
1102 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1105 mStreams[stream].mIndexMin = indexMin;
1106 mStreams[stream].mIndexMax = indexMax;
1109 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1111 audio_devices_t device)
1114 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1117 if (!audio_is_output_device(device)) {
1121 // Force max volume if stream cannot be muted
1122 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1124 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1125 stream, device, index);
1127 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1128 // clear all device specific values
1129 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1130 mStreams[stream].mIndexCur.clear();
1132 mStreams[stream].mIndexCur.add(device, index);
1134 // compute and apply stream volume on all outputs according to connected device
1135 status_t status = NO_ERROR;
1136 for (size_t i = 0; i < mOutputs.size(); i++) {
1137 audio_devices_t curDevice =
1138 getDeviceForVolume(mOutputs.valueAt(i)->device());
1139 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1140 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1141 if (volStatus != NO_ERROR) {
1149 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1151 audio_devices_t device)
1153 if (index == NULL) {
1156 if (!audio_is_output_device(device)) {
1159 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1160 // the strategy the stream belongs to.
1161 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1162 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1164 device = getDeviceForVolume(device);
1166 *index = mStreams[stream].getVolumeIndex(device);
1167 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1171 audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
1172 const SortedVector<audio_io_handle_t>& outputs)
1174 // select one output among several suitable for global effects.
1175 // The priority is as follows:
1176 // 1: An offloaded output. If the effect ends up not being offloadable,
1177 // AudioFlinger will invalidate the track and the offloaded output
1178 // will be closed causing the effect to be moved to a PCM output.
1179 // 2: A deep buffer output
1180 // 3: the first output in the list
1182 if (outputs.size() == 0) {
1186 audio_io_handle_t outputOffloaded = 0;
1187 audio_io_handle_t outputDeepBuffer = 0;
1189 for (size_t i = 0; i < outputs.size(); i++) {
1190 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1191 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1192 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1193 outputOffloaded = outputs[i];
1195 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1196 outputDeepBuffer = outputs[i];
1200 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1201 outputOffloaded, outputDeepBuffer);
1202 if (outputOffloaded != 0) {
1203 return outputOffloaded;
1205 if (outputDeepBuffer != 0) {
1206 return outputDeepBuffer;
1212 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1214 // apply simple rule where global effects are attached to the same output as MUSIC streams
1216 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1217 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1218 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1220 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1221 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1222 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1227 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1228 audio_io_handle_t io,
1233 ssize_t index = mOutputs.indexOfKey(io);
1235 index = mInputs.indexOfKey(io);
1237 ALOGW("registerEffect() unknown io %d", io);
1238 return INVALID_OPERATION;
1242 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1243 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1244 desc->name, desc->memoryUsage);
1245 return INVALID_OPERATION;
1247 mTotalEffectsMemory += desc->memoryUsage;
1248 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1249 desc->name, io, strategy, session, id);
1250 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1252 EffectDescriptor *pDesc = new EffectDescriptor();
1253 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1255 pDesc->mStrategy = (routing_strategy)strategy;
1256 pDesc->mSession = session;
1257 pDesc->mEnabled = false;
1259 mEffects.add(id, pDesc);
1264 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1266 ssize_t index = mEffects.indexOfKey(id);
1268 ALOGW("unregisterEffect() unknown effect ID %d", id);
1269 return INVALID_OPERATION;
1272 EffectDescriptor *pDesc = mEffects.valueAt(index);
1274 setEffectEnabled(pDesc, false);
1276 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1277 ALOGW("unregisterEffect() memory %d too big for total %d",
1278 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1279 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1281 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1282 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1283 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1285 mEffects.removeItem(id);
1291 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1293 ssize_t index = mEffects.indexOfKey(id);
1295 ALOGW("unregisterEffect() unknown effect ID %d", id);
1296 return INVALID_OPERATION;
1299 return setEffectEnabled(mEffects.valueAt(index), enabled);
1302 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1304 if (enabled == pDesc->mEnabled) {
1305 ALOGV("setEffectEnabled(%s) effect already %s",
1306 enabled?"true":"false", enabled?"enabled":"disabled");
1307 return INVALID_OPERATION;
1311 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1312 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1313 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1314 return INVALID_OPERATION;
1316 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1317 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1319 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1320 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1321 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1322 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1324 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1325 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1327 pDesc->mEnabled = enabled;
1331 bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled()
1333 for (size_t i = 0; i < mEffects.size(); i++) {
1334 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1335 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1336 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1337 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1338 pDesc->mDesc.name, pDesc->mSession);
1345 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1347 nsecs_t sysTime = systemTime();
1348 for (size_t i = 0; i < mOutputs.size(); i++) {
1349 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1350 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1357 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1359 nsecs_t sysTime = systemTime();
1360 for (size_t i = 0; i < mOutputs.size(); i++) {
1361 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1362 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1363 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1370 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1372 for (size_t i = 0; i < mInputs.size(); i++) {
1373 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1374 if ((inputDescriptor->mInputSource == (int)source ||
1375 (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
1376 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1377 && (inputDescriptor->mRefCount > 0)) {
1385 status_t AudioPolicyManagerBase::dump(int fd)
1387 const size_t SIZE = 256;
1391 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1392 result.append(buffer);
1394 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1395 result.append(buffer);
1396 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1397 result.append(buffer);
1398 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1399 result.append(buffer);
1400 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbOutCardAndDevice.string());
1401 result.append(buffer);
1402 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1403 result.append(buffer);
1404 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1405 result.append(buffer);
1406 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1407 result.append(buffer);
1408 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1409 result.append(buffer);
1410 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1411 result.append(buffer);
1412 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1413 result.append(buffer);
1414 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1415 result.append(buffer);
1416 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1417 result.append(buffer);
1418 write(fd, result.string(), result.size());
1421 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1422 write(fd, buffer, strlen(buffer));
1423 for (size_t i = 0; i < mHwModules.size(); i++) {
1424 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
1425 write(fd, buffer, strlen(buffer));
1426 mHwModules[i]->dump(fd);
1429 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1430 write(fd, buffer, strlen(buffer));
1431 for (size_t i = 0; i < mOutputs.size(); i++) {
1432 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1433 write(fd, buffer, strlen(buffer));
1434 mOutputs.valueAt(i)->dump(fd);
1437 snprintf(buffer, SIZE, "\nInputs dump:\n");
1438 write(fd, buffer, strlen(buffer));
1439 for (size_t i = 0; i < mInputs.size(); i++) {
1440 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1441 write(fd, buffer, strlen(buffer));
1442 mInputs.valueAt(i)->dump(fd);
1445 snprintf(buffer, SIZE, "\nStreams dump:\n");
1446 write(fd, buffer, strlen(buffer));
1447 snprintf(buffer, SIZE,
1448 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1449 write(fd, buffer, strlen(buffer));
1450 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1451 snprintf(buffer, SIZE, " %02zu ", i);
1452 write(fd, buffer, strlen(buffer));
1453 mStreams[i].dump(fd);
1456 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1457 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1458 write(fd, buffer, strlen(buffer));
1460 snprintf(buffer, SIZE, "Registered effects:\n");
1461 write(fd, buffer, strlen(buffer));
1462 for (size_t i = 0; i < mEffects.size(); i++) {
1463 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1464 write(fd, buffer, strlen(buffer));
1465 mEffects.valueAt(i)->dump(fd);
1472 // This function checks for the parameters which can be offloaded.
1473 // This can be enhanced depending on the capability of the DSP and policy
1475 bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1477 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1478 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
1479 offloadInfo.sample_rate, offloadInfo.channel_mask,
1481 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1482 offloadInfo.has_video);
1484 // Check if offload has been disabled
1485 char propValue[PROPERTY_VALUE_MAX];
1486 if (property_get("audio.offload.disable", propValue, "0")) {
1487 if (atoi(propValue) != 0) {
1488 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1493 // Check if stream type is music, then only allow offload as of now.
1494 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1496 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1500 //TODO: enable audio offloading with video when ready
1501 if (offloadInfo.has_video)
1503 ALOGV("isOffloadSupported: has_video == true, returning false");
1507 //If duration is less than minimum value defined in property, return false
1508 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1509 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1510 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1513 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1514 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1518 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1519 // creating an offloaded track and tearing it down immediately after start when audioflinger
1520 // detects there is an active non offloadable effect.
1521 // FIXME: We should check the audio session here but we do not have it in this context.
1522 // This may prevent offloading in rare situations where effects are left active by apps
1523 // in the background.
1524 if (isNonOffloadableEffectEnabled()) {
1528 // See if there is a profile to support this.
1529 // AUDIO_DEVICE_NONE
1530 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1531 offloadInfo.sample_rate,
1533 offloadInfo.channel_mask,
1534 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1535 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1536 return (profile != NULL);
1539 // ----------------------------------------------------------------------------
1540 // AudioPolicyManagerBase
1541 // ----------------------------------------------------------------------------
1543 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1545 #ifdef AUDIO_POLICY_TEST
1547 #endif //AUDIO_POLICY_TEST
1548 mPrimaryOutput((audio_io_handle_t)0),
1549 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1550 mPhoneState(AudioSystem::MODE_NORMAL),
1551 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1552 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1553 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),
1554 mSpeakerDrcEnabled(false)
1556 mpClientInterface = clientInterface;
1558 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1559 mForceUse[i] = AudioSystem::FORCE_NONE;
1562 mA2dpDeviceAddress = String8("");
1563 mScoDeviceAddress = String8("");
1564 mUsbOutCardAndDevice = String8("");
1566 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1567 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1568 ALOGE("could not load audio policy configuration file, setting defaults");
1569 defaultAudioPolicyConfig();
1573 // must be done after reading the policy
1574 initializeVolumeCurves();
1576 // open all output streams needed to access attached devices
1577 for (size_t i = 0; i < mHwModules.size(); i++) {
1578 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1579 if (mHwModules[i]->mHandle == 0) {
1580 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1583 // open all output streams needed to access attached devices
1584 // except for direct output streams that are only opened when they are actually
1585 // required by an app.
1586 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1588 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1590 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1591 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1592 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1593 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1594 outProfile->mSupportedDevices);
1595 audio_io_handle_t output = mpClientInterface->openOutput(
1596 outProfile->mModule->mHandle,
1597 &outputDesc->mDevice,
1598 &outputDesc->mSamplingRate,
1599 &outputDesc->mFormat,
1600 &outputDesc->mChannelMask,
1601 &outputDesc->mLatency,
1602 outputDesc->mFlags);
1606 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1607 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1608 if (mPrimaryOutput == 0 &&
1609 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1610 mPrimaryOutput = output;
1612 addOutput(output, outputDesc);
1613 setOutputDevice(output,
1614 (audio_devices_t)(mDefaultOutputDevice &
1615 outProfile->mSupportedDevices),
1622 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1623 "Not output found for attached devices %08x",
1624 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1626 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1628 updateDevicesAndOutputs();
1630 #ifdef AUDIO_POLICY_TEST
1631 if (mPrimaryOutput != 0) {
1632 AudioParameter outputCmd = AudioParameter();
1633 outputCmd.addInt(String8("set_id"), 0);
1634 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1636 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1637 mTestSamplingRate = 44100;
1638 mTestFormat = AudioSystem::PCM_16_BIT;
1639 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1642 mDirectOutput = false;
1643 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1644 mTestOutputs[i] = 0;
1647 const size_t SIZE = 256;
1649 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1650 run(buffer, ANDROID_PRIORITY_AUDIO);
1652 #endif //AUDIO_POLICY_TEST
1655 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1657 #ifdef AUDIO_POLICY_TEST
1659 #endif //AUDIO_POLICY_TEST
1660 for (size_t i = 0; i < mOutputs.size(); i++) {
1661 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1662 delete mOutputs.valueAt(i);
1664 for (size_t i = 0; i < mInputs.size(); i++) {
1665 mpClientInterface->closeInput(mInputs.keyAt(i));
1666 delete mInputs.valueAt(i);
1668 for (size_t i = 0; i < mHwModules.size(); i++) {
1669 delete mHwModules[i];
1673 status_t AudioPolicyManagerBase::initCheck()
1675 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1678 #ifdef AUDIO_POLICY_TEST
1679 bool AudioPolicyManagerBase::threadLoop()
1681 ALOGV("entering threadLoop()");
1682 while (!exitPending())
1688 Mutex::Autolock _l(mLock);
1689 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1691 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1692 AudioParameter param = AudioParameter(command);
1694 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1696 ALOGV("Test command %s received", command.string());
1698 if (param.get(String8("target"), target) != NO_ERROR) {
1701 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1702 param.remove(String8("test_cmd_policy_output"));
1703 mCurOutput = valueInt;
1705 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1706 param.remove(String8("test_cmd_policy_direct"));
1707 if (value == "false") {
1708 mDirectOutput = false;
1709 } else if (value == "true") {
1710 mDirectOutput = true;
1713 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1714 param.remove(String8("test_cmd_policy_input"));
1715 mTestInput = valueInt;
1718 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1719 param.remove(String8("test_cmd_policy_format"));
1720 int format = AudioSystem::INVALID_FORMAT;
1721 if (value == "PCM 16 bits") {
1722 format = AudioSystem::PCM_16_BIT;
1723 } else if (value == "PCM 8 bits") {
1724 format = AudioSystem::PCM_8_BIT;
1725 } else if (value == "Compressed MP3") {
1726 format = AudioSystem::MP3;
1728 if (format != AudioSystem::INVALID_FORMAT) {
1729 if (target == "Manager") {
1730 mTestFormat = format;
1731 } else if (mTestOutputs[mCurOutput] != 0) {
1732 AudioParameter outputParam = AudioParameter();
1733 outputParam.addInt(String8("format"), format);
1734 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1738 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1739 param.remove(String8("test_cmd_policy_channels"));
1742 if (value == "Channels Stereo") {
1743 channels = AudioSystem::CHANNEL_OUT_STEREO;
1744 } else if (value == "Channels Mono") {
1745 channels = AudioSystem::CHANNEL_OUT_MONO;
1747 if (channels != 0) {
1748 if (target == "Manager") {
1749 mTestChannels = channels;
1750 } else if (mTestOutputs[mCurOutput] != 0) {
1751 AudioParameter outputParam = AudioParameter();
1752 outputParam.addInt(String8("channels"), channels);
1753 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1757 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1758 param.remove(String8("test_cmd_policy_sampleRate"));
1759 if (valueInt >= 0 && valueInt <= 96000) {
1760 int samplingRate = valueInt;
1761 if (target == "Manager") {
1762 mTestSamplingRate = samplingRate;
1763 } else if (mTestOutputs[mCurOutput] != 0) {
1764 AudioParameter outputParam = AudioParameter();
1765 outputParam.addInt(String8("sampling_rate"), samplingRate);
1766 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1771 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1772 param.remove(String8("test_cmd_policy_reopen"));
1774 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1775 mpClientInterface->closeOutput(mPrimaryOutput);
1777 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1779 delete mOutputs.valueFor(mPrimaryOutput);
1780 mOutputs.removeItem(mPrimaryOutput);
1782 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1783 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1784 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1785 &outputDesc->mDevice,
1786 &outputDesc->mSamplingRate,
1787 &outputDesc->mFormat,
1788 &outputDesc->mChannelMask,
1789 &outputDesc->mLatency,
1790 outputDesc->mFlags);
1791 if (mPrimaryOutput == 0) {
1792 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1793 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1795 AudioParameter outputCmd = AudioParameter();
1796 outputCmd.addInt(String8("set_id"), 0);
1797 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1798 addOutput(mPrimaryOutput, outputDesc);
1803 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1809 void AudioPolicyManagerBase::exit()
1812 AutoMutex _l(mLock);
1814 mWaitWorkCV.signal();
1816 requestExitAndWait();
1819 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1821 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1822 if (output == mTestOutputs[i]) return i;
1826 #endif //AUDIO_POLICY_TEST
1830 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1832 outputDesc->mId = id;
1833 mOutputs.add(id, outputDesc);
1836 void AudioPolicyManagerBase::addInput(audio_io_handle_t id, AudioInputDescriptor *inputDesc)
1838 inputDesc->mId = id;
1839 mInputs.add(id, inputDesc);
1842 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1843 AudioSystem::device_connection_state state,
1844 SortedVector<audio_io_handle_t>& outputs,
1845 const String8 paramStr)
1847 AudioOutputDescriptor *desc;
1849 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1850 // first list already open outputs that can be routed to this device
1851 for (size_t i = 0; i < mOutputs.size(); i++) {
1852 desc = mOutputs.valueAt(i);
1853 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1854 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1855 outputs.add(mOutputs.keyAt(i));
1858 // then look for output profiles that can be routed to this device
1859 SortedVector<IOProfile *> profiles;
1860 for (size_t i = 0; i < mHwModules.size(); i++)
1862 if (mHwModules[i]->mHandle == 0) {
1865 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1867 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1868 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
1869 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1874 if (profiles.isEmpty() && outputs.isEmpty()) {
1875 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1879 // open outputs for matching profiles if needed. Direct outputs are also opened to
1880 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1881 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1882 IOProfile *profile = profiles[profile_index];
1884 // nothing to do if one output is already opened for this profile
1886 for (j = 0; j < mOutputs.size(); j++) {
1887 desc = mOutputs.valueAt(j);
1888 if (!desc->isDuplicated() && desc->mProfile == profile) {
1892 if (j != mOutputs.size()) {
1896 ALOGV("opening output for device %08x with params %s", device, paramStr.string());
1897 desc = new AudioOutputDescriptor(profile);
1898 desc->mDevice = device;
1899 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1900 offloadInfo.sample_rate = desc->mSamplingRate;
1901 offloadInfo.format = desc->mFormat;
1902 offloadInfo.channel_mask = desc->mChannelMask;
1904 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1906 &desc->mSamplingRate,
1908 &desc->mChannelMask,
1913 if (!paramStr.isEmpty()) {
1914 // Here is where the out_set_parameters() for card & device gets called
1915 mpClientInterface->setParameters(output, paramStr);
1918 // Here is where we step through and resolve any "dynamic" fields
1921 if (profile->mSamplingRates[0] == 0) {
1922 reply = mpClientInterface->getParameters(output,
1923 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1924 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1926 value = strpbrk((char *)reply.string(), "=");
1927 if (value != NULL) {
1928 loadSamplingRates(value + 1, profile);
1931 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
1932 reply = mpClientInterface->getParameters(output,
1933 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1934 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1936 value = strpbrk((char *)reply.string(), "=");
1937 if (value != NULL) {
1938 loadFormats(value + 1, profile);
1941 if (profile->mChannelMasks[0] == 0) {
1942 reply = mpClientInterface->getParameters(output,
1943 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1944 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1946 value = strpbrk((char *)reply.string(), "=");
1947 if (value != NULL) {
1948 loadOutChannels(value + 1, profile);
1951 if (((profile->mSamplingRates[0] == 0) &&
1952 (profile->mSamplingRates.size() < 2)) ||
1953 ((profile->mFormats[0] == 0) &&
1954 (profile->mFormats.size() < 2)) ||
1955 ((profile->mChannelMasks[0] == 0) &&
1956 (profile->mChannelMasks.size() < 2))) {
1957 ALOGW("checkOutputsForDevice() direct output missing param");
1958 mpClientInterface->closeOutput(output);
1960 } else if (profile->mSamplingRates[0] == 0) {
1961 mpClientInterface->closeOutput(output);
1962 desc->mSamplingRate = profile->mSamplingRates[1];
1963 offloadInfo.sample_rate = desc->mSamplingRate;
1964 output = mpClientInterface->openOutput(
1965 profile->mModule->mHandle,
1967 &desc->mSamplingRate,
1969 &desc->mChannelMask,
1976 addOutput(output, desc);
1977 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
1978 audio_io_handle_t duplicatedOutput = 0;
1980 // set initial stream volume for device
1981 applyStreamVolumes(output, device, 0, true);
1983 //TODO: configure audio effect output stage here
1985 // open a duplicating output thread for the new output and the primary output
1986 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1988 if (duplicatedOutput != 0) {
1989 // add duplicated output descriptor
1990 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1991 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1992 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1993 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1994 dupOutputDesc->mFormat = desc->mFormat;
1995 dupOutputDesc->mChannelMask = desc->mChannelMask;
1996 dupOutputDesc->mLatency = desc->mLatency;
1997 addOutput(duplicatedOutput, dupOutputDesc);
1998 applyStreamVolumes(duplicatedOutput, device, 0, true);
2000 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2001 mPrimaryOutput, output);
2002 mpClientInterface->closeOutput(output);
2003 mOutputs.removeItem(output);
2010 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2012 profiles.removeAt(profile_index);
2015 outputs.add(output);
2016 ALOGV("checkOutputsForDevice(): adding output %d", output);
2020 if (profiles.isEmpty()) {
2021 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2024 } else { // Disconnect
2025 // check if one opened output is not needed any more after disconnecting one device
2026 for (size_t i = 0; i < mOutputs.size(); i++) {
2027 desc = mOutputs.valueAt(i);
2028 if (!desc->isDuplicated() &&
2029 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
2030 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2031 outputs.add(mOutputs.keyAt(i));
2034 // Clear any profiles associated with the disconnected device.
2035 for (size_t i = 0; i < mHwModules.size(); i++)
2037 if (mHwModules[i]->mHandle == 0) {
2040 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2042 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
2043 if (profile->mSupportedDevices & device) {
2044 ALOGV("checkOutputsForDevice(): clearing direct output profile %zu on module %zu",
2046 if (profile->mSamplingRates[0] == 0) {
2047 profile->mSamplingRates.clear();
2048 profile->mSamplingRates.add(0);
2050 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2051 profile->mFormats.clear();
2052 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2054 if (profile->mChannelMasks[0] == 0) {
2055 profile->mChannelMasks.clear();
2056 profile->mChannelMasks.add(0);
2065 status_t AudioPolicyManagerBase::checkInputsForDevice(audio_devices_t device,
2066 AudioSystem::device_connection_state state,
2067 SortedVector<audio_io_handle_t>& inputs,
2068 const String8 paramStr)
2070 AudioInputDescriptor *desc;
2071 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
2072 // first list already open inputs that can be routed to this device
2073 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2074 desc = mInputs.valueAt(input_index);
2075 if (desc->mProfile->mSupportedDevices & (device & ~AUDIO_DEVICE_BIT_IN)) {
2076 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2077 inputs.add(mInputs.keyAt(input_index));
2081 // then look for input profiles that can be routed to this device
2082 SortedVector<IOProfile *> profiles;
2083 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
2085 if (mHwModules[module_index]->mHandle == 0) {
2088 for (size_t profile_index = 0;
2089 profile_index < mHwModules[module_index]->mInputProfiles.size();
2092 if (mHwModules[module_index]->mInputProfiles[profile_index]->mSupportedDevices
2093 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2094 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
2095 profile_index, module_index);
2096 profiles.add(mHwModules[module_index]->mInputProfiles[profile_index]);
2101 if (profiles.isEmpty() && inputs.isEmpty()) {
2102 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2106 // open inputs for matching profiles if needed. Direct inputs are also opened to
2107 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2108 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2110 IOProfile *profile = profiles[profile_index];
2111 // nothing to do if one input is already opened for this profile
2113 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2114 desc = mInputs.valueAt(input_index);
2115 if (desc->mProfile == profile) {
2119 if (input_index != mInputs.size()) {
2123 ALOGV("opening input for device 0x%X with params %s", device, paramStr.string());
2124 desc = new AudioInputDescriptor(profile);
2125 desc->mDevice = device;
2127 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2129 &desc->mSamplingRate,
2131 &desc->mChannelMask);
2134 if (!paramStr.isEmpty()) {
2135 mpClientInterface->setParameters(input, paramStr);
2138 // Here is where we step through and resolve any "dynamic" fields
2141 if (profile->mSamplingRates[0] == 0) {
2142 reply = mpClientInterface->getParameters(input,
2143 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2144 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2146 value = strpbrk((char *)reply.string(), "=");
2147 if (value != NULL) {
2148 loadSamplingRates(value + 1, profile);
2151 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2152 reply = mpClientInterface->getParameters(input,
2153 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2154 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2155 value = strpbrk((char *)reply.string(), "=");
2156 if (value != NULL) {
2157 loadFormats(value + 1, profile);
2160 if (profile->mChannelMasks[0] == 0) {
2161 reply = mpClientInterface->getParameters(input,
2162 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2163 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2165 value = strpbrk((char *)reply.string(), "=");
2166 if (value != NULL) {
2167 loadInChannels(value + 1, profile);
2170 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2171 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2172 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2173 ALOGW("checkInputsForDevice() direct input missing param");
2174 mpClientInterface->closeInput(input);
2179 addInput(input, desc);
2181 } // endif input != 0
2184 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2186 profiles.removeAt(profile_index);
2190 ALOGV("checkInputsForDevice(): adding input %d", input);
2192 } // end scan profiles
2194 if (profiles.isEmpty()) {
2195 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2200 // check if one opened input is not needed any more after disconnecting one device
2201 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2202 desc = mInputs.valueAt(input_index);
2203 if (!(desc->mProfile->mSupportedDevices & mAvailableInputDevices)) {
2204 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2205 mInputs.keyAt(input_index));
2206 inputs.add(mInputs.keyAt(input_index));
2209 // Clear any profiles associated with the disconnected device.
2210 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
2212 if (mHwModules[module_index]->mHandle == 0) {
2215 for (size_t profile_index = 0;
2216 profile_index < mHwModules[module_index]->mInputProfiles.size();
2219 IOProfile *profile = mHwModules[module_index]->mInputProfiles[profile_index];
2220 if (profile->mSupportedDevices & device) {
2221 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
2222 profile_index, module_index);
2223 if (profile->mSamplingRates[0] == 0) {
2224 profile->mSamplingRates.clear();
2225 profile->mSamplingRates.add(0);
2227 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2228 profile->mFormats.clear();
2229 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2231 if (profile->mChannelMasks[0] == 0) {
2232 profile->mChannelMasks.clear();
2233 profile->mChannelMasks.add(0);
2243 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
2245 ALOGV("closeOutput(%d)", output);
2247 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2248 if (outputDesc == NULL) {
2249 ALOGW("closeOutput() unknown output %d", output);
2253 // look for duplicated outputs connected to the output being removed.
2254 for (size_t i = 0; i < mOutputs.size(); i++) {
2255 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2256 if (dupOutputDesc->isDuplicated() &&
2257 (dupOutputDesc->mOutput1 == outputDesc ||
2258 dupOutputDesc->mOutput2 == outputDesc)) {
2259 AudioOutputDescriptor *outputDesc2;
2260 if (dupOutputDesc->mOutput1 == outputDesc) {
2261 outputDesc2 = dupOutputDesc->mOutput2;
2263 outputDesc2 = dupOutputDesc->mOutput1;
2265 // As all active tracks on duplicated output will be deleted,
2266 // and as they were also referenced on the other output, the reference
2267 // count for their stream type must be adjusted accordingly on
2268 // the other output.
2269 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
2270 int refCount = dupOutputDesc->mRefCount[j];
2271 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
2273 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2274 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2276 mpClientInterface->closeOutput(duplicatedOutput);
2277 delete mOutputs.valueFor(duplicatedOutput);
2278 mOutputs.removeItem(duplicatedOutput);
2282 AudioParameter param;
2283 param.add(String8("closing"), String8("true"));
2284 mpClientInterface->setParameters(output, param.toString());
2286 mpClientInterface->closeOutput(output);
2288 mOutputs.removeItem(output);
2289 mPreviousOutputs = mOutputs;
2292 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
2293 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2295 SortedVector<audio_io_handle_t> outputs;
2297 ALOGVV("getOutputsForDevice() device %04x", device);
2298 for (size_t i = 0; i < openOutputs.size(); i++) {
2299 ALOGVV("output %d isDuplicated=%d device=%04x",
2300 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2301 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2302 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2303 outputs.add(openOutputs.keyAt(i));
2309 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2310 SortedVector<audio_io_handle_t>& outputs2)
2312 if (outputs1.size() != outputs2.size()) {
2315 for (size_t i = 0; i < outputs1.size(); i++) {
2316 if (outputs1[i] != outputs2[i]) {
2323 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
2325 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2326 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2327 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2328 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2330 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2331 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2332 strategy, srcOutputs[0], dstOutputs[0]);
2333 // mute strategy while moving tracks from one output to another
2334 for (size_t i = 0; i < srcOutputs.size(); i++) {
2335 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2336 if (desc->isStrategyActive(strategy)) {
2337 setStrategyMute(strategy, true, srcOutputs[i]);
2338 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2342 // Move effects associated to this strategy from previous output to new output
2343 if (strategy == STRATEGY_MEDIA) {
2344 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2345 SortedVector<audio_io_handle_t> moved;
2346 for (size_t i = 0; i < mEffects.size(); i++) {
2347 EffectDescriptor *desc = mEffects.valueAt(i);
2348 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2349 desc->mIo != fxOutput) {
2350 if (moved.indexOf(desc->mIo) < 0) {
2351 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2352 mEffects.keyAt(i), fxOutput);
2353 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2355 moved.add(desc->mIo);
2357 desc->mIo = fxOutput;
2361 // Move tracks associated to this strategy from previous output to new output
2362 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2363 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2364 mpClientInterface->invalidateStream((AudioSystem::stream_type)i);
2370 void AudioPolicyManagerBase::checkOutputForAllStrategies()
2372 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2373 checkOutputForStrategy(STRATEGY_PHONE);
2374 checkOutputForStrategy(STRATEGY_SONIFICATION);
2375 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2376 checkOutputForStrategy(STRATEGY_MEDIA);
2377 checkOutputForStrategy(STRATEGY_DTMF);
2380 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2386 for (size_t i = 0; i < mOutputs.size(); i++) {
2387 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2388 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2389 return mOutputs.keyAt(i);
2396 void AudioPolicyManagerBase::checkA2dpSuspend()
2401 audio_io_handle_t a2dpOutput = getA2dpOutput();
2402 if (a2dpOutput == 0) {
2406 // suspend A2DP output if:
2407 // (NOT already suspended) &&
2408 // ((SCO device is connected &&
2409 // (forced usage for communication || for record is SCO))) ||
2410 // (phone state is ringing || in call)
2412 // restore A2DP output if:
2413 // (Already suspended) &&
2414 // ((SCO device is NOT connected ||
2415 // (forced usage NOT for communication && NOT for record is SCO))) &&
2416 // (phone state is NOT ringing && NOT in call)
2418 if (mA2dpSuspended) {
2419 if (((mScoDeviceAddress == "") ||
2420 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2421 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2422 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2423 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2425 mpClientInterface->restoreOutput(a2dpOutput);
2426 mA2dpSuspended = false;
2429 if (((mScoDeviceAddress != "") &&
2430 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2431 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2432 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2433 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2435 mpClientInterface->suspendOutput(a2dpOutput);
2436 mA2dpSuspended = true;
2441 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2443 audio_devices_t device = AUDIO_DEVICE_NONE;
2445 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2446 // check the following by order of priority to request a routing change if necessary:
2447 // 1: the strategy enforced audible is active on the output:
2448 // use device for strategy enforced audible
2449 // 2: we are in call or the strategy phone is active on the output:
2450 // use device for strategy phone
2451 // 3: the strategy sonification is active on the output:
2452 // use device for strategy sonification
2453 // 4: the strategy "respectful" sonification is active on the output:
2454 // use device for strategy "respectful" sonification
2455 // 5: the strategy media is active on the output:
2456 // use device for strategy media
2457 // 6: the strategy DTMF is active on the output:
2458 // use device for strategy DTMF
2459 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2460 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2461 } else if (isInCall() ||
2462 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2463 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2464 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2465 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2466 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2467 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2468 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2469 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2470 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2471 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2474 ALOGV("getNewDevice() selected device %x", device);
2478 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2479 return (uint32_t)getStrategy(stream);
2482 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2483 audio_devices_t devices;
2484 // By checking the range of stream before calling getStrategy, we avoid
2485 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2486 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2487 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2488 devices = AUDIO_DEVICE_NONE;
2490 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2491 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2496 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2497 AudioSystem::stream_type stream) {
2498 // stream to strategy mapping
2500 case AudioSystem::VOICE_CALL:
2501 case AudioSystem::BLUETOOTH_SCO:
2502 return STRATEGY_PHONE;
2503 case AudioSystem::RING:
2504 case AudioSystem::ALARM:
2505 return STRATEGY_SONIFICATION;
2506 case AudioSystem::NOTIFICATION:
2507 return STRATEGY_SONIFICATION_RESPECTFUL;
2508 case AudioSystem::DTMF:
2509 return STRATEGY_DTMF;
2511 ALOGE("unknown stream type");
2512 case AudioSystem::SYSTEM:
2513 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2514 // while key clicks are played produces a poor result
2515 case AudioSystem::TTS:
2516 case AudioSystem::MUSIC:
2517 return STRATEGY_MEDIA;
2518 case AudioSystem::ENFORCED_AUDIBLE:
2519 return STRATEGY_ENFORCED_AUDIBLE;
2523 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2525 case AudioSystem::MUSIC:
2526 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2527 updateDevicesAndOutputs();
2534 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2537 uint32_t device = AUDIO_DEVICE_NONE;
2540 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2541 strategy, mDeviceForStrategy[strategy]);
2542 return mDeviceForStrategy[strategy];
2547 case STRATEGY_SONIFICATION_RESPECTFUL:
2549 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2550 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2551 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2552 // while media is playing on a remote device, use the the sonification behavior.
2553 // Note that we test this usecase before testing if media is playing because
2554 // the isStreamActive() method only informs about the activity of a stream, not
2555 // if it's for local playback. Note also that we use the same delay between both tests
2556 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2557 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2558 // while media is playing (or has recently played), use the same device
2559 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2561 // when media is not playing anymore, fall back on the sonification behavior
2562 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2569 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2570 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2573 // when in call, DTMF and PHONE strategies follow the same rules
2576 case STRATEGY_PHONE:
2577 // for phone strategy, we first consider the forced use and then the available devices by order
2579 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2580 case AudioSystem::FORCE_BT_SCO:
2581 if (!isInCall() || strategy != STRATEGY_DTMF) {
2582 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2585 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2587 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2589 // if SCO device is requested but no SCO device is available, fall back to default case
2592 default: // FORCE_NONE
2593 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2594 if (mHasA2dp && !isInCall() &&
2595 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2596 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2597 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2599 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2602 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2604 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2606 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2607 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2609 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2611 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2613 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2615 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2618 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2620 device = mDefaultOutputDevice;
2621 if (device == AUDIO_DEVICE_NONE) {
2622 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2626 case AudioSystem::FORCE_SPEAKER:
2627 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2628 // A2DP speaker when forcing to speaker output
2629 if (mHasA2dp && !isInCall() &&
2630 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2631 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2632 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2635 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2636 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2638 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2640 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2642 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2644 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2647 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2649 device = mDefaultOutputDevice;
2650 if (device == AUDIO_DEVICE_NONE) {
2651 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2657 case STRATEGY_SONIFICATION:
2659 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2660 // handleIncallSonification().
2662 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2667 case STRATEGY_ENFORCED_AUDIBLE:
2668 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2670 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2671 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2673 if ((strategy == STRATEGY_SONIFICATION) ||
2674 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2675 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2676 if (device == AUDIO_DEVICE_NONE) {
2677 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2680 // The second device used for sonification is the same as the device used by media strategy
2683 case STRATEGY_MEDIA: {
2684 uint32_t device2 = AUDIO_DEVICE_NONE;
2685 if (strategy != STRATEGY_SONIFICATION) {
2686 // no sonification on remote submix (e.g. WFD)
2687 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2689 if ((device2 == AUDIO_DEVICE_NONE) &&
2690 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2691 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2692 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2693 if (device2 == AUDIO_DEVICE_NONE) {
2694 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2696 if (device2 == AUDIO_DEVICE_NONE) {
2697 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2700 if (device2 == AUDIO_DEVICE_NONE) {
2701 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2703 if (device2 == AUDIO_DEVICE_NONE) {
2704 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2706 if (device2 == AUDIO_DEVICE_NONE) {
2707 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2709 if (device2 == AUDIO_DEVICE_NONE) {
2710 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2712 if (device2 == AUDIO_DEVICE_NONE) {
2713 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2715 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2716 // no sonification on aux digital (e.g. HDMI)
2717 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2719 if ((device2 == AUDIO_DEVICE_NONE) &&
2720 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2721 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2723 if (device2 == AUDIO_DEVICE_NONE) {
2724 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2727 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2728 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2731 device = mDefaultOutputDevice;
2732 if (device == AUDIO_DEVICE_NONE) {
2733 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2738 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2742 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2746 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2748 for (int i = 0; i < NUM_STRATEGIES; i++) {
2749 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2751 mPreviousOutputs = mOutputs;
2754 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2755 audio_devices_t prevDevice,
2758 // mute/unmute strategies using an incompatible device combination
2759 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2760 // if unmuting, unmute only after the specified delay
2761 if (outputDesc->isDuplicated()) {
2765 uint32_t muteWaitMs = 0;
2766 audio_devices_t device = outputDesc->device();
2767 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2768 // temporary mute output if device selection changes to avoid volume bursts due to
2769 // different per device volumes
2770 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2772 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2773 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2774 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2775 bool doMute = false;
2777 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2779 outputDesc->mStrategyMutedByDevice[i] = true;
2780 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2782 outputDesc->mStrategyMutedByDevice[i] = false;
2784 if (doMute || tempMute) {
2785 for (size_t j = 0; j < mOutputs.size(); j++) {
2786 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2787 // skip output if it does not share any device with current output
2788 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2789 == AUDIO_DEVICE_NONE) {
2792 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2793 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2794 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2795 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2796 if (desc->isStrategyActive((routing_strategy)i)) {
2797 // do tempMute only for current output
2798 if (tempMute && (desc == outputDesc)) {
2799 setStrategyMute((routing_strategy)i, true, curOutput);
2800 setStrategyMute((routing_strategy)i, false, curOutput,
2801 desc->latency() * 2, device);
2803 if ((tempMute && (desc == outputDesc)) || mute) {
2804 if (muteWaitMs < desc->latency()) {
2805 muteWaitMs = desc->latency();
2813 // FIXME: should not need to double latency if volume could be applied immediately by the
2814 // audioflinger mixer. We must account for the delay between now and the next time
2815 // the audioflinger thread for this output will process a buffer (which corresponds to
2816 // one buffer size, usually 1/2 or 1/4 of the latency).
2818 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2819 if (muteWaitMs > delayMs) {
2820 muteWaitMs -= delayMs;
2821 usleep(muteWaitMs * 1000);
2827 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2828 audio_devices_t device,
2832 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2833 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2834 AudioParameter param;
2835 uint32_t muteWaitMs;
2837 if (outputDesc->isDuplicated()) {
2838 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2839 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2842 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2844 if ((device != AUDIO_DEVICE_NONE) &&
2845 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2849 // filter devices according to output selected
2850 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2852 audio_devices_t prevDevice = outputDesc->mDevice;
2854 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2856 if (device != AUDIO_DEVICE_NONE) {
2857 outputDesc->mDevice = device;
2859 // Force routing if previously asked for this output
2860 if (outputDesc->mForceRouting) {
2861 ALOGV("Force routing to current device as previous device was null for this output");
2864 // Request consumed. Reset mForceRouting to false
2865 outputDesc->mForceRouting = false;
2869 // Device is null and does not reflect the routing. Save the necessity to force
2870 // re-routing upon next attempt to select a non-null device for this output
2871 outputDesc->mForceRouting = true;
2874 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2876 // Do not change the routing if:
2877 // - the requested device is AUDIO_DEVICE_NONE
2878 // - the requested device is the same as current device and force is not specified.
2879 // Doing this check here allows the caller to call setOutputDevice() without conditions
2880 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2881 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2885 ALOGV("setOutputDevice() changing device");
2887 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2888 mpClientInterface->setParameters(output, param.toString(), delayMs);
2890 // update stream volumes according to new device
2891 applyStreamVolumes(output, device, delayMs);
2896 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2897 uint32_t samplingRate,
2898 audio_format_t format,
2899 audio_channel_mask_t channelMask)
2901 // Choose an input profile based on the requested capture parameters: select the first available
2902 // profile supporting all requested parameters.
2903 for (size_t i = 0; i < mHwModules.size(); i++)
2905 if (mHwModules[i]->mHandle == 0) {
2908 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2910 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2912 if (profile->isCompatibleProfile(device, samplingRate, format,
2913 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
2921 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2923 uint32_t device = AUDIO_DEVICE_NONE;
2925 switch (inputSource) {
2926 case AUDIO_SOURCE_VOICE_UPLINK:
2927 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2928 device = AUDIO_DEVICE_IN_VOICE_CALL;
2933 case AUDIO_SOURCE_DEFAULT:
2934 case AUDIO_SOURCE_MIC:
2935 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
2936 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
2941 case AUDIO_SOURCE_VOICE_RECOGNITION:
2942 case AUDIO_SOURCE_HOTWORD:
2943 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2944 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2945 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2946 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2947 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2948 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2949 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_USB_DEVICE) {
2950 device = AUDIO_DEVICE_IN_USB_DEVICE;
2951 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2952 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2955 case AUDIO_SOURCE_CAMCORDER:
2956 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2957 device = AUDIO_DEVICE_IN_BACK_MIC;
2958 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2959 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2962 case AUDIO_SOURCE_VOICE_DOWNLINK:
2963 case AUDIO_SOURCE_VOICE_CALL:
2964 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2965 device = AUDIO_DEVICE_IN_VOICE_CALL;
2968 case AUDIO_SOURCE_REMOTE_SUBMIX:
2969 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2970 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2974 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2977 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2981 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2983 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2984 device &= ~AUDIO_DEVICE_BIT_IN;
2985 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2991 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2993 for (size_t i = 0; i < mInputs.size(); i++) {
2994 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2995 if ((input_descriptor->mRefCount > 0)
2996 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2997 return mInputs.keyAt(i);
3004 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
3006 if (device == AUDIO_DEVICE_NONE) {
3007 // this happens when forcing a route update and no track is active on an output.
3008 // In this case the returned category is not important.
3009 device = AUDIO_DEVICE_OUT_SPEAKER;
3010 } else if (AudioSystem::popCount(device) > 1) {
3011 // Multiple device selection is either:
3012 // - speaker + one other device: give priority to speaker in this case.
3013 // - one A2DP device + another device: happens with duplicated output. In this case
3014 // retain the device on the A2DP output as the other must not correspond to an active
3015 // selection if not the speaker.
3016 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3017 device = AUDIO_DEVICE_OUT_SPEAKER;
3019 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3023 ALOGW_IF(AudioSystem::popCount(device) != 1,
3024 "getDeviceForVolume() invalid device combination: %08x",
3030 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
3032 switch(getDeviceForVolume(device)) {
3033 case AUDIO_DEVICE_OUT_EARPIECE:
3034 return DEVICE_CATEGORY_EARPIECE;
3035 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3036 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3037 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3038 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3039 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3040 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3041 return DEVICE_CATEGORY_HEADSET;
3042 case AUDIO_DEVICE_OUT_SPEAKER:
3043 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3044 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3045 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3046 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3047 case AUDIO_DEVICE_OUT_USB_DEVICE:
3048 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3050 return DEVICE_CATEGORY_SPEAKER;
3054 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
3057 device_category deviceCategory = getDeviceCategory(device);
3058 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3060 // the volume index in the UI is relative to the min and max volume indices for this stream type
3061 int nbSteps = 1 + curve[VOLMAX].mIndex -
3062 curve[VOLMIN].mIndex;
3063 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3064 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3066 // find what part of the curve this index volume belongs to, or if it's out of bounds
3068 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3070 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3072 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3074 } else if (volIdx <= curve[VOLMAX].mIndex) {
3076 } else { // out of bounds
3080 // linear interpolation in the attenuation table in dB
3081 float decibels = curve[segment].mDBAttenuation +
3082 ((float)(volIdx - curve[segment].mIndex)) *
3083 ( (curve[segment+1].mDBAttenuation -
3084 curve[segment].mDBAttenuation) /
3085 ((float)(curve[segment+1].mIndex -
3086 curve[segment].mIndex)) );
3088 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3090 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3091 curve[segment].mIndex, volIdx,
3092 curve[segment+1].mIndex,
3093 curve[segment].mDBAttenuation,
3095 curve[segment+1].mDBAttenuation,
3098 return amplification;
3101 const AudioPolicyManagerBase::VolumeCurvePoint
3102 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3103 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3106 const AudioPolicyManagerBase::VolumeCurvePoint
3107 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3108 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3111 const AudioPolicyManagerBase::VolumeCurvePoint
3112 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3113 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3116 const AudioPolicyManagerBase::VolumeCurvePoint
3117 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3118 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3121 const AudioPolicyManagerBase::VolumeCurvePoint
3122 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
3123 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3126 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3127 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3128 // AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3129 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3131 const AudioPolicyManagerBase::VolumeCurvePoint
3132 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3133 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3136 const AudioPolicyManagerBase::VolumeCurvePoint
3137 AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
3138 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3141 const AudioPolicyManagerBase::VolumeCurvePoint
3142 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3143 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3146 const AudioPolicyManagerBase::VolumeCurvePoint
3147 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3148 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3151 const AudioPolicyManagerBase::VolumeCurvePoint
3152 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3153 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3156 const AudioPolicyManagerBase::VolumeCurvePoint
3157 *AudioPolicyManagerBase::sVolumeProfiles[AudioSystem::NUM_STREAM_TYPES]
3158 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
3159 { // AUDIO_STREAM_VOICE_CALL
3160 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3161 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3162 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3164 { // AUDIO_STREAM_SYSTEM
3165 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3166 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3167 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3169 { // AUDIO_STREAM_RING
3170 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3171 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3172 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3174 { // AUDIO_STREAM_MUSIC
3175 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3176 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3177 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3179 { // AUDIO_STREAM_ALARM
3180 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3181 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3182 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3184 { // AUDIO_STREAM_NOTIFICATION
3185 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3186 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3187 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3189 { // AUDIO_STREAM_BLUETOOTH_SCO
3190 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3191 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3192 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3194 { // AUDIO_STREAM_ENFORCED_AUDIBLE
3195 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3196 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3197 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3199 { // AUDIO_STREAM_DTMF
3200 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3201 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3202 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3204 { // AUDIO_STREAM_TTS
3205 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3206 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3207 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3211 void AudioPolicyManagerBase::initializeVolumeCurves()
3213 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3214 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
3215 mStreams[i].mVolumeCurve[j] =
3216 sVolumeProfiles[i][j];
3220 // Check availability of DRC on speaker path: if available, override some of the speaker curves
3221 if (mSpeakerDrcEnabled) {
3222 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3223 sDefaultSystemVolumeCurveDrc;
3224 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3225 sSpeakerSonificationVolumeCurveDrc;
3226 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3227 sSpeakerSonificationVolumeCurveDrc;
3228 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3229 sSpeakerSonificationVolumeCurveDrc;
3233 float AudioPolicyManagerBase::computeVolume(int stream,
3235 audio_io_handle_t output,
3236 audio_devices_t device)
3239 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3240 StreamDescriptor &streamDesc = mStreams[stream];
3242 if (device == AUDIO_DEVICE_NONE) {
3243 device = outputDesc->device();
3246 // if volume is not 0 (not muted), force media volume to max on digital output
3247 if (stream == AudioSystem::MUSIC &&
3248 index != mStreams[stream].mIndexMin &&
3249 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3250 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
3254 volume = volIndexToAmpl(device, streamDesc, index);
3256 // if a headset is connected, apply the following rules to ring tones and notifications
3257 // to avoid sound level bursts in user's ears:
3258 // - always attenuate ring tones and notifications volume by 6dB
3259 // - if music is playing, always limit the volume to current music volume,
3260 // with a minimum threshold at -36dB so that notification is always perceived.
3261 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3262 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3263 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3264 AUDIO_DEVICE_OUT_WIRED_HEADSET |
3265 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3266 ((stream_strategy == STRATEGY_SONIFICATION)
3267 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
3268 || (stream == AudioSystem::SYSTEM)
3269 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
3270 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
3271 streamDesc.mCanBeMuted) {
3272 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3273 // when the phone is ringing we must consider that music could have been paused just before
3274 // by the music application and behave as if music was active if the last music track was
3276 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
3277 mLimitRingtoneVolume) {
3278 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
3279 float musicVol = computeVolume(AudioSystem::MUSIC,
3280 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
3283 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3284 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3285 if (volume > minVol) {
3287 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3295 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
3297 audio_io_handle_t output,
3298 audio_devices_t device,
3303 // do not change actual stream volume if the stream is muted
3304 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3305 ALOGVV("checkAndSetVolume() stream %d muted count %d",
3306 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3310 // do not change in call volume if bluetooth is connected and vice versa
3311 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
3312 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
3313 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
3314 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
3315 return INVALID_OPERATION;
3318 float volume = computeVolume(stream, index, output, device);
3319 // We actually change the volume if:
3320 // - the float value returned by computeVolume() changed
3321 // - the force flag is set
3322 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3324 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3325 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3326 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3328 if (stream == AudioSystem::BLUETOOTH_SCO) {
3329 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
3331 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
3334 if (stream == AudioSystem::VOICE_CALL ||
3335 stream == AudioSystem::BLUETOOTH_SCO) {
3337 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3338 if (stream == AudioSystem::VOICE_CALL) {
3339 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3344 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3345 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3346 mLastVoiceVolume = voiceVolume;
3353 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
3354 audio_devices_t device,
3358 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3360 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3361 checkAndSetVolume(stream,
3362 mStreams[stream].getVolumeIndex(device),
3370 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
3372 audio_io_handle_t output,
3374 audio_devices_t device)
3376 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3377 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3378 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3379 setStreamMute(stream, on, output, delayMs, device);
3384 void AudioPolicyManagerBase::setStreamMute(int stream,
3386 audio_io_handle_t output,
3388 audio_devices_t device)
3390 StreamDescriptor &streamDesc = mStreams[stream];
3391 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3392 if (device == AUDIO_DEVICE_NONE) {
3393 device = outputDesc->device();
3396 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3397 stream, on, output, outputDesc->mMuteCount[stream], device);
3400 if (outputDesc->mMuteCount[stream] == 0) {
3401 if (streamDesc.mCanBeMuted &&
3402 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3403 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3404 checkAndSetVolume(stream, 0, output, device, delayMs);
3407 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3408 outputDesc->mMuteCount[stream]++;
3410 if (outputDesc->mMuteCount[stream] == 0) {
3411 ALOGV("setStreamMute() unmuting non muted stream!");
3414 if (--outputDesc->mMuteCount[stream] == 0) {
3415 checkAndSetVolume(stream,
3416 streamDesc.getVolumeIndex(device),
3424 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3426 // if the stream pertains to sonification strategy and we are in call we must
3427 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3428 // in the device used for phone strategy and play the tone if the selected device does not
3429 // interfere with the device used for phone strategy
3430 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3431 // many times as there are active tracks on the output
3432 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3433 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3434 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3435 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3436 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3437 stream, starting, outputDesc->mDevice, stateChange);
3438 if (outputDesc->mRefCount[stream]) {
3441 muteCount = outputDesc->mRefCount[stream];
3443 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3444 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3445 for (int i = 0; i < muteCount; i++) {
3446 setStreamMute(stream, starting, mPrimaryOutput);
3449 ALOGV("handleIncallSonification() high visibility");
3450 if (outputDesc->device() &
3451 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3452 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3453 for (int i = 0; i < muteCount; i++) {
3454 setStreamMute(stream, starting, mPrimaryOutput);
3458 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3460 mpClientInterface->stopTone();
3467 bool AudioPolicyManagerBase::isInCall()
3469 return isStateInCall(mPhoneState);
3472 bool AudioPolicyManagerBase::isStateInCall(int state) {
3473 return ((state == AudioSystem::MODE_IN_CALL) ||
3474 (state == AudioSystem::MODE_IN_COMMUNICATION));
3477 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3479 return MAX_EFFECTS_CPU_LOAD;
3482 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3484 return MAX_EFFECTS_MEMORY;
3487 // --- AudioOutputDescriptor class implementation
3489 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3490 const IOProfile *profile)
3491 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3492 mChannelMask(0), mLatency(0),
3493 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3494 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0),
3495 mForceRouting(false)
3497 // clear usage count for all stream types
3498 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3500 mCurVolume[i] = -1.0;
3504 for (int i = 0; i < NUM_STRATEGIES; i++) {
3505 mStrategyMutedByDevice[i] = false;
3507 if (profile != NULL) {
3508 mSamplingRate = profile->mSamplingRates[0];
3509 mFormat = profile->mFormats[0];
3510 mChannelMask = profile->mChannelMasks[0];
3511 mFlags = profile->mFlags;
3515 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3517 if (isDuplicated()) {
3518 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3524 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3526 if (isDuplicated()) {
3527 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3533 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3534 const AudioOutputDescriptor *outputDesc)
3536 if (isDuplicated()) {
3537 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3538 } else if (outputDesc->isDuplicated()){
3539 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3541 return (mProfile->mModule == outputDesc->mProfile->mModule);
3545 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3547 // forward usage count change to attached outputs
3548 if (isDuplicated()) {
3549 mOutput1->changeRefCount(stream, delta);
3550 mOutput2->changeRefCount(stream, delta);
3552 if ((delta + (int)mRefCount[stream]) < 0) {
3553 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3554 mRefCount[stream] = 0;
3557 mRefCount[stream] += delta;
3558 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3561 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3563 if (isDuplicated()) {
3564 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3566 return mProfile->mSupportedDevices ;
3570 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3572 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3575 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3577 nsecs_t sysTime) const
3579 if ((sysTime == 0) && (inPastMs != 0)) {
3580 sysTime = systemTime();
3582 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3583 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3584 (NUM_STRATEGIES == strategy)) &&
3585 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3592 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3594 nsecs_t sysTime) const
3596 if (mRefCount[stream] != 0) {
3599 if (inPastMs == 0) {
3603 sysTime = systemTime();
3605 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3612 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3614 const size_t SIZE = 256;
3618 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3619 result.append(buffer);
3620 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3621 result.append(buffer);
3622 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3623 result.append(buffer);
3624 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3625 result.append(buffer);
3626 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3627 result.append(buffer);
3628 snprintf(buffer, SIZE, " Devices %08x\n", device());
3629 result.append(buffer);
3630 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3631 result.append(buffer);
3632 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3633 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3634 result.append(buffer);
3636 write(fd, result.string(), result.size());
3641 // --- AudioInputDescriptor class implementation
3643 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3644 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
3645 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3646 mInputSource(0), mProfile(profile)
3648 if (profile != NULL) {
3649 mSamplingRate = profile->mSamplingRates[0];
3650 mFormat = profile->mFormats[0];
3651 mChannelMask = profile->mChannelMasks[0];
3655 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3657 const size_t SIZE = 256;
3661 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3662 result.append(buffer);
3663 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3664 result.append(buffer);
3665 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3666 result.append(buffer);
3667 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3668 result.append(buffer);
3669 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3670 result.append(buffer);
3671 write(fd, result.string(), result.size());
3676 // --- StreamDescriptor class implementation
3678 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3679 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3681 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3684 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3686 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3687 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3688 if (mIndexCur.indexOfKey(device) < 0) {
3689 device = AUDIO_DEVICE_OUT_DEFAULT;
3691 return mIndexCur.valueFor(device);
3694 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3696 const size_t SIZE = 256;
3700 snprintf(buffer, SIZE, "%s %02d %02d ",
3701 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3702 result.append(buffer);
3703 for (size_t i = 0; i < mIndexCur.size(); i++) {
3704 snprintf(buffer, SIZE, "%04x : %02d, ",
3706 mIndexCur.valueAt(i));
3707 result.append(buffer);
3709 result.append("\n");
3711 write(fd, result.string(), result.size());
3714 // --- EffectDescriptor class implementation
3716 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3718 const size_t SIZE = 256;
3722 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3723 result.append(buffer);
3724 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3725 result.append(buffer);
3726 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3727 result.append(buffer);
3728 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3729 result.append(buffer);
3730 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3731 result.append(buffer);
3732 write(fd, result.string(), result.size());
3737 // --- IOProfile class implementation
3739 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3740 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3744 AudioPolicyManagerBase::HwModule::~HwModule()
3746 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3747 delete mOutputProfiles[i];
3749 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3750 delete mInputProfiles[i];
3752 free((void *)mName);
3755 void AudioPolicyManagerBase::HwModule::dump(int fd)
3757 const size_t SIZE = 256;
3761 snprintf(buffer, SIZE, " - name: %s\n", mName);
3762 result.append(buffer);
3763 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3764 result.append(buffer);
3765 write(fd, result.string(), result.size());
3766 if (mOutputProfiles.size()) {
3767 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
3768 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3769 snprintf(buffer, SIZE, " output %zu:\n", i);
3770 write(fd, buffer, strlen(buffer));
3771 mOutputProfiles[i]->dump(fd);
3774 if (mInputProfiles.size()) {
3775 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
3776 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3777 snprintf(buffer, SIZE, " input %zu:\n", i);
3778 write(fd, buffer, strlen(buffer));
3779 mInputProfiles[i]->dump(fd);
3784 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3785 : mFlags((audio_output_flags_t)0), mModule(module)
3789 AudioPolicyManagerBase::IOProfile::~IOProfile()
3793 // checks if the IO profile is compatible with specified parameters.
3794 // Sampling rate, format and channel mask must be specified in order to
3795 // get a valid a match
3796 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3797 uint32_t samplingRate,
3798 audio_format_t format,
3799 audio_channel_mask_t channelMask,
3800 audio_output_flags_t flags) const
3802 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3806 if ((mSupportedDevices & device) != device) {
3809 if ((mFlags & flags) != flags) {
3813 for (i = 0; i < mSamplingRates.size(); i++)
3815 if (mSamplingRates[i] == samplingRate) {
3819 if (i == mSamplingRates.size()) {
3822 for (i = 0; i < mFormats.size(); i++)
3824 if (mFormats[i] == format) {
3828 if (i == mFormats.size()) {
3831 for (i = 0; i < mChannelMasks.size(); i++)
3833 if (mChannelMasks[i] == channelMask) {
3837 if (i == mChannelMasks.size()) {
3843 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3845 const size_t SIZE = 256;
3849 snprintf(buffer, SIZE, " - sampling rates: ");
3850 result.append(buffer);
3851 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3852 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3853 result.append(buffer);
3854 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3857 snprintf(buffer, SIZE, " - channel masks: ");
3858 result.append(buffer);
3859 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3860 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3861 result.append(buffer);
3862 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3865 snprintf(buffer, SIZE, " - formats: ");
3866 result.append(buffer);
3867 for (size_t i = 0; i < mFormats.size(); i++) {
3868 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3869 result.append(buffer);
3870 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3873 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
3874 result.append(buffer);
3875 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3876 result.append(buffer);
3878 write(fd, result.string(), result.size());
3881 void AudioPolicyManagerBase::IOProfile::log()
3883 const size_t SIZE = 256;
3887 ALOGV(" - sampling rates: ");
3888 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3889 ALOGV(" %d", mSamplingRates[i]);
3892 ALOGV(" - channel masks: ");
3893 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3894 ALOGV(" 0x%04x", mChannelMasks[i]);
3897 ALOGV(" - formats: ");
3898 for (size_t i = 0; i < mFormats.size(); i++) {
3899 ALOGV(" 0x%08x", mFormats[i]);
3902 ALOGV(" - devices: 0x%04x\n", mSupportedDevices);
3903 ALOGV(" - flags: 0x%04x\n", mFlags);
3906 // --- audio_policy.conf file parsing
3908 struct StringToEnum {
3913 #define STRING_TO_ENUM(string) { #string, string }
3914 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3916 const struct StringToEnum sDeviceNameToEnumTable[] = {
3917 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3918 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3919 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3920 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3921 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3922 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3923 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3924 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3925 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3926 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3927 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3928 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3929 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3930 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3931 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3932 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3933 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3934 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3935 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3936 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3937 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3938 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3939 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3940 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
3941 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
3944 const struct StringToEnum sFlagNameToEnumTable[] = {
3945 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3946 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3947 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3948 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3949 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3950 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3953 const struct StringToEnum sFormatNameToEnumTable[] = {
3954 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3955 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3956 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
3957 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
3958 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
3959 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
3960 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3961 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3962 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3963 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
3964 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
3965 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
3966 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
3967 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
3970 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3971 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3972 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3973 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3974 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3977 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3978 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3979 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3980 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3984 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3988 for (size_t i = 0; i < size; i++) {
3989 if (strcmp(table[i].name, name) == 0) {
3990 ALOGV("stringToEnum() found %s", table[i].name);
3991 return table[i].value;
3997 bool AudioPolicyManagerBase::stringToBool(const char *value)
3999 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
4002 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
4006 // it is OK to cast name to non const here as we are not going to use it after
4007 // strtok() modifies it
4008 char *flagName = strtok(name, "|");
4009 while (flagName != NULL) {
4010 if (strlen(flagName) != 0) {
4011 flag |= stringToEnum(sFlagNameToEnumTable,
4012 ARRAY_SIZE(sFlagNameToEnumTable),
4015 flagName = strtok(NULL, "|");
4017 //force direct flag if offload flag is set: offloading implies a direct output stream
4018 // and all common behaviors are driven by checking only the direct flag
4019 // this should normally be set appropriately in the policy configuration file
4020 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
4021 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
4024 return (audio_output_flags_t)flag;
4027 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
4029 uint32_t device = 0;
4031 char *devName = strtok(name, "|");
4032 while (devName != NULL) {
4033 if (strlen(devName) != 0) {
4034 device |= stringToEnum(sDeviceNameToEnumTable,
4035 ARRAY_SIZE(sDeviceNameToEnumTable),
4038 devName = strtok(NULL, "|");
4043 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
4045 char *str = strtok(name, "|");
4047 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4048 // rates should be read from the output stream after it is opened for the first time
4049 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4050 profile->mSamplingRates.add(0);
4054 while (str != NULL) {
4055 uint32_t rate = atoi(str);
4057 ALOGV("loadSamplingRates() adding rate %d", rate);
4058 profile->mSamplingRates.add(rate);
4060 str = strtok(NULL, "|");
4065 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
4067 char *str = strtok(name, "|");
4069 // by convention, "0' in the first entry in mFormats indicates the supported formats
4070 // should be read from the output stream after it is opened for the first time
4071 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4072 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
4076 while (str != NULL) {
4077 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4078 ARRAY_SIZE(sFormatNameToEnumTable),
4080 if (format != AUDIO_FORMAT_DEFAULT) {
4081 profile->mFormats.add(format);
4083 str = strtok(NULL, "|");
4088 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
4090 const char *str = strtok(name, "|");
4092 ALOGV("loadInChannels() %s", name);
4094 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4095 profile->mChannelMasks.add(0);
4099 while (str != NULL) {
4100 audio_channel_mask_t channelMask =
4101 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4102 ARRAY_SIZE(sInChannelsNameToEnumTable),
4104 if (channelMask != 0) {
4105 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4106 profile->mChannelMasks.add(channelMask);
4108 str = strtok(NULL, "|");
4113 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
4115 const char *str = strtok(name, "|");
4117 ALOGV("loadOutChannels() %s", name);
4119 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4120 // masks should be read from the output stream after it is opened for the first time
4121 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4122 profile->mChannelMasks.add(0);
4126 while (str != NULL) {
4127 audio_channel_mask_t channelMask =
4128 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4129 ARRAY_SIZE(sOutChannelsNameToEnumTable),
4131 if (channelMask != 0) {
4132 profile->mChannelMasks.add(channelMask);
4134 str = strtok(NULL, "|");
4139 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
4141 cnode *node = root->first_child;
4143 IOProfile *profile = new IOProfile(module);
4146 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4147 loadSamplingRates((char *)node->value, profile);
4148 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4149 loadFormats((char *)node->value, profile);
4150 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4151 loadInChannels((char *)node->value, profile);
4152 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4153 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
4157 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
4158 "loadInput() invalid supported devices");
4159 ALOGW_IF(profile->mChannelMasks.size() == 0,
4160 "loadInput() invalid supported channel masks");
4161 ALOGW_IF(profile->mSamplingRates.size() == 0,
4162 "loadInput() invalid supported sampling rates");
4163 ALOGW_IF(profile->mFormats.size() == 0,
4164 "loadInput() invalid supported formats");
4165 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
4166 (profile->mChannelMasks.size() != 0) &&
4167 (profile->mSamplingRates.size() != 0) &&
4168 (profile->mFormats.size() != 0)) {
4170 ALOGV("loadInput() adding input mSupportedDevices 0x%X", profile->mSupportedDevices);
4172 module->mInputProfiles.add(profile);
4180 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
4182 cnode *node = root->first_child;
4184 IOProfile *profile = new IOProfile(module);
4187 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4188 loadSamplingRates((char *)node->value, profile);
4189 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4190 loadFormats((char *)node->value, profile);
4191 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4192 loadOutChannels((char *)node->value, profile);
4193 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4194 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
4195 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4196 profile->mFlags = parseFlagNames((char *)node->value);
4200 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
4201 "loadOutput() invalid supported devices");
4202 ALOGW_IF(profile->mChannelMasks.size() == 0,
4203 "loadOutput() invalid supported channel masks");
4204 ALOGW_IF(profile->mSamplingRates.size() == 0,
4205 "loadOutput() invalid supported sampling rates");
4206 ALOGW_IF(profile->mFormats.size() == 0,
4207 "loadOutput() invalid supported formats");
4208 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
4209 (profile->mChannelMasks.size() != 0) &&
4210 (profile->mSamplingRates.size() != 0) &&
4211 (profile->mFormats.size() != 0)) {
4213 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
4214 profile->mSupportedDevices, profile->mFlags);
4216 module->mOutputProfiles.add(profile);
4224 void AudioPolicyManagerBase::loadHwModule(cnode *root)
4226 cnode *node = config_find(root, OUTPUTS_TAG);
4227 status_t status = NAME_NOT_FOUND;
4229 HwModule *module = new HwModule(root->name);
4232 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
4234 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
4236 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
4237 mHasRemoteSubmix = true;
4240 node = node->first_child;
4242 ALOGV("loadHwModule() loading output %s", node->name);
4243 status_t tmpStatus = loadOutput(node, module);
4244 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4250 node = config_find(root, INPUTS_TAG);
4252 node = node->first_child;
4254 ALOGV("loadHwModule() loading input %s", node->name);
4255 status_t tmpStatus = loadInput(node, module);
4256 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4262 if (status == NO_ERROR) {
4263 mHwModules.add(module);
4269 void AudioPolicyManagerBase::loadHwModules(cnode *root)
4271 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
4276 node = node->first_child;
4278 ALOGV("loadHwModules() loading module %s", node->name);
4284 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
4286 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4290 node = node->first_child;
4292 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
4293 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
4294 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
4295 "loadGlobalConfig() no attached output devices");
4296 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
4297 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
4298 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
4299 ARRAY_SIZE(sDeviceNameToEnumTable),
4300 (char *)node->value);
4301 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
4302 "loadGlobalConfig() default device not specified");
4303 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
4304 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
4305 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
4306 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
4307 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4308 mSpeakerDrcEnabled = stringToBool((char *)node->value);
4309 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4315 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
4320 data = (char *)load_file(path, NULL);
4324 root = config_node("", "");
4325 config_load(root, data);
4327 loadGlobalConfig(root);
4328 loadHwModules(root);
4334 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4339 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
4344 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
4345 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
4346 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
4348 module = new HwModule("primary");
4350 profile = new IOProfile(module);
4351 profile->mSamplingRates.add(44100);
4352 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4353 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4354 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
4355 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4356 module->mOutputProfiles.add(profile);
4358 profile = new IOProfile(module);
4359 profile->mSamplingRates.add(8000);
4360 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4361 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4362 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
4363 module->mInputProfiles.add(profile);
4365 mHwModules.add(module);
4368 }; // namespace android