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>
40 #include <hardware/audio.h>
41 #include <hardware/audio_effect.h>
42 #include <hardware_legacy/audio_policy_conf.h>
43 #include <hardware_legacy/AudioPolicyManagerBase.h>
45 namespace android_audio_legacy {
47 // ----------------------------------------------------------------------------
48 // AudioPolicyInterface implementation
49 // ----------------------------------------------------------------------------
52 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
53 AudioSystem::device_connection_state state,
54 const char *device_address)
56 ALOGV("setDeviceConnectionState() device: 0x%X, state %d, address %s", device, state, device_address);
58 // connect/disconnect only 1 device at a time
59 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
61 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
62 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
66 // handle output devices
67 if (audio_is_output_device(device)) {
68 SortedVector <audio_io_handle_t> outputs;
70 if (!mHasA2dp && audio_is_a2dp_device(device)) {
71 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
74 if (!mHasUsb && audio_is_usb_out_device(device)) {
75 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
78 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
79 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
83 // save a copy of the opened output descriptors before any output is opened or closed
84 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
85 mPreviousOutputs = mOutputs;
89 // handle output device connection
90 case AudioSystem::DEVICE_STATE_AVAILABLE:
91 if (mAvailableOutputDevices & device) {
92 ALOGW("setDeviceConnectionState() device already connected: %x", device);
93 return INVALID_OPERATION;
95 ALOGV("setDeviceConnectionState() connecting device %x", device);
97 if (mHasA2dp && audio_is_a2dp_device(device)) {
98 // handle A2DP device connection
100 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
101 paramStr = param.toString();
102 } else if (mHasUsb && audio_is_usb_out_device(device)) {
103 // handle USB device connection
104 paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
107 if (checkOutputsForDevice(device, state, outputs, paramStr) != NO_ERROR) {
108 return INVALID_OPERATION;
110 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
112 // register new device as available
113 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
115 if (mHasA2dp && audio_is_a2dp_device(device)) {
116 // handle A2DP device connection
117 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
118 mA2dpSuspended = false;
119 } else if (audio_is_bluetooth_sco_device(device)) {
120 // handle SCO device connection
121 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
122 } else if (mHasUsb && audio_is_usb_out_device(device)) {
123 // handle USB device connection
124 mUsbOutCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
128 // handle output device disconnection
129 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
130 if (!(mAvailableOutputDevices & device)) {
131 ALOGW("setDeviceConnectionState() device not connected: %x", device);
132 return INVALID_OPERATION;
135 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
136 // remove device from available output devices
137 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
138 checkOutputsForDevice(device, state, outputs, paramStr);
140 if (mHasA2dp && audio_is_a2dp_device(device)) {
141 // handle A2DP device disconnection
142 mA2dpDeviceAddress = "";
143 mA2dpSuspended = false;
144 } else if (audio_is_bluetooth_sco_device(device)) {
145 // handle SCO device disconnection
146 mScoDeviceAddress = "";
147 } else if (mHasUsb && audio_is_usb_out_device(device)) {
148 // handle USB device disconnection
149 mUsbOutCardAndDevice = "";
151 // not currently handling multiple simultaneous submixes: ignoring remote submix
156 ALOGE("setDeviceConnectionState() invalid state: %x", state);
161 checkOutputForAllStrategies();
162 // outputs must be closed after checkOutputForAllStrategies() is executed
163 if (!outputs.isEmpty()) {
164 for (size_t i = 0; i < outputs.size(); i++) {
165 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
166 // close unused outputs after device disconnection or direct outputs that have been
167 // opened by checkOutputsForDevice() to query dynamic parameters
168 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
169 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
170 (desc->mDirectOpenCount == 0))) {
171 closeOutput(outputs[i]);
176 updateDevicesAndOutputs();
177 for (size_t i = 0; i < mOutputs.size(); i++) {
178 // do not force device change on duplicated output because if device is 0, it will
179 // also force a device 0 for the two outputs it is duplicated to which may override
180 // a valid device selection on those outputs.
181 setOutputDevice(mOutputs.keyAt(i),
182 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
183 !mOutputs.valueAt(i)->isDuplicated(),
187 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
188 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
189 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
190 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
191 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
192 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
196 } // end if is output device
198 // handle input devices
199 if (audio_is_input_device(device)) {
200 SortedVector <audio_io_handle_t> inputs;
205 // handle input device connection
206 case AudioSystem::DEVICE_STATE_AVAILABLE: {
207 if (mAvailableInputDevices & device) {
208 ALOGW("setDeviceConnectionState() device already connected: %d", device);
209 return INVALID_OPERATION;
212 if (mHasUsb && audio_is_usb_in_device(device)) {
213 // handle USB device connection
214 paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
217 if (checkInputsForDevice(device, state, inputs, paramStr) != NO_ERROR) {
218 return INVALID_OPERATION;
220 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
224 // handle input device disconnection
225 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
226 if (!(mAvailableInputDevices & device)) {
227 ALOGW("setDeviceConnectionState() device not connected: %d", device);
228 return INVALID_OPERATION;
230 checkInputsForDevice(device, state, inputs, paramStr);
231 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
235 ALOGE("setDeviceConnectionState() invalid state: %x", state);
242 } // end if is input device
244 ALOGW("setDeviceConnectionState() invalid device: %x", device);
248 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
249 const char *device_address)
251 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
252 String8 address = String8(device_address);
253 if (audio_is_output_device(device)) {
254 if (device & mAvailableOutputDevices) {
255 if (audio_is_a2dp_device(device) &&
256 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
259 if (audio_is_bluetooth_sco_device(device) &&
260 address != "" && mScoDeviceAddress != address) {
263 if (audio_is_usb_out_device(device) &&
264 (!mHasUsb || (address != "" && mUsbOutCardAndDevice != address))) {
265 ALOGE("getDeviceConnectionState() invalid device: %x", device);
268 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
271 state = AudioSystem::DEVICE_STATE_AVAILABLE;
273 } else if (audio_is_input_device(device)) {
274 if (device & mAvailableInputDevices) {
275 state = AudioSystem::DEVICE_STATE_AVAILABLE;
282 void AudioPolicyManagerBase::setPhoneState(int state)
284 ALOGV("setPhoneState() state %d", state);
285 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
286 if (state < 0 || state >= AudioSystem::NUM_MODES) {
287 ALOGW("setPhoneState() invalid state %d", state);
291 if (state == mPhoneState ) {
292 ALOGW("setPhoneState() setting same state %d", state);
296 // if leaving call state, handle special case of active streams
297 // pertaining to sonification strategy see handleIncallSonification()
299 ALOGV("setPhoneState() in call state management: new state is %d", state);
300 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
301 handleIncallSonification(stream, false, true);
305 // store previous phone state for management of sonification strategy below
306 int oldState = mPhoneState;
310 // are we entering or starting a call
311 if (!isStateInCall(oldState) && isStateInCall(state)) {
312 ALOGV(" Entering call in setPhoneState()");
313 // force routing command to audio hardware when starting a call
314 // even if no device change is needed
316 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
317 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
318 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
320 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
321 ALOGV(" Exiting call in setPhoneState()");
322 // force routing command to audio hardware when exiting a call
323 // even if no device change is needed
325 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
326 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
327 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
329 } else if (isStateInCall(state) && (state != oldState)) {
330 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
331 // force routing command to audio hardware when switching between telephony and VoIP
332 // even if no device change is needed
336 // check for device and output changes triggered by new phone state
337 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
339 checkOutputForAllStrategies();
340 updateDevicesAndOutputs();
342 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
344 // force routing command to audio hardware when ending call
345 // even if no device change is needed
346 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
347 newDevice = hwOutputDesc->device();
351 if (isStateInCall(state)) {
352 nsecs_t sysTime = systemTime();
353 for (size_t i = 0; i < mOutputs.size(); i++) {
354 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
355 // mute media and sonification strategies and delay device switch by the largest
356 // latency of any output where either strategy is active.
357 // This avoid sending the ring tone or music tail into the earpiece or headset.
358 if ((desc->isStrategyActive(STRATEGY_MEDIA,
359 SONIFICATION_HEADSET_MUSIC_DELAY,
361 desc->isStrategyActive(STRATEGY_SONIFICATION,
362 SONIFICATION_HEADSET_MUSIC_DELAY,
364 (delayMs < (int)desc->mLatency*2)) {
365 delayMs = desc->mLatency*2;
367 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
368 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
369 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
370 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
371 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
372 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
376 // change routing is necessary
377 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
379 // if entering in call state, handle special case of active streams
380 // pertaining to sonification strategy see handleIncallSonification()
381 if (isStateInCall(state)) {
382 ALOGV("setPhoneState() in call state management: new state is %d", state);
383 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
384 handleIncallSonification(stream, true, true);
388 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
389 if (state == AudioSystem::MODE_RINGTONE &&
390 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
391 mLimitRingtoneVolume = true;
393 mLimitRingtoneVolume = false;
397 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
399 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
401 bool forceVolumeReeval = false;
403 case AudioSystem::FOR_COMMUNICATION:
404 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
405 config != AudioSystem::FORCE_NONE) {
406 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
409 forceVolumeReeval = true;
410 mForceUse[usage] = config;
412 case AudioSystem::FOR_MEDIA:
413 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
414 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
415 config != AudioSystem::FORCE_ANALOG_DOCK &&
416 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
417 config != AudioSystem::FORCE_NO_BT_A2DP) {
418 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
421 mForceUse[usage] = config;
423 case AudioSystem::FOR_RECORD:
424 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
425 config != AudioSystem::FORCE_NONE) {
426 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
429 mForceUse[usage] = config;
431 case AudioSystem::FOR_DOCK:
432 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
433 config != AudioSystem::FORCE_BT_DESK_DOCK &&
434 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
435 config != AudioSystem::FORCE_ANALOG_DOCK &&
436 config != AudioSystem::FORCE_DIGITAL_DOCK) {
437 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
439 forceVolumeReeval = true;
440 mForceUse[usage] = config;
442 case AudioSystem::FOR_SYSTEM:
443 if (config != AudioSystem::FORCE_NONE &&
444 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
445 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
447 forceVolumeReeval = true;
448 mForceUse[usage] = config;
451 ALOGW("setForceUse() invalid usage %d", usage);
455 // check for device and output changes triggered by new force usage
457 checkOutputForAllStrategies();
458 updateDevicesAndOutputs();
459 for (size_t i = 0; i < mOutputs.size(); i++) {
460 audio_io_handle_t output = mOutputs.keyAt(i);
461 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
462 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
463 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
464 applyStreamVolumes(output, newDevice, 0, true);
468 audio_io_handle_t activeInput = getActiveInput();
469 if (activeInput != 0) {
470 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
471 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
472 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
473 ALOGV("setForceUse() changing device from %x to %x for input %d",
474 inputDesc->mDevice, newDevice, activeInput);
475 inputDesc->mDevice = newDevice;
476 AudioParameter param = AudioParameter();
477 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
478 mpClientInterface->setParameters(activeInput, param.toString());
484 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
486 return mForceUse[usage];
489 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
491 ALOGV("setSystemProperty() property %s, value %s", property, value);
494 // Find a direct output profile compatible with the parameters passed, even if the input flags do
495 // not explicitly request a direct output
496 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
497 audio_devices_t device,
498 uint32_t samplingRate,
499 audio_format_t format,
500 audio_channel_mask_t channelMask,
501 audio_output_flags_t flags)
503 for (size_t i = 0; i < mHwModules.size(); i++) {
504 if (mHwModules[i]->mHandle == 0) {
507 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
508 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
509 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
510 if (profile->isCompatibleProfile(device, samplingRate, format,
512 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
513 if (mAvailableOutputDevices & profile->mSupportedDevices) {
514 return mHwModules[i]->mOutputProfiles[j];
518 if (profile->isCompatibleProfile(device, samplingRate, format,
520 AUDIO_OUTPUT_FLAG_DIRECT)) {
521 if (mAvailableOutputDevices & profile->mSupportedDevices) {
522 return mHwModules[i]->mOutputProfiles[j];
531 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
532 uint32_t samplingRate,
533 audio_format_t format,
534 audio_channel_mask_t channelMask,
535 AudioSystem::output_flags flags,
536 const audio_offload_info_t *offloadInfo)
538 audio_io_handle_t output = 0;
539 uint32_t latency = 0;
540 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
541 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
542 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
543 device, stream, samplingRate, format, channelMask, flags);
545 #ifdef AUDIO_POLICY_TEST
546 if (mCurOutput != 0) {
547 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
548 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
550 if (mTestOutputs[mCurOutput] == 0) {
551 ALOGV("getOutput() opening test output");
552 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
553 outputDesc->mDevice = mTestDevice;
554 outputDesc->mSamplingRate = mTestSamplingRate;
555 outputDesc->mFormat = mTestFormat;
556 outputDesc->mChannelMask = mTestChannels;
557 outputDesc->mLatency = mTestLatencyMs;
558 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
559 outputDesc->mRefCount[stream] = 0;
560 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
561 &outputDesc->mSamplingRate,
562 &outputDesc->mFormat,
563 &outputDesc->mChannelMask,
564 &outputDesc->mLatency,
567 if (mTestOutputs[mCurOutput]) {
568 AudioParameter outputCmd = AudioParameter();
569 outputCmd.addInt(String8("set_id"),mCurOutput);
570 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
571 addOutput(mTestOutputs[mCurOutput], outputDesc);
574 return mTestOutputs[mCurOutput];
576 #endif //AUDIO_POLICY_TEST
578 // open a direct output if required by specified parameters
579 //force direct flag if offload flag is set: offloading implies a direct output stream
580 // and all common behaviors are driven by checking only the direct flag
581 // this should normally be set appropriately in the policy configuration file
582 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
583 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
586 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
587 // creating an offloaded track and tearing it down immediately after start when audioflinger
588 // detects there is an active non offloadable effect.
589 // FIXME: We should check the audio session here but we do not have it in this context.
590 // This may prevent offloading in rare situations where effects are left active by apps
591 // in the background.
592 IOProfile *profile = NULL;
593 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
594 !isNonOffloadableEffectEnabled()) {
595 profile = getProfileForDirectOutput(device,
599 (audio_output_flags_t)flags);
602 if (profile != NULL) {
603 AudioOutputDescriptor *outputDesc = NULL;
605 for (size_t i = 0; i < mOutputs.size(); i++) {
606 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
607 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
609 // reuse direct output if currently open and configured with same parameters
610 if ((samplingRate == outputDesc->mSamplingRate) &&
611 (format == outputDesc->mFormat) &&
612 (channelMask == outputDesc->mChannelMask)) {
613 outputDesc->mDirectOpenCount++;
614 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
615 return mOutputs.keyAt(i);
619 // close direct output if currently open and configured with different parameters
620 if (outputDesc != NULL) {
621 closeOutput(outputDesc->mId);
623 outputDesc = new AudioOutputDescriptor(profile);
624 outputDesc->mDevice = device;
625 outputDesc->mSamplingRate = samplingRate;
626 outputDesc->mFormat = format;
627 outputDesc->mChannelMask = channelMask;
628 outputDesc->mLatency = 0;
629 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
630 outputDesc->mRefCount[stream] = 0;
631 outputDesc->mStopTime[stream] = 0;
632 outputDesc->mDirectOpenCount = 1;
633 output = mpClientInterface->openOutput(profile->mModule->mHandle,
634 &outputDesc->mDevice,
635 &outputDesc->mSamplingRate,
636 &outputDesc->mFormat,
637 &outputDesc->mChannelMask,
638 &outputDesc->mLatency,
642 // only accept an output with the requested parameters
644 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
645 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
646 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
647 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
648 "format %d %d, channelMask %04x %04x", output, samplingRate,
649 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
650 outputDesc->mChannelMask);
652 mpClientInterface->closeOutput(output);
657 audio_io_handle_t srcOutput = getOutputForEffect();
658 addOutput(output, outputDesc);
659 audio_io_handle_t dstOutput = getOutputForEffect();
660 if (dstOutput == output) {
661 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
663 mPreviousOutputs = mOutputs;
664 ALOGV("getOutput() returns new direct output %d", output);
668 // ignoring channel mask due to downmix capability in mixer
670 // open a non direct output
672 // for non direct outputs, only PCM is supported
673 if (audio_is_linear_pcm(format)) {
674 // get which output is suitable for the specified stream. The actual
675 // routing change will happen when startOutput() will be called
676 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
678 output = selectOutput(outputs, flags);
680 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
681 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
683 ALOGV("getOutput() returns output %d", output);
688 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
689 AudioSystem::output_flags flags)
691 // select one output among several that provide a path to a particular device or set of
692 // devices (the list was previously build by getOutputsForDevice()).
693 // The priority is as follows:
694 // 1: the output with the highest number of requested policy flags
695 // 2: the primary output
696 // 3: the first output in the list
698 if (outputs.size() == 0) {
701 if (outputs.size() == 1) {
705 int maxCommonFlags = 0;
706 audio_io_handle_t outputFlags = 0;
707 audio_io_handle_t outputPrimary = 0;
709 for (size_t i = 0; i < outputs.size(); i++) {
710 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
711 if (!outputDesc->isDuplicated()) {
712 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
713 if (commonFlags > maxCommonFlags) {
714 outputFlags = outputs[i];
715 maxCommonFlags = commonFlags;
716 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
718 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
719 outputPrimary = outputs[i];
724 if (outputFlags != 0) {
727 if (outputPrimary != 0) {
728 return outputPrimary;
734 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
735 AudioSystem::stream_type stream,
738 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
739 ssize_t index = mOutputs.indexOfKey(output);
741 ALOGW("startOutput() unknown output %d", output);
745 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
747 // increment usage count for this stream on the requested output:
748 // NOTE that the usage count is the same for duplicated output and hardware output which is
749 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
750 outputDesc->changeRefCount(stream, 1);
752 if (outputDesc->mRefCount[stream] == 1) {
753 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
754 routing_strategy strategy = getStrategy(stream);
755 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
756 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
759 for (size_t i = 0; i < mOutputs.size(); i++) {
760 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
761 if (desc != outputDesc) {
762 // force a device change if any other output is managed by the same hw
763 // module and has a current device selection that differs from selected device.
764 // In this case, the audio HAL must receive the new device selection so that it can
765 // change the device currently selected by the other active output.
766 if (outputDesc->sharesHwModuleWith(desc) &&
767 desc->device() != newDevice) {
770 // wait for audio on other active outputs to be presented when starting
771 // a notification so that audio focus effect can propagate.
772 uint32_t latency = desc->latency();
773 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
778 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
780 // handle special case for sonification while in call
782 handleIncallSonification(stream, true, false);
785 // apply volume rules for current stream and device if necessary
786 checkAndSetVolume(stream,
787 mStreams[stream].getVolumeIndex(newDevice),
791 // update the outputs if starting an output with a stream that can affect notification
793 handleNotificationRoutingForStream(stream);
794 if (waitMs > muteWaitMs) {
795 usleep((waitMs - muteWaitMs) * 2 * 1000);
802 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
803 AudioSystem::stream_type stream,
806 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
807 ssize_t index = mOutputs.indexOfKey(output);
809 ALOGW("stopOutput() unknown output %d", output);
813 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
815 // handle special case for sonification while in call
817 handleIncallSonification(stream, false, false);
820 if (outputDesc->mRefCount[stream] > 0) {
821 // decrement usage count of this stream on the output
822 outputDesc->changeRefCount(stream, -1);
823 // store time at which the stream was stopped - see isStreamActive()
824 if (outputDesc->mRefCount[stream] == 0) {
825 outputDesc->mStopTime[stream] = systemTime();
826 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
827 // delay the device switch by twice the latency because stopOutput() is executed when
828 // the track stop() command is received and at that time the audio track buffer can
829 // still contain data that needs to be drained. The latency only covers the audio HAL
830 // and kernel buffers. Also the latency does not always include additional delay in the
831 // audio path (audio DSP, CODEC ...)
832 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
834 // force restoring the device selection on other active outputs if it differs from the
835 // one being selected for this output
836 for (size_t i = 0; i < mOutputs.size(); i++) {
837 audio_io_handle_t curOutput = mOutputs.keyAt(i);
838 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
839 if (curOutput != output &&
841 outputDesc->sharesHwModuleWith(desc) &&
842 (newDevice != desc->device())) {
843 setOutputDevice(curOutput,
844 getNewDevice(curOutput, false /*fromCache*/),
846 outputDesc->mLatency*2);
849 // update the outputs if stopping one with a stream that can affect notification routing
850 handleNotificationRoutingForStream(stream);
854 ALOGW("stopOutput() refcount is already 0 for output %d", output);
855 return INVALID_OPERATION;
859 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
861 ALOGV("releaseOutput() %d", output);
862 ssize_t index = mOutputs.indexOfKey(output);
864 ALOGW("releaseOutput() releasing unknown output %d", output);
868 #ifdef AUDIO_POLICY_TEST
869 int testIndex = testOutputIndex(output);
870 if (testIndex != 0) {
871 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
872 if (outputDesc->isActive()) {
873 mpClientInterface->closeOutput(output);
874 delete mOutputs.valueAt(index);
875 mOutputs.removeItem(output);
876 mTestOutputs[testIndex] = 0;
880 #endif //AUDIO_POLICY_TEST
882 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
883 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
884 if (desc->mDirectOpenCount <= 0) {
885 ALOGW("releaseOutput() invalid open count %d for output %d",
886 desc->mDirectOpenCount, output);
889 if (--desc->mDirectOpenCount == 0) {
891 // If effects where present on the output, audioflinger moved them to the primary
892 // output by default: move them back to the appropriate output.
893 audio_io_handle_t dstOutput = getOutputForEffect();
894 if (dstOutput != mPrimaryOutput) {
895 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
902 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
903 uint32_t samplingRate,
904 audio_format_t format,
905 audio_channel_mask_t channelMask,
906 AudioSystem::audio_in_acoustics acoustics)
908 audio_io_handle_t input = 0;
909 audio_devices_t device = getDeviceForInputSource(inputSource);
911 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
912 inputSource, samplingRate, format, channelMask, acoustics);
914 if (device == AUDIO_DEVICE_NONE) {
915 ALOGW("getInput() could not find device for inputSource %d", inputSource);
919 // adapt channel selection to input source
920 switch(inputSource) {
921 case AUDIO_SOURCE_VOICE_UPLINK:
922 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
924 case AUDIO_SOURCE_VOICE_DOWNLINK:
925 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
927 case AUDIO_SOURCE_VOICE_CALL:
928 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
934 IOProfile *profile = getInputProfile(device,
938 if (profile == NULL) {
939 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %d, format %d, "
941 device, samplingRate, format, channelMask);
945 if (profile->mModule->mHandle == 0) {
946 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
950 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
952 inputDesc->mInputSource = inputSource;
953 inputDesc->mDevice = device;
954 inputDesc->mSamplingRate = samplingRate;
955 inputDesc->mFormat = format;
956 inputDesc->mChannelMask = channelMask;
957 inputDesc->mRefCount = 0;
959 input = mpClientInterface->openInput(profile->mModule->mHandle,
961 &inputDesc->mSamplingRate,
963 &inputDesc->mChannelMask);
965 // only accept input with the exact requested set of parameters
967 (samplingRate != inputDesc->mSamplingRate) ||
968 (format != inputDesc->mFormat) ||
969 (channelMask != inputDesc->mChannelMask)) {
970 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask 0x%X",
971 samplingRate, format, channelMask);
973 mpClientInterface->closeInput(input);
978 addInput(input, inputDesc);
983 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
985 ALOGV("startInput() input %d", input);
986 ssize_t index = mInputs.indexOfKey(input);
988 ALOGW("startInput() unknown input %d", input);
991 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
993 #ifdef AUDIO_POLICY_TEST
995 #endif //AUDIO_POLICY_TEST
997 // refuse 2 active AudioRecord clients at the same time except if the active input
998 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
999 audio_io_handle_t activeInput = getActiveInput();
1000 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1001 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1002 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1003 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1004 stopInput(activeInput);
1005 releaseInput(activeInput);
1007 ALOGW("startInput() input %d failed: other input already started", input);
1008 return INVALID_OPERATION;
1013 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1014 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1015 inputDesc->mDevice = newDevice;
1018 // automatically enable the remote submix output when input is started
1019 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1020 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1021 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1024 AudioParameter param = AudioParameter();
1025 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1027 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1028 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1030 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1031 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1033 mpClientInterface->setParameters(input, param.toString());
1035 inputDesc->mRefCount = 1;
1039 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
1041 ALOGV("stopInput() input %d", input);
1042 ssize_t index = mInputs.indexOfKey(input);
1044 ALOGW("stopInput() unknown input %d", input);
1047 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1049 if (inputDesc->mRefCount == 0) {
1050 ALOGW("stopInput() input %d already stopped", input);
1051 return INVALID_OPERATION;
1053 // automatically disable the remote submix output when input is stopped
1054 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1055 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1056 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1059 AudioParameter param = AudioParameter();
1060 param.addInt(String8(AudioParameter::keyRouting), 0);
1061 mpClientInterface->setParameters(input, param.toString());
1062 inputDesc->mRefCount = 0;
1067 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1069 ALOGV("releaseInput() %d", input);
1070 ssize_t index = mInputs.indexOfKey(input);
1072 ALOGW("releaseInput() releasing unknown input %d", input);
1075 mpClientInterface->closeInput(input);
1076 delete mInputs.valueAt(index);
1077 mInputs.removeItem(input);
1079 ALOGV("releaseInput() exit");
1082 void AudioPolicyManagerBase::closeAllInputs() {
1083 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1084 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1089 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1093 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1094 if (indexMin < 0 || indexMin >= indexMax) {
1095 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1098 mStreams[stream].mIndexMin = indexMin;
1099 mStreams[stream].mIndexMax = indexMax;
1102 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1104 audio_devices_t device)
1107 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1110 if (!audio_is_output_device(device)) {
1114 // Force max volume if stream cannot be muted
1115 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1117 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1118 stream, device, index);
1120 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1121 // clear all device specific values
1122 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1123 mStreams[stream].mIndexCur.clear();
1125 mStreams[stream].mIndexCur.add(device, index);
1127 // compute and apply stream volume on all outputs according to connected device
1128 status_t status = NO_ERROR;
1129 for (size_t i = 0; i < mOutputs.size(); i++) {
1130 audio_devices_t curDevice =
1131 getDeviceForVolume(mOutputs.valueAt(i)->device());
1132 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1133 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1134 if (volStatus != NO_ERROR) {
1142 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1144 audio_devices_t device)
1146 if (index == NULL) {
1149 if (!audio_is_output_device(device)) {
1152 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1153 // the strategy the stream belongs to.
1154 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1155 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1157 device = getDeviceForVolume(device);
1159 *index = mStreams[stream].getVolumeIndex(device);
1160 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1164 audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
1165 const SortedVector<audio_io_handle_t>& outputs)
1167 // select one output among several suitable for global effects.
1168 // The priority is as follows:
1169 // 1: An offloaded output. If the effect ends up not being offloadable,
1170 // AudioFlinger will invalidate the track and the offloaded output
1171 // will be closed causing the effect to be moved to a PCM output.
1172 // 2: A deep buffer output
1173 // 3: the first output in the list
1175 if (outputs.size() == 0) {
1179 audio_io_handle_t outputOffloaded = 0;
1180 audio_io_handle_t outputDeepBuffer = 0;
1182 for (size_t i = 0; i < outputs.size(); i++) {
1183 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1184 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1185 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1186 outputOffloaded = outputs[i];
1188 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1189 outputDeepBuffer = outputs[i];
1193 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1194 outputOffloaded, outputDeepBuffer);
1195 if (outputOffloaded != 0) {
1196 return outputOffloaded;
1198 if (outputDeepBuffer != 0) {
1199 return outputDeepBuffer;
1205 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1207 // apply simple rule where global effects are attached to the same output as MUSIC streams
1209 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1210 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1211 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1213 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1214 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1215 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1220 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1221 audio_io_handle_t io,
1226 ssize_t index = mOutputs.indexOfKey(io);
1228 index = mInputs.indexOfKey(io);
1230 ALOGW("registerEffect() unknown io %d", io);
1231 return INVALID_OPERATION;
1235 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1236 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1237 desc->name, desc->memoryUsage);
1238 return INVALID_OPERATION;
1240 mTotalEffectsMemory += desc->memoryUsage;
1241 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1242 desc->name, io, strategy, session, id);
1243 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1245 EffectDescriptor *pDesc = new EffectDescriptor();
1246 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1248 pDesc->mStrategy = (routing_strategy)strategy;
1249 pDesc->mSession = session;
1250 pDesc->mEnabled = false;
1252 mEffects.add(id, pDesc);
1257 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1259 ssize_t index = mEffects.indexOfKey(id);
1261 ALOGW("unregisterEffect() unknown effect ID %d", id);
1262 return INVALID_OPERATION;
1265 EffectDescriptor *pDesc = mEffects.valueAt(index);
1267 setEffectEnabled(pDesc, false);
1269 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1270 ALOGW("unregisterEffect() memory %d too big for total %d",
1271 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1272 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1274 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1275 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1276 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1278 mEffects.removeItem(id);
1284 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1286 ssize_t index = mEffects.indexOfKey(id);
1288 ALOGW("unregisterEffect() unknown effect ID %d", id);
1289 return INVALID_OPERATION;
1292 return setEffectEnabled(mEffects.valueAt(index), enabled);
1295 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1297 if (enabled == pDesc->mEnabled) {
1298 ALOGV("setEffectEnabled(%s) effect already %s",
1299 enabled?"true":"false", enabled?"enabled":"disabled");
1300 return INVALID_OPERATION;
1304 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1305 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1306 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1307 return INVALID_OPERATION;
1309 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1310 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1312 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1313 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1314 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1315 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1317 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1318 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1320 pDesc->mEnabled = enabled;
1324 bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled()
1326 for (size_t i = 0; i < mEffects.size(); i++) {
1327 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1328 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1329 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1330 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1331 pDesc->mDesc.name, pDesc->mSession);
1338 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1340 nsecs_t sysTime = systemTime();
1341 for (size_t i = 0; i < mOutputs.size(); i++) {
1342 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1343 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1350 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1352 nsecs_t sysTime = systemTime();
1353 for (size_t i = 0; i < mOutputs.size(); i++) {
1354 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1355 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1356 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1363 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1365 for (size_t i = 0; i < mInputs.size(); i++) {
1366 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1367 if ((inputDescriptor->mInputSource == (int)source ||
1368 (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
1369 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1370 && (inputDescriptor->mRefCount > 0)) {
1378 status_t AudioPolicyManagerBase::dump(int fd)
1380 const size_t SIZE = 256;
1384 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1385 result.append(buffer);
1387 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1388 result.append(buffer);
1389 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1390 result.append(buffer);
1391 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1392 result.append(buffer);
1393 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbOutCardAndDevice.string());
1394 result.append(buffer);
1395 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1396 result.append(buffer);
1397 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1398 result.append(buffer);
1399 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1400 result.append(buffer);
1401 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1402 result.append(buffer);
1403 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1404 result.append(buffer);
1405 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1406 result.append(buffer);
1407 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1408 result.append(buffer);
1409 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1410 result.append(buffer);
1411 write(fd, result.string(), result.size());
1414 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1415 write(fd, buffer, strlen(buffer));
1416 for (size_t i = 0; i < mHwModules.size(); i++) {
1417 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
1418 write(fd, buffer, strlen(buffer));
1419 mHwModules[i]->dump(fd);
1422 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1423 write(fd, buffer, strlen(buffer));
1424 for (size_t i = 0; i < mOutputs.size(); i++) {
1425 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1426 write(fd, buffer, strlen(buffer));
1427 mOutputs.valueAt(i)->dump(fd);
1430 snprintf(buffer, SIZE, "\nInputs dump:\n");
1431 write(fd, buffer, strlen(buffer));
1432 for (size_t i = 0; i < mInputs.size(); i++) {
1433 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1434 write(fd, buffer, strlen(buffer));
1435 mInputs.valueAt(i)->dump(fd);
1438 snprintf(buffer, SIZE, "\nStreams dump:\n");
1439 write(fd, buffer, strlen(buffer));
1440 snprintf(buffer, SIZE,
1441 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1442 write(fd, buffer, strlen(buffer));
1443 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1444 snprintf(buffer, SIZE, " %02zu ", i);
1445 write(fd, buffer, strlen(buffer));
1446 mStreams[i].dump(fd);
1449 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1450 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1451 write(fd, buffer, strlen(buffer));
1453 snprintf(buffer, SIZE, "Registered effects:\n");
1454 write(fd, buffer, strlen(buffer));
1455 for (size_t i = 0; i < mEffects.size(); i++) {
1456 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1457 write(fd, buffer, strlen(buffer));
1458 mEffects.valueAt(i)->dump(fd);
1465 // This function checks for the parameters which can be offloaded.
1466 // This can be enhanced depending on the capability of the DSP and policy
1468 bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1470 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1471 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
1472 offloadInfo.sample_rate, offloadInfo.channel_mask,
1474 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1475 offloadInfo.has_video);
1477 // Check if offload has been disabled
1478 char propValue[PROPERTY_VALUE_MAX];
1479 if (property_get("audio.offload.disable", propValue, "0")) {
1480 if (atoi(propValue) != 0) {
1481 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1486 // Check if stream type is music, then only allow offload as of now.
1487 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1489 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1493 //TODO: enable audio offloading with video when ready
1494 if (offloadInfo.has_video)
1496 ALOGV("isOffloadSupported: has_video == true, returning false");
1500 //If duration is less than minimum value defined in property, return false
1501 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1502 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1503 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1506 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1507 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1511 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1512 // creating an offloaded track and tearing it down immediately after start when audioflinger
1513 // detects there is an active non offloadable effect.
1514 // FIXME: We should check the audio session here but we do not have it in this context.
1515 // This may prevent offloading in rare situations where effects are left active by apps
1516 // in the background.
1517 if (isNonOffloadableEffectEnabled()) {
1521 // See if there is a profile to support this.
1522 // AUDIO_DEVICE_NONE
1523 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1524 offloadInfo.sample_rate,
1526 offloadInfo.channel_mask,
1527 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1528 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1529 return (profile != NULL);
1532 // ----------------------------------------------------------------------------
1533 // AudioPolicyManagerBase
1534 // ----------------------------------------------------------------------------
1536 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1538 #ifdef AUDIO_POLICY_TEST
1540 #endif //AUDIO_POLICY_TEST
1541 mPrimaryOutput((audio_io_handle_t)0),
1542 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1543 mPhoneState(AudioSystem::MODE_NORMAL),
1544 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1545 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1546 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),
1547 mSpeakerDrcEnabled(false)
1549 mpClientInterface = clientInterface;
1551 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1552 mForceUse[i] = AudioSystem::FORCE_NONE;
1555 mA2dpDeviceAddress = String8("");
1556 mScoDeviceAddress = String8("");
1557 mUsbOutCardAndDevice = String8("");
1559 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1560 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1561 ALOGE("could not load audio policy configuration file, setting defaults");
1562 defaultAudioPolicyConfig();
1566 // must be done after reading the policy
1567 initializeVolumeCurves();
1569 // open all output streams needed to access attached devices
1570 for (size_t i = 0; i < mHwModules.size(); i++) {
1571 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1572 if (mHwModules[i]->mHandle == 0) {
1573 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1576 // open all output streams needed to access attached devices
1577 // except for direct output streams that are only opened when they are actually
1578 // required by an app.
1579 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1581 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1583 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1584 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1585 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1586 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1587 outProfile->mSupportedDevices);
1588 audio_io_handle_t output = mpClientInterface->openOutput(
1589 outProfile->mModule->mHandle,
1590 &outputDesc->mDevice,
1591 &outputDesc->mSamplingRate,
1592 &outputDesc->mFormat,
1593 &outputDesc->mChannelMask,
1594 &outputDesc->mLatency,
1595 outputDesc->mFlags);
1599 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1600 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1601 if (mPrimaryOutput == 0 &&
1602 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1603 mPrimaryOutput = output;
1605 addOutput(output, outputDesc);
1606 setOutputDevice(output,
1607 (audio_devices_t)(mDefaultOutputDevice &
1608 outProfile->mSupportedDevices),
1615 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1616 "Not output found for attached devices %08x",
1617 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1619 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1621 updateDevicesAndOutputs();
1623 #ifdef AUDIO_POLICY_TEST
1624 if (mPrimaryOutput != 0) {
1625 AudioParameter outputCmd = AudioParameter();
1626 outputCmd.addInt(String8("set_id"), 0);
1627 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1629 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1630 mTestSamplingRate = 44100;
1631 mTestFormat = AudioSystem::PCM_16_BIT;
1632 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1635 mDirectOutput = false;
1636 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1637 mTestOutputs[i] = 0;
1640 const size_t SIZE = 256;
1642 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1643 run(buffer, ANDROID_PRIORITY_AUDIO);
1645 #endif //AUDIO_POLICY_TEST
1648 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1650 #ifdef AUDIO_POLICY_TEST
1652 #endif //AUDIO_POLICY_TEST
1653 for (size_t i = 0; i < mOutputs.size(); i++) {
1654 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1655 delete mOutputs.valueAt(i);
1657 for (size_t i = 0; i < mInputs.size(); i++) {
1658 mpClientInterface->closeInput(mInputs.keyAt(i));
1659 delete mInputs.valueAt(i);
1661 for (size_t i = 0; i < mHwModules.size(); i++) {
1662 delete mHwModules[i];
1666 status_t AudioPolicyManagerBase::initCheck()
1668 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1671 #ifdef AUDIO_POLICY_TEST
1672 bool AudioPolicyManagerBase::threadLoop()
1674 ALOGV("entering threadLoop()");
1675 while (!exitPending())
1681 Mutex::Autolock _l(mLock);
1682 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1684 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1685 AudioParameter param = AudioParameter(command);
1687 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1689 ALOGV("Test command %s received", command.string());
1691 if (param.get(String8("target"), target) != NO_ERROR) {
1694 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1695 param.remove(String8("test_cmd_policy_output"));
1696 mCurOutput = valueInt;
1698 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1699 param.remove(String8("test_cmd_policy_direct"));
1700 if (value == "false") {
1701 mDirectOutput = false;
1702 } else if (value == "true") {
1703 mDirectOutput = true;
1706 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1707 param.remove(String8("test_cmd_policy_input"));
1708 mTestInput = valueInt;
1711 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1712 param.remove(String8("test_cmd_policy_format"));
1713 int format = AudioSystem::INVALID_FORMAT;
1714 if (value == "PCM 16 bits") {
1715 format = AudioSystem::PCM_16_BIT;
1716 } else if (value == "PCM 8 bits") {
1717 format = AudioSystem::PCM_8_BIT;
1718 } else if (value == "Compressed MP3") {
1719 format = AudioSystem::MP3;
1721 if (format != AudioSystem::INVALID_FORMAT) {
1722 if (target == "Manager") {
1723 mTestFormat = format;
1724 } else if (mTestOutputs[mCurOutput] != 0) {
1725 AudioParameter outputParam = AudioParameter();
1726 outputParam.addInt(String8("format"), format);
1727 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1731 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1732 param.remove(String8("test_cmd_policy_channels"));
1735 if (value == "Channels Stereo") {
1736 channels = AudioSystem::CHANNEL_OUT_STEREO;
1737 } else if (value == "Channels Mono") {
1738 channels = AudioSystem::CHANNEL_OUT_MONO;
1740 if (channels != 0) {
1741 if (target == "Manager") {
1742 mTestChannels = channels;
1743 } else if (mTestOutputs[mCurOutput] != 0) {
1744 AudioParameter outputParam = AudioParameter();
1745 outputParam.addInt(String8("channels"), channels);
1746 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1750 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1751 param.remove(String8("test_cmd_policy_sampleRate"));
1752 if (valueInt >= 0 && valueInt <= 96000) {
1753 int samplingRate = valueInt;
1754 if (target == "Manager") {
1755 mTestSamplingRate = samplingRate;
1756 } else if (mTestOutputs[mCurOutput] != 0) {
1757 AudioParameter outputParam = AudioParameter();
1758 outputParam.addInt(String8("sampling_rate"), samplingRate);
1759 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1764 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1765 param.remove(String8("test_cmd_policy_reopen"));
1767 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1768 mpClientInterface->closeOutput(mPrimaryOutput);
1770 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1772 delete mOutputs.valueFor(mPrimaryOutput);
1773 mOutputs.removeItem(mPrimaryOutput);
1775 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1776 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1777 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1778 &outputDesc->mDevice,
1779 &outputDesc->mSamplingRate,
1780 &outputDesc->mFormat,
1781 &outputDesc->mChannelMask,
1782 &outputDesc->mLatency,
1783 outputDesc->mFlags);
1784 if (mPrimaryOutput == 0) {
1785 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1786 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1788 AudioParameter outputCmd = AudioParameter();
1789 outputCmd.addInt(String8("set_id"), 0);
1790 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1791 addOutput(mPrimaryOutput, outputDesc);
1796 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1802 void AudioPolicyManagerBase::exit()
1805 AutoMutex _l(mLock);
1807 mWaitWorkCV.signal();
1809 requestExitAndWait();
1812 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1814 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1815 if (output == mTestOutputs[i]) return i;
1819 #endif //AUDIO_POLICY_TEST
1823 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1825 outputDesc->mId = id;
1826 mOutputs.add(id, outputDesc);
1829 void AudioPolicyManagerBase::addInput(audio_io_handle_t id, AudioInputDescriptor *inputDesc)
1831 inputDesc->mId = id;
1832 mInputs.add(id, inputDesc);
1835 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1836 AudioSystem::device_connection_state state,
1837 SortedVector<audio_io_handle_t>& outputs,
1838 const String8 paramStr)
1840 AudioOutputDescriptor *desc;
1842 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1843 // first list already open outputs that can be routed to this device
1844 for (size_t i = 0; i < mOutputs.size(); i++) {
1845 desc = mOutputs.valueAt(i);
1846 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1847 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1848 outputs.add(mOutputs.keyAt(i));
1851 // then look for output profiles that can be routed to this device
1852 SortedVector<IOProfile *> profiles;
1853 for (size_t i = 0; i < mHwModules.size(); i++)
1855 if (mHwModules[i]->mHandle == 0) {
1858 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1860 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1861 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
1862 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1867 if (profiles.isEmpty() && outputs.isEmpty()) {
1868 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1872 // open outputs for matching profiles if needed. Direct outputs are also opened to
1873 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1874 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1875 IOProfile *profile = profiles[profile_index];
1877 // nothing to do if one output is already opened for this profile
1879 for (j = 0; j < mOutputs.size(); j++) {
1880 desc = mOutputs.valueAt(j);
1881 if (!desc->isDuplicated() && desc->mProfile == profile) {
1885 if (j != mOutputs.size()) {
1889 ALOGV("opening output for device %08x with params %s", device, paramStr.string());
1890 desc = new AudioOutputDescriptor(profile);
1891 desc->mDevice = device;
1892 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1893 offloadInfo.sample_rate = desc->mSamplingRate;
1894 offloadInfo.format = desc->mFormat;
1895 offloadInfo.channel_mask = desc->mChannelMask;
1897 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1899 &desc->mSamplingRate,
1901 &desc->mChannelMask,
1906 if (!paramStr.isEmpty()) {
1907 // Here is where the out_set_parameters() for card & device gets called
1908 mpClientInterface->setParameters(output, paramStr);
1911 // Here is where we step through and resolve any "dynamic" fields
1914 if (profile->mSamplingRates[0] == 0) {
1915 reply = mpClientInterface->getParameters(output,
1916 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1917 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1919 value = strpbrk((char *)reply.string(), "=");
1920 if (value != NULL) {
1921 loadSamplingRates(value + 1, profile);
1924 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
1925 reply = mpClientInterface->getParameters(output,
1926 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1927 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1929 value = strpbrk((char *)reply.string(), "=");
1930 if (value != NULL) {
1931 loadFormats(value + 1, profile);
1934 if (profile->mChannelMasks[0] == 0) {
1935 reply = mpClientInterface->getParameters(output,
1936 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1937 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1939 value = strpbrk((char *)reply.string(), "=");
1940 if (value != NULL) {
1941 loadOutChannels(value + 1, profile);
1944 if (((profile->mSamplingRates[0] == 0) &&
1945 (profile->mSamplingRates.size() < 2)) ||
1946 ((profile->mFormats[0] == 0) &&
1947 (profile->mFormats.size() < 2)) ||
1948 ((profile->mChannelMasks[0] == 0) &&
1949 (profile->mChannelMasks.size() < 2))) {
1950 ALOGW("checkOutputsForDevice() direct output missing param");
1951 mpClientInterface->closeOutput(output);
1953 } else if (profile->mSamplingRates[0] == 0) {
1954 mpClientInterface->closeOutput(output);
1955 desc->mSamplingRate = profile->mSamplingRates[1];
1956 offloadInfo.sample_rate = desc->mSamplingRate;
1957 output = mpClientInterface->openOutput(
1958 profile->mModule->mHandle,
1960 &desc->mSamplingRate,
1962 &desc->mChannelMask,
1969 addOutput(output, desc);
1970 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
1971 audio_io_handle_t duplicatedOutput = 0;
1973 // set initial stream volume for device
1974 applyStreamVolumes(output, device, 0, true);
1976 //TODO: configure audio effect output stage here
1978 // open a duplicating output thread for the new output and the primary output
1979 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1981 if (duplicatedOutput != 0) {
1982 // add duplicated output descriptor
1983 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1984 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1985 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1986 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1987 dupOutputDesc->mFormat = desc->mFormat;
1988 dupOutputDesc->mChannelMask = desc->mChannelMask;
1989 dupOutputDesc->mLatency = desc->mLatency;
1990 addOutput(duplicatedOutput, dupOutputDesc);
1991 applyStreamVolumes(duplicatedOutput, device, 0, true);
1993 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1994 mPrimaryOutput, output);
1995 mpClientInterface->closeOutput(output);
1996 mOutputs.removeItem(output);
2003 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2005 profiles.removeAt(profile_index);
2008 outputs.add(output);
2009 ALOGV("checkOutputsForDevice(): adding output %d", output);
2013 if (profiles.isEmpty()) {
2014 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2017 } else { // Disconnect
2018 // check if one opened output is not needed any more after disconnecting one device
2019 for (size_t i = 0; i < mOutputs.size(); i++) {
2020 desc = mOutputs.valueAt(i);
2021 if (!desc->isDuplicated() &&
2022 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
2023 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2024 outputs.add(mOutputs.keyAt(i));
2027 // Clear any profiles associated with the disconnected device.
2028 for (size_t i = 0; i < mHwModules.size(); i++)
2030 if (mHwModules[i]->mHandle == 0) {
2033 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2035 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
2036 if (profile->mSupportedDevices & device) {
2037 ALOGV("checkOutputsForDevice(): clearing direct output profile %zu on module %zu",
2039 if (profile->mSamplingRates[0] == 0) {
2040 profile->mSamplingRates.clear();
2041 profile->mSamplingRates.add(0);
2043 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2044 profile->mFormats.clear();
2045 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2047 if (profile->mChannelMasks[0] == 0) {
2048 profile->mChannelMasks.clear();
2049 profile->mChannelMasks.add(0);
2058 status_t AudioPolicyManagerBase::checkInputsForDevice(audio_devices_t device,
2059 AudioSystem::device_connection_state state,
2060 SortedVector<audio_io_handle_t>& inputs,
2061 const String8 paramStr)
2063 AudioInputDescriptor *desc;
2064 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
2065 // first list already open inputs that can be routed to this device
2066 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2067 desc = mInputs.valueAt(input_index);
2068 if (desc->mProfile->mSupportedDevices & (device & ~AUDIO_DEVICE_BIT_IN)) {
2069 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2070 inputs.add(mInputs.keyAt(input_index));
2074 // then look for input profiles that can be routed to this device
2075 SortedVector<IOProfile *> profiles;
2076 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
2078 if (mHwModules[module_index]->mHandle == 0) {
2081 for (size_t profile_index = 0;
2082 profile_index < mHwModules[module_index]->mInputProfiles.size();
2085 if (mHwModules[module_index]->mInputProfiles[profile_index]->mSupportedDevices
2086 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2087 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2088 profile_index, module_index);
2089 profiles.add(mHwModules[module_index]->mInputProfiles[profile_index]);
2094 if (profiles.isEmpty() && inputs.isEmpty()) {
2095 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2099 // open inputs for matching profiles if needed. Direct inputs are also opened to
2100 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2101 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2103 IOProfile *profile = profiles[profile_index];
2104 // nothing to do if one input is already opened for this profile
2106 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2107 desc = mInputs.valueAt(input_index);
2108 if (desc->mProfile == profile) {
2112 if (input_index != mInputs.size()) {
2116 ALOGV("opening input for device 0x%X with params %s", device, paramStr.string());
2117 desc = new AudioInputDescriptor(profile);
2118 desc->mDevice = device;
2120 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2122 &desc->mSamplingRate,
2124 &desc->mChannelMask);
2127 if (!paramStr.isEmpty()) {
2128 mpClientInterface->setParameters(input, paramStr);
2131 // Here is where we step through and resolve any "dynamic" fields
2134 if (profile->mSamplingRates[0] == 0) {
2135 reply = mpClientInterface->getParameters(input,
2136 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2137 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2139 value = strpbrk((char *)reply.string(), "=");
2140 if (value != NULL) {
2141 loadSamplingRates(value + 1, profile);
2144 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2145 reply = mpClientInterface->getParameters(input,
2146 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2147 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2148 value = strpbrk((char *)reply.string(), "=");
2149 if (value != NULL) {
2150 loadFormats(value + 1, profile);
2153 if (profile->mChannelMasks[0] == 0) {
2154 reply = mpClientInterface->getParameters(input,
2155 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2156 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2158 value = strpbrk((char *)reply.string(), "=");
2159 if (value != NULL) {
2160 loadInChannels(value + 1, profile);
2163 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2164 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2165 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2166 ALOGW("checkInputsForDevice() direct input missing param");
2167 mpClientInterface->closeInput(input);
2172 addInput(input, desc);
2174 } // endif input != 0
2177 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2179 profiles.removeAt(profile_index);
2183 ALOGV("checkInputsForDevice(): adding input %d", input);
2185 } // end scan profiles
2187 if (profiles.isEmpty()) {
2188 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2193 // check if one opened input is not needed any more after disconnecting one device
2194 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2195 desc = mInputs.valueAt(input_index);
2196 if (!(desc->mProfile->mSupportedDevices & mAvailableInputDevices)) {
2197 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2198 mInputs.keyAt(input_index));
2199 inputs.add(mInputs.keyAt(input_index));
2202 // Clear any profiles associated with the disconnected device.
2203 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
2205 if (mHwModules[module_index]->mHandle == 0) {
2208 for (size_t profile_index = 0;
2209 profile_index < mHwModules[module_index]->mInputProfiles.size();
2212 IOProfile *profile = mHwModules[module_index]->mInputProfiles[profile_index];
2213 if (profile->mSupportedDevices & device) {
2214 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2215 profile_index, module_index);
2216 if (profile->mSamplingRates[0] == 0) {
2217 profile->mSamplingRates.clear();
2218 profile->mSamplingRates.add(0);
2220 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2221 profile->mFormats.clear();
2222 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2224 if (profile->mChannelMasks[0] == 0) {
2225 profile->mChannelMasks.clear();
2226 profile->mChannelMasks.add(0);
2236 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
2238 ALOGV("closeOutput(%d)", output);
2240 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2241 if (outputDesc == NULL) {
2242 ALOGW("closeOutput() unknown output %d", output);
2246 // look for duplicated outputs connected to the output being removed.
2247 for (size_t i = 0; i < mOutputs.size(); i++) {
2248 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2249 if (dupOutputDesc->isDuplicated() &&
2250 (dupOutputDesc->mOutput1 == outputDesc ||
2251 dupOutputDesc->mOutput2 == outputDesc)) {
2252 AudioOutputDescriptor *outputDesc2;
2253 if (dupOutputDesc->mOutput1 == outputDesc) {
2254 outputDesc2 = dupOutputDesc->mOutput2;
2256 outputDesc2 = dupOutputDesc->mOutput1;
2258 // As all active tracks on duplicated output will be deleted,
2259 // and as they were also referenced on the other output, the reference
2260 // count for their stream type must be adjusted accordingly on
2261 // the other output.
2262 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
2263 int refCount = dupOutputDesc->mRefCount[j];
2264 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
2266 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2267 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2269 mpClientInterface->closeOutput(duplicatedOutput);
2270 delete mOutputs.valueFor(duplicatedOutput);
2271 mOutputs.removeItem(duplicatedOutput);
2275 AudioParameter param;
2276 param.add(String8("closing"), String8("true"));
2277 mpClientInterface->setParameters(output, param.toString());
2279 mpClientInterface->closeOutput(output);
2281 mOutputs.removeItem(output);
2282 mPreviousOutputs = mOutputs;
2285 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
2286 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2288 SortedVector<audio_io_handle_t> outputs;
2290 ALOGVV("getOutputsForDevice() device %04x", device);
2291 for (size_t i = 0; i < openOutputs.size(); i++) {
2292 ALOGVV("output %d isDuplicated=%d device=%04x",
2293 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2294 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2295 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2296 outputs.add(openOutputs.keyAt(i));
2302 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2303 SortedVector<audio_io_handle_t>& outputs2)
2305 if (outputs1.size() != outputs2.size()) {
2308 for (size_t i = 0; i < outputs1.size(); i++) {
2309 if (outputs1[i] != outputs2[i]) {
2316 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
2318 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2319 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2320 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2321 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2323 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2324 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2325 strategy, srcOutputs[0], dstOutputs[0]);
2326 // mute strategy while moving tracks from one output to another
2327 for (size_t i = 0; i < srcOutputs.size(); i++) {
2328 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2329 if (desc->isStrategyActive(strategy)) {
2330 setStrategyMute(strategy, true, srcOutputs[i]);
2331 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2335 // Move effects associated to this strategy from previous output to new output
2336 if (strategy == STRATEGY_MEDIA) {
2337 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2338 SortedVector<audio_io_handle_t> moved;
2339 for (size_t i = 0; i < mEffects.size(); i++) {
2340 EffectDescriptor *desc = mEffects.valueAt(i);
2341 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2342 desc->mIo != fxOutput) {
2343 if (moved.indexOf(desc->mIo) < 0) {
2344 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2345 mEffects.keyAt(i), fxOutput);
2346 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2348 moved.add(desc->mIo);
2350 desc->mIo = fxOutput;
2354 // Move tracks associated to this strategy from previous output to new output
2355 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2356 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2357 mpClientInterface->invalidateStream((AudioSystem::stream_type)i);
2363 void AudioPolicyManagerBase::checkOutputForAllStrategies()
2365 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2366 checkOutputForStrategy(STRATEGY_PHONE);
2367 checkOutputForStrategy(STRATEGY_SONIFICATION);
2368 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2369 checkOutputForStrategy(STRATEGY_MEDIA);
2370 checkOutputForStrategy(STRATEGY_DTMF);
2373 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2379 for (size_t i = 0; i < mOutputs.size(); i++) {
2380 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2381 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2382 return mOutputs.keyAt(i);
2389 void AudioPolicyManagerBase::checkA2dpSuspend()
2394 audio_io_handle_t a2dpOutput = getA2dpOutput();
2395 if (a2dpOutput == 0) {
2399 // suspend A2DP output if:
2400 // (NOT already suspended) &&
2401 // ((SCO device is connected &&
2402 // (forced usage for communication || for record is SCO))) ||
2403 // (phone state is ringing || in call)
2405 // restore A2DP output if:
2406 // (Already suspended) &&
2407 // ((SCO device is NOT connected ||
2408 // (forced usage NOT for communication && NOT for record is SCO))) &&
2409 // (phone state is NOT ringing && NOT in call)
2411 if (mA2dpSuspended) {
2412 if (((mScoDeviceAddress == "") ||
2413 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2414 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2415 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2416 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2418 mpClientInterface->restoreOutput(a2dpOutput);
2419 mA2dpSuspended = false;
2422 if (((mScoDeviceAddress != "") &&
2423 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2424 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2425 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2426 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2428 mpClientInterface->suspendOutput(a2dpOutput);
2429 mA2dpSuspended = true;
2434 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2436 audio_devices_t device = AUDIO_DEVICE_NONE;
2438 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2439 // check the following by order of priority to request a routing change if necessary:
2440 // 1: the strategy enforced audible is active on the output:
2441 // use device for strategy enforced audible
2442 // 2: we are in call or the strategy phone is active on the output:
2443 // use device for strategy phone
2444 // 3: the strategy sonification is active on the output:
2445 // use device for strategy sonification
2446 // 4: the strategy "respectful" sonification is active on the output:
2447 // use device for strategy "respectful" sonification
2448 // 5: the strategy media is active on the output:
2449 // use device for strategy media
2450 // 6: the strategy DTMF is active on the output:
2451 // use device for strategy DTMF
2452 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2453 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2454 } else if (isInCall() ||
2455 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2456 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2457 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2458 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2459 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2460 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2461 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2462 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2463 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2464 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2467 ALOGV("getNewDevice() selected device %x", device);
2471 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2472 return (uint32_t)getStrategy(stream);
2475 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2476 audio_devices_t devices;
2477 // By checking the range of stream before calling getStrategy, we avoid
2478 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2479 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2480 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2481 devices = AUDIO_DEVICE_NONE;
2483 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2484 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2489 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2490 AudioSystem::stream_type stream) {
2491 // stream to strategy mapping
2493 case AudioSystem::VOICE_CALL:
2494 case AudioSystem::BLUETOOTH_SCO:
2495 return STRATEGY_PHONE;
2496 case AudioSystem::RING:
2497 case AudioSystem::ALARM:
2498 return STRATEGY_SONIFICATION;
2499 case AudioSystem::NOTIFICATION:
2500 return STRATEGY_SONIFICATION_RESPECTFUL;
2501 case AudioSystem::DTMF:
2502 return STRATEGY_DTMF;
2504 ALOGE("unknown stream type");
2505 case AudioSystem::SYSTEM:
2506 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2507 // while key clicks are played produces a poor result
2508 case AudioSystem::TTS:
2509 case AudioSystem::MUSIC:
2510 return STRATEGY_MEDIA;
2511 case AudioSystem::ENFORCED_AUDIBLE:
2512 return STRATEGY_ENFORCED_AUDIBLE;
2516 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2518 case AudioSystem::MUSIC:
2519 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2520 updateDevicesAndOutputs();
2527 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2530 uint32_t device = AUDIO_DEVICE_NONE;
2533 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2534 strategy, mDeviceForStrategy[strategy]);
2535 return mDeviceForStrategy[strategy];
2540 case STRATEGY_SONIFICATION_RESPECTFUL:
2542 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2543 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2544 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2545 // while media is playing on a remote device, use the the sonification behavior.
2546 // Note that we test this usecase before testing if media is playing because
2547 // the isStreamActive() method only informs about the activity of a stream, not
2548 // if it's for local playback. Note also that we use the same delay between both tests
2549 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2550 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2551 // while media is playing (or has recently played), use the same device
2552 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2554 // when media is not playing anymore, fall back on the sonification behavior
2555 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2562 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2563 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2566 // when in call, DTMF and PHONE strategies follow the same rules
2569 case STRATEGY_PHONE:
2570 // for phone strategy, we first consider the forced use and then the available devices by order
2572 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2573 case AudioSystem::FORCE_BT_SCO:
2574 if (!isInCall() || strategy != STRATEGY_DTMF) {
2575 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2578 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2580 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2582 // if SCO device is requested but no SCO device is available, fall back to default case
2585 default: // FORCE_NONE
2586 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2587 if (mHasA2dp && !isInCall() &&
2588 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2589 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2590 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2592 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2595 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2597 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2599 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2600 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2602 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2604 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2606 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2608 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2611 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2613 device = mDefaultOutputDevice;
2614 if (device == AUDIO_DEVICE_NONE) {
2615 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2619 case AudioSystem::FORCE_SPEAKER:
2620 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2621 // A2DP speaker when forcing to speaker output
2622 if (mHasA2dp && !isInCall() &&
2623 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2624 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2625 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2628 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2629 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2631 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2633 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2635 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2637 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2640 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2642 device = mDefaultOutputDevice;
2643 if (device == AUDIO_DEVICE_NONE) {
2644 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2650 case STRATEGY_SONIFICATION:
2652 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2653 // handleIncallSonification().
2655 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2660 case STRATEGY_ENFORCED_AUDIBLE:
2661 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2663 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2664 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2666 if ((strategy == STRATEGY_SONIFICATION) ||
2667 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2668 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2669 if (device == AUDIO_DEVICE_NONE) {
2670 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2673 // The second device used for sonification is the same as the device used by media strategy
2676 case STRATEGY_MEDIA: {
2677 uint32_t device2 = AUDIO_DEVICE_NONE;
2678 if (strategy != STRATEGY_SONIFICATION) {
2679 // no sonification on remote submix (e.g. WFD)
2680 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2682 if ((device2 == AUDIO_DEVICE_NONE) &&
2683 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2684 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2685 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2686 if (device2 == AUDIO_DEVICE_NONE) {
2687 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2689 if (device2 == AUDIO_DEVICE_NONE) {
2690 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2693 if (device2 == AUDIO_DEVICE_NONE) {
2694 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2696 if (device2 == AUDIO_DEVICE_NONE) {
2697 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2699 if (device2 == AUDIO_DEVICE_NONE) {
2700 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2702 if (device2 == AUDIO_DEVICE_NONE) {
2703 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2705 if (device2 == AUDIO_DEVICE_NONE) {
2706 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2708 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2709 // no sonification on aux digital (e.g. HDMI)
2710 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2712 if ((device2 == AUDIO_DEVICE_NONE) &&
2713 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2714 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2716 if (device2 == AUDIO_DEVICE_NONE) {
2717 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2720 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2721 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2724 device = mDefaultOutputDevice;
2725 if (device == AUDIO_DEVICE_NONE) {
2726 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2731 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2735 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2739 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2741 for (int i = 0; i < NUM_STRATEGIES; i++) {
2742 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2744 mPreviousOutputs = mOutputs;
2747 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2748 audio_devices_t prevDevice,
2751 // mute/unmute strategies using an incompatible device combination
2752 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2753 // if unmuting, unmute only after the specified delay
2754 if (outputDesc->isDuplicated()) {
2758 uint32_t muteWaitMs = 0;
2759 audio_devices_t device = outputDesc->device();
2760 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2761 // temporary mute output if device selection changes to avoid volume bursts due to
2762 // different per device volumes
2763 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2765 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2766 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2767 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2768 bool doMute = false;
2770 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2772 outputDesc->mStrategyMutedByDevice[i] = true;
2773 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2775 outputDesc->mStrategyMutedByDevice[i] = false;
2777 if (doMute || tempMute) {
2778 for (size_t j = 0; j < mOutputs.size(); j++) {
2779 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2780 // skip output if it does not share any device with current output
2781 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2782 == AUDIO_DEVICE_NONE) {
2785 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2786 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2787 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2788 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2789 if (desc->isStrategyActive((routing_strategy)i)) {
2790 // do tempMute only for current output
2791 if (tempMute && (desc == outputDesc)) {
2792 setStrategyMute((routing_strategy)i, true, curOutput);
2793 setStrategyMute((routing_strategy)i, false, curOutput,
2794 desc->latency() * 2, device);
2796 if ((tempMute && (desc == outputDesc)) || mute) {
2797 if (muteWaitMs < desc->latency()) {
2798 muteWaitMs = desc->latency();
2806 // FIXME: should not need to double latency if volume could be applied immediately by the
2807 // audioflinger mixer. We must account for the delay between now and the next time
2808 // the audioflinger thread for this output will process a buffer (which corresponds to
2809 // one buffer size, usually 1/2 or 1/4 of the latency).
2811 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2812 if (muteWaitMs > delayMs) {
2813 muteWaitMs -= delayMs;
2814 usleep(muteWaitMs * 1000);
2820 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2821 audio_devices_t device,
2825 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2826 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2827 AudioParameter param;
2828 uint32_t muteWaitMs;
2830 if (outputDesc->isDuplicated()) {
2831 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2832 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2835 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2837 if ((device != AUDIO_DEVICE_NONE) &&
2838 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2842 // filter devices according to output selected
2843 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2845 audio_devices_t prevDevice = outputDesc->mDevice;
2847 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2849 if (device != AUDIO_DEVICE_NONE) {
2850 outputDesc->mDevice = device;
2852 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2854 // Do not change the routing if:
2855 // - the requested device is AUDIO_DEVICE_NONE
2856 // - the requested device is the same as current device and force is not specified.
2857 // Doing this check here allows the caller to call setOutputDevice() without conditions
2858 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2859 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2863 ALOGV("setOutputDevice() changing device");
2865 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2866 mpClientInterface->setParameters(output, param.toString(), delayMs);
2868 // update stream volumes according to new device
2869 applyStreamVolumes(output, device, delayMs);
2874 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2875 uint32_t samplingRate,
2876 audio_format_t format,
2877 audio_channel_mask_t channelMask)
2879 // Choose an input profile based on the requested capture parameters: select the first available
2880 // profile supporting all requested parameters.
2881 for (size_t i = 0; i < mHwModules.size(); i++)
2883 if (mHwModules[i]->mHandle == 0) {
2886 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2888 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2890 if (profile->isCompatibleProfile(device, samplingRate, format,
2891 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
2899 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2901 uint32_t device = AUDIO_DEVICE_NONE;
2903 switch (inputSource) {
2904 case AUDIO_SOURCE_VOICE_UPLINK:
2905 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2906 device = AUDIO_DEVICE_IN_VOICE_CALL;
2911 case AUDIO_SOURCE_DEFAULT:
2912 case AUDIO_SOURCE_MIC:
2913 case AUDIO_SOURCE_VOICE_RECOGNITION:
2914 case AUDIO_SOURCE_HOTWORD:
2915 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2916 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2917 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2918 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2919 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2920 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2921 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_USB_DEVICE) {
2922 device = AUDIO_DEVICE_IN_USB_DEVICE;
2923 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2924 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2927 case AUDIO_SOURCE_CAMCORDER:
2928 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2929 device = AUDIO_DEVICE_IN_BACK_MIC;
2930 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2931 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2934 case AUDIO_SOURCE_VOICE_DOWNLINK:
2935 case AUDIO_SOURCE_VOICE_CALL:
2936 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2937 device = AUDIO_DEVICE_IN_VOICE_CALL;
2940 case AUDIO_SOURCE_REMOTE_SUBMIX:
2941 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2942 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2946 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2949 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2953 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2955 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2956 device &= ~AUDIO_DEVICE_BIT_IN;
2957 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2963 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2965 for (size_t i = 0; i < mInputs.size(); i++) {
2966 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2967 if ((input_descriptor->mRefCount > 0)
2968 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2969 return mInputs.keyAt(i);
2976 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2978 if (device == AUDIO_DEVICE_NONE) {
2979 // this happens when forcing a route update and no track is active on an output.
2980 // In this case the returned category is not important.
2981 device = AUDIO_DEVICE_OUT_SPEAKER;
2982 } else if (AudioSystem::popCount(device) > 1) {
2983 // Multiple device selection is either:
2984 // - speaker + one other device: give priority to speaker in this case.
2985 // - one A2DP device + another device: happens with duplicated output. In this case
2986 // retain the device on the A2DP output as the other must not correspond to an active
2987 // selection if not the speaker.
2988 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2989 device = AUDIO_DEVICE_OUT_SPEAKER;
2991 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2995 ALOGW_IF(AudioSystem::popCount(device) != 1,
2996 "getDeviceForVolume() invalid device combination: %08x",
3002 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
3004 switch(getDeviceForVolume(device)) {
3005 case AUDIO_DEVICE_OUT_EARPIECE:
3006 return DEVICE_CATEGORY_EARPIECE;
3007 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3008 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3009 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3010 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3011 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3012 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3013 return DEVICE_CATEGORY_HEADSET;
3014 case AUDIO_DEVICE_OUT_SPEAKER:
3015 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3016 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3017 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3018 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3019 case AUDIO_DEVICE_OUT_USB_DEVICE:
3020 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3022 return DEVICE_CATEGORY_SPEAKER;
3026 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
3029 device_category deviceCategory = getDeviceCategory(device);
3030 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3032 // the volume index in the UI is relative to the min and max volume indices for this stream type
3033 int nbSteps = 1 + curve[VOLMAX].mIndex -
3034 curve[VOLMIN].mIndex;
3035 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3036 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3038 // find what part of the curve this index volume belongs to, or if it's out of bounds
3040 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3042 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3044 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3046 } else if (volIdx <= curve[VOLMAX].mIndex) {
3048 } else { // out of bounds
3052 // linear interpolation in the attenuation table in dB
3053 float decibels = curve[segment].mDBAttenuation +
3054 ((float)(volIdx - curve[segment].mIndex)) *
3055 ( (curve[segment+1].mDBAttenuation -
3056 curve[segment].mDBAttenuation) /
3057 ((float)(curve[segment+1].mIndex -
3058 curve[segment].mIndex)) );
3060 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3062 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3063 curve[segment].mIndex, volIdx,
3064 curve[segment+1].mIndex,
3065 curve[segment].mDBAttenuation,
3067 curve[segment+1].mDBAttenuation,
3070 return amplification;
3073 const AudioPolicyManagerBase::VolumeCurvePoint
3074 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3075 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3078 const AudioPolicyManagerBase::VolumeCurvePoint
3079 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3080 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3083 const AudioPolicyManagerBase::VolumeCurvePoint
3084 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3085 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3088 const AudioPolicyManagerBase::VolumeCurvePoint
3089 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3090 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3093 const AudioPolicyManagerBase::VolumeCurvePoint
3094 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
3095 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3098 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3099 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3100 // AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3101 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3103 const AudioPolicyManagerBase::VolumeCurvePoint
3104 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3105 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3108 const AudioPolicyManagerBase::VolumeCurvePoint
3109 AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
3110 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3113 const AudioPolicyManagerBase::VolumeCurvePoint
3114 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3115 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3118 const AudioPolicyManagerBase::VolumeCurvePoint
3119 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3120 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3123 const AudioPolicyManagerBase::VolumeCurvePoint
3124 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3125 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3128 const AudioPolicyManagerBase::VolumeCurvePoint
3129 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
3130 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
3131 { // AUDIO_STREAM_VOICE_CALL
3132 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3133 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3134 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3136 { // AUDIO_STREAM_SYSTEM
3137 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3138 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3139 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3141 { // AUDIO_STREAM_RING
3142 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3143 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3144 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3146 { // AUDIO_STREAM_MUSIC
3147 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3148 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3149 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3151 { // AUDIO_STREAM_ALARM
3152 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3153 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3154 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3156 { // AUDIO_STREAM_NOTIFICATION
3157 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3158 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3159 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3161 { // AUDIO_STREAM_BLUETOOTH_SCO
3162 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3163 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3164 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3166 { // AUDIO_STREAM_ENFORCED_AUDIBLE
3167 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3168 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3169 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3171 { // AUDIO_STREAM_DTMF
3172 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3173 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3174 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3176 { // AUDIO_STREAM_TTS
3177 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3178 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3179 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3183 void AudioPolicyManagerBase::initializeVolumeCurves()
3185 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3186 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
3187 mStreams[i].mVolumeCurve[j] =
3188 sVolumeProfiles[i][j];
3192 // Check availability of DRC on speaker path: if available, override some of the speaker curves
3193 if (mSpeakerDrcEnabled) {
3194 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3195 sDefaultSystemVolumeCurveDrc;
3196 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3197 sSpeakerSonificationVolumeCurveDrc;
3198 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3199 sSpeakerSonificationVolumeCurveDrc;
3200 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3201 sSpeakerSonificationVolumeCurveDrc;
3205 float AudioPolicyManagerBase::computeVolume(int stream,
3207 audio_io_handle_t output,
3208 audio_devices_t device)
3211 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3212 StreamDescriptor &streamDesc = mStreams[stream];
3214 if (device == AUDIO_DEVICE_NONE) {
3215 device = outputDesc->device();
3218 // if volume is not 0 (not muted), force media volume to max on digital output
3219 if (stream == AudioSystem::MUSIC &&
3220 index != mStreams[stream].mIndexMin &&
3221 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3222 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
3223 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
3224 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
3228 volume = volIndexToAmpl(device, streamDesc, index);
3230 // if a headset is connected, apply the following rules to ring tones and notifications
3231 // to avoid sound level bursts in user's ears:
3232 // - always attenuate ring tones and notifications volume by 6dB
3233 // - if music is playing, always limit the volume to current music volume,
3234 // with a minimum threshold at -36dB so that notification is always perceived.
3235 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3236 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3237 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3238 AUDIO_DEVICE_OUT_WIRED_HEADSET |
3239 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3240 ((stream_strategy == STRATEGY_SONIFICATION)
3241 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
3242 || (stream == AudioSystem::SYSTEM)
3243 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
3244 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
3245 streamDesc.mCanBeMuted) {
3246 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3247 // when the phone is ringing we must consider that music could have been paused just before
3248 // by the music application and behave as if music was active if the last music track was
3250 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
3251 mLimitRingtoneVolume) {
3252 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
3253 float musicVol = computeVolume(AudioSystem::MUSIC,
3254 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
3257 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3258 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3259 if (volume > minVol) {
3261 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3269 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
3271 audio_io_handle_t output,
3272 audio_devices_t device,
3277 // do not change actual stream volume if the stream is muted
3278 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3279 ALOGVV("checkAndSetVolume() stream %d muted count %d",
3280 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3284 // do not change in call volume if bluetooth is connected and vice versa
3285 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
3286 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
3287 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
3288 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
3289 return INVALID_OPERATION;
3292 float volume = computeVolume(stream, index, output, device);
3293 // We actually change the volume if:
3294 // - the float value returned by computeVolume() changed
3295 // - the force flag is set
3296 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3298 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3299 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3300 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3302 if (stream == AudioSystem::BLUETOOTH_SCO) {
3303 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
3305 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
3308 if (stream == AudioSystem::VOICE_CALL ||
3309 stream == AudioSystem::BLUETOOTH_SCO) {
3311 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3312 if (stream == AudioSystem::VOICE_CALL) {
3313 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3318 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3319 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3320 mLastVoiceVolume = voiceVolume;
3327 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
3328 audio_devices_t device,
3332 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3334 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3335 checkAndSetVolume(stream,
3336 mStreams[stream].getVolumeIndex(device),
3344 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
3346 audio_io_handle_t output,
3348 audio_devices_t device)
3350 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3351 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3352 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3353 setStreamMute(stream, on, output, delayMs, device);
3358 void AudioPolicyManagerBase::setStreamMute(int stream,
3360 audio_io_handle_t output,
3362 audio_devices_t device)
3364 StreamDescriptor &streamDesc = mStreams[stream];
3365 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3366 if (device == AUDIO_DEVICE_NONE) {
3367 device = outputDesc->device();
3370 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3371 stream, on, output, outputDesc->mMuteCount[stream], device);
3374 if (outputDesc->mMuteCount[stream] == 0) {
3375 if (streamDesc.mCanBeMuted &&
3376 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3377 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3378 checkAndSetVolume(stream, 0, output, device, delayMs);
3381 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3382 outputDesc->mMuteCount[stream]++;
3384 if (outputDesc->mMuteCount[stream] == 0) {
3385 ALOGV("setStreamMute() unmuting non muted stream!");
3388 if (--outputDesc->mMuteCount[stream] == 0) {
3389 checkAndSetVolume(stream,
3390 streamDesc.getVolumeIndex(device),
3398 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3400 // if the stream pertains to sonification strategy and we are in call we must
3401 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3402 // in the device used for phone strategy and play the tone if the selected device does not
3403 // interfere with the device used for phone strategy
3404 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3405 // many times as there are active tracks on the output
3406 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3407 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3408 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3409 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3410 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3411 stream, starting, outputDesc->mDevice, stateChange);
3412 if (outputDesc->mRefCount[stream]) {
3415 muteCount = outputDesc->mRefCount[stream];
3417 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3418 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3419 for (int i = 0; i < muteCount; i++) {
3420 setStreamMute(stream, starting, mPrimaryOutput);
3423 ALOGV("handleIncallSonification() high visibility");
3424 if (outputDesc->device() &
3425 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3426 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3427 for (int i = 0; i < muteCount; i++) {
3428 setStreamMute(stream, starting, mPrimaryOutput);
3432 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3434 mpClientInterface->stopTone();
3441 bool AudioPolicyManagerBase::isInCall()
3443 return isStateInCall(mPhoneState);
3446 bool AudioPolicyManagerBase::isStateInCall(int state) {
3447 return ((state == AudioSystem::MODE_IN_CALL) ||
3448 (state == AudioSystem::MODE_IN_COMMUNICATION));
3451 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3453 return MAX_EFFECTS_CPU_LOAD;
3456 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3458 return MAX_EFFECTS_MEMORY;
3461 // --- AudioOutputDescriptor class implementation
3463 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3464 const IOProfile *profile)
3465 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3466 mChannelMask(0), mLatency(0),
3467 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3468 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3470 // clear usage count for all stream types
3471 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3473 mCurVolume[i] = -1.0;
3477 for (int i = 0; i < NUM_STRATEGIES; i++) {
3478 mStrategyMutedByDevice[i] = false;
3480 if (profile != NULL) {
3481 mSamplingRate = profile->mSamplingRates[0];
3482 mFormat = profile->mFormats[0];
3483 mChannelMask = profile->mChannelMasks[0];
3484 mFlags = profile->mFlags;
3488 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3490 if (isDuplicated()) {
3491 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3497 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3499 if (isDuplicated()) {
3500 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3506 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3507 const AudioOutputDescriptor *outputDesc)
3509 if (isDuplicated()) {
3510 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3511 } else if (outputDesc->isDuplicated()){
3512 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3514 return (mProfile->mModule == outputDesc->mProfile->mModule);
3518 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3520 // forward usage count change to attached outputs
3521 if (isDuplicated()) {
3522 mOutput1->changeRefCount(stream, delta);
3523 mOutput2->changeRefCount(stream, delta);
3525 if ((delta + (int)mRefCount[stream]) < 0) {
3526 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3527 mRefCount[stream] = 0;
3530 mRefCount[stream] += delta;
3531 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3534 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3536 if (isDuplicated()) {
3537 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3539 return mProfile->mSupportedDevices ;
3543 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3545 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3548 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3550 nsecs_t sysTime) const
3552 if ((sysTime == 0) && (inPastMs != 0)) {
3553 sysTime = systemTime();
3555 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3556 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3557 (NUM_STRATEGIES == strategy)) &&
3558 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3565 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3567 nsecs_t sysTime) const
3569 if (mRefCount[stream] != 0) {
3572 if (inPastMs == 0) {
3576 sysTime = systemTime();
3578 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3585 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3587 const size_t SIZE = 256;
3591 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3592 result.append(buffer);
3593 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3594 result.append(buffer);
3595 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3596 result.append(buffer);
3597 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3598 result.append(buffer);
3599 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3600 result.append(buffer);
3601 snprintf(buffer, SIZE, " Devices %08x\n", device());
3602 result.append(buffer);
3603 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3604 result.append(buffer);
3605 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3606 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3607 result.append(buffer);
3609 write(fd, result.string(), result.size());
3614 // --- AudioInputDescriptor class implementation
3616 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3617 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
3618 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3619 mInputSource(0), mProfile(profile)
3621 if (profile != NULL) {
3622 mSamplingRate = profile->mSamplingRates[0];
3623 mFormat = profile->mFormats[0];
3624 mChannelMask = profile->mChannelMasks[0];
3628 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3630 const size_t SIZE = 256;
3634 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3635 result.append(buffer);
3636 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3637 result.append(buffer);
3638 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3639 result.append(buffer);
3640 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3641 result.append(buffer);
3642 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3643 result.append(buffer);
3644 write(fd, result.string(), result.size());
3649 // --- StreamDescriptor class implementation
3651 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3652 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3654 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3657 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3659 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3660 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3661 if (mIndexCur.indexOfKey(device) < 0) {
3662 device = AUDIO_DEVICE_OUT_DEFAULT;
3664 return mIndexCur.valueFor(device);
3667 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3669 const size_t SIZE = 256;
3673 snprintf(buffer, SIZE, "%s %02d %02d ",
3674 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3675 result.append(buffer);
3676 for (size_t i = 0; i < mIndexCur.size(); i++) {
3677 snprintf(buffer, SIZE, "%04x : %02d, ",
3679 mIndexCur.valueAt(i));
3680 result.append(buffer);
3682 result.append("\n");
3684 write(fd, result.string(), result.size());
3687 // --- EffectDescriptor class implementation
3689 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3691 const size_t SIZE = 256;
3695 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3696 result.append(buffer);
3697 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3698 result.append(buffer);
3699 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3700 result.append(buffer);
3701 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3702 result.append(buffer);
3703 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3704 result.append(buffer);
3705 write(fd, result.string(), result.size());
3710 // --- IOProfile class implementation
3712 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3713 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3717 AudioPolicyManagerBase::HwModule::~HwModule()
3719 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3720 delete mOutputProfiles[i];
3722 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3723 delete mInputProfiles[i];
3725 free((void *)mName);
3728 void AudioPolicyManagerBase::HwModule::dump(int fd)
3730 const size_t SIZE = 256;
3734 snprintf(buffer, SIZE, " - name: %s\n", mName);
3735 result.append(buffer);
3736 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3737 result.append(buffer);
3738 write(fd, result.string(), result.size());
3739 if (mOutputProfiles.size()) {
3740 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
3741 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3742 snprintf(buffer, SIZE, " output %zu:\n", i);
3743 write(fd, buffer, strlen(buffer));
3744 mOutputProfiles[i]->dump(fd);
3747 if (mInputProfiles.size()) {
3748 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
3749 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3750 snprintf(buffer, SIZE, " input %zu:\n", i);
3751 write(fd, buffer, strlen(buffer));
3752 mInputProfiles[i]->dump(fd);
3757 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3758 : mFlags((audio_output_flags_t)0), mModule(module)
3762 AudioPolicyManagerBase::IOProfile::~IOProfile()
3766 // checks if the IO profile is compatible with specified parameters.
3767 // Sampling rate, format and channel mask must be specified in order to
3768 // get a valid a match
3769 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3770 uint32_t samplingRate,
3771 audio_format_t format,
3772 audio_channel_mask_t channelMask,
3773 audio_output_flags_t flags) const
3775 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3779 if ((mSupportedDevices & device) != device) {
3782 if ((mFlags & flags) != flags) {
3786 for (i = 0; i < mSamplingRates.size(); i++)
3788 if (mSamplingRates[i] == samplingRate) {
3792 if (i == mSamplingRates.size()) {
3795 for (i = 0; i < mFormats.size(); i++)
3797 if (mFormats[i] == format) {
3801 if (i == mFormats.size()) {
3804 for (i = 0; i < mChannelMasks.size(); i++)
3806 if (mChannelMasks[i] == channelMask) {
3810 if (i == mChannelMasks.size()) {
3816 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3818 const size_t SIZE = 256;
3822 snprintf(buffer, SIZE, " - sampling rates: ");
3823 result.append(buffer);
3824 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3825 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3826 result.append(buffer);
3827 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3830 snprintf(buffer, SIZE, " - channel masks: ");
3831 result.append(buffer);
3832 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3833 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3834 result.append(buffer);
3835 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3838 snprintf(buffer, SIZE, " - formats: ");
3839 result.append(buffer);
3840 for (size_t i = 0; i < mFormats.size(); i++) {
3841 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3842 result.append(buffer);
3843 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3846 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
3847 result.append(buffer);
3848 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3849 result.append(buffer);
3851 write(fd, result.string(), result.size());
3854 void AudioPolicyManagerBase::IOProfile::log()
3856 const size_t SIZE = 256;
3860 ALOGV(" - sampling rates: ");
3861 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3862 ALOGV(" %d", mSamplingRates[i]);
3865 ALOGV(" - channel masks: ");
3866 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3867 ALOGV(" 0x%04x", mChannelMasks[i]);
3870 ALOGV(" - formats: ");
3871 for (size_t i = 0; i < mFormats.size(); i++) {
3872 ALOGV(" 0x%08x", mFormats[i]);
3875 ALOGV(" - devices: 0x%04x\n", mSupportedDevices);
3876 ALOGV(" - flags: 0x%04x\n", mFlags);
3879 // --- audio_policy.conf file parsing
3881 struct StringToEnum {
3886 #define STRING_TO_ENUM(string) { #string, string }
3887 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3889 const struct StringToEnum sDeviceNameToEnumTable[] = {
3890 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3891 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3892 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3893 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3894 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3895 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3896 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3897 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3898 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3899 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3900 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3901 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3902 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3903 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3904 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3905 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3906 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3907 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3908 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3909 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3910 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3911 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3912 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3913 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
3916 const struct StringToEnum sFlagNameToEnumTable[] = {
3917 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3918 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3919 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3920 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3921 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3922 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3925 const struct StringToEnum sFormatNameToEnumTable[] = {
3926 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3927 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3928 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
3929 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
3930 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
3931 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
3932 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3933 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3934 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3937 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3938 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3939 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3940 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3941 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3944 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3945 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3946 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3947 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3951 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3955 for (size_t i = 0; i < size; i++) {
3956 if (strcmp(table[i].name, name) == 0) {
3957 ALOGV("stringToEnum() found %s", table[i].name);
3958 return table[i].value;
3964 bool AudioPolicyManagerBase::stringToBool(const char *value)
3966 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
3969 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3973 // it is OK to cast name to non const here as we are not going to use it after
3974 // strtok() modifies it
3975 char *flagName = strtok(name, "|");
3976 while (flagName != NULL) {
3977 if (strlen(flagName) != 0) {
3978 flag |= stringToEnum(sFlagNameToEnumTable,
3979 ARRAY_SIZE(sFlagNameToEnumTable),
3982 flagName = strtok(NULL, "|");
3984 //force direct flag if offload flag is set: offloading implies a direct output stream
3985 // and all common behaviors are driven by checking only the direct flag
3986 // this should normally be set appropriately in the policy configuration file
3987 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3988 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
3991 return (audio_output_flags_t)flag;
3994 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3996 uint32_t device = 0;
3998 char *devName = strtok(name, "|");
3999 while (devName != NULL) {
4000 if (strlen(devName) != 0) {
4001 device |= stringToEnum(sDeviceNameToEnumTable,
4002 ARRAY_SIZE(sDeviceNameToEnumTable),
4005 devName = strtok(NULL, "|");
4010 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
4012 char *str = strtok(name, "|");
4014 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4015 // rates should be read from the output stream after it is opened for the first time
4016 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4017 profile->mSamplingRates.add(0);
4021 while (str != NULL) {
4022 uint32_t rate = atoi(str);
4024 ALOGV("loadSamplingRates() adding rate %d", rate);
4025 profile->mSamplingRates.add(rate);
4027 str = strtok(NULL, "|");
4032 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
4034 char *str = strtok(name, "|");
4036 // by convention, "0' in the first entry in mFormats indicates the supported formats
4037 // should be read from the output stream after it is opened for the first time
4038 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4039 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
4043 while (str != NULL) {
4044 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4045 ARRAY_SIZE(sFormatNameToEnumTable),
4047 if (format != AUDIO_FORMAT_DEFAULT) {
4048 profile->mFormats.add(format);
4050 str = strtok(NULL, "|");
4055 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
4057 const char *str = strtok(name, "|");
4059 ALOGV("loadInChannels() %s", name);
4061 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4062 profile->mChannelMasks.add(0);
4066 while (str != NULL) {
4067 audio_channel_mask_t channelMask =
4068 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4069 ARRAY_SIZE(sInChannelsNameToEnumTable),
4071 if (channelMask != 0) {
4072 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4073 profile->mChannelMasks.add(channelMask);
4075 str = strtok(NULL, "|");
4080 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
4082 const char *str = strtok(name, "|");
4084 ALOGV("loadOutChannels() %s", name);
4086 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4087 // masks should be read from the output stream after it is opened for the first time
4088 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4089 profile->mChannelMasks.add(0);
4093 while (str != NULL) {
4094 audio_channel_mask_t channelMask =
4095 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4096 ARRAY_SIZE(sOutChannelsNameToEnumTable),
4098 if (channelMask != 0) {
4099 profile->mChannelMasks.add(channelMask);
4101 str = strtok(NULL, "|");
4106 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
4108 cnode *node = root->first_child;
4110 IOProfile *profile = new IOProfile(module);
4113 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4114 loadSamplingRates((char *)node->value, profile);
4115 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4116 loadFormats((char *)node->value, profile);
4117 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4118 loadInChannels((char *)node->value, profile);
4119 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4120 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
4124 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
4125 "loadInput() invalid supported devices");
4126 ALOGW_IF(profile->mChannelMasks.size() == 0,
4127 "loadInput() invalid supported channel masks");
4128 ALOGW_IF(profile->mSamplingRates.size() == 0,
4129 "loadInput() invalid supported sampling rates");
4130 ALOGW_IF(profile->mFormats.size() == 0,
4131 "loadInput() invalid supported formats");
4132 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
4133 (profile->mChannelMasks.size() != 0) &&
4134 (profile->mSamplingRates.size() != 0) &&
4135 (profile->mFormats.size() != 0)) {
4137 ALOGV("loadInput() adding input mSupportedDevices 0x%X", profile->mSupportedDevices);
4139 module->mInputProfiles.add(profile);
4147 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
4149 cnode *node = root->first_child;
4151 IOProfile *profile = new IOProfile(module);
4154 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4155 loadSamplingRates((char *)node->value, profile);
4156 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4157 loadFormats((char *)node->value, profile);
4158 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4159 loadOutChannels((char *)node->value, profile);
4160 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4161 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
4162 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4163 profile->mFlags = parseFlagNames((char *)node->value);
4167 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
4168 "loadOutput() invalid supported devices");
4169 ALOGW_IF(profile->mChannelMasks.size() == 0,
4170 "loadOutput() invalid supported channel masks");
4171 ALOGW_IF(profile->mSamplingRates.size() == 0,
4172 "loadOutput() invalid supported sampling rates");
4173 ALOGW_IF(profile->mFormats.size() == 0,
4174 "loadOutput() invalid supported formats");
4175 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
4176 (profile->mChannelMasks.size() != 0) &&
4177 (profile->mSamplingRates.size() != 0) &&
4178 (profile->mFormats.size() != 0)) {
4180 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
4181 profile->mSupportedDevices, profile->mFlags);
4183 module->mOutputProfiles.add(profile);
4191 void AudioPolicyManagerBase::loadHwModule(cnode *root)
4193 cnode *node = config_find(root, OUTPUTS_TAG);
4194 status_t status = NAME_NOT_FOUND;
4196 HwModule *module = new HwModule(root->name);
4199 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
4201 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
4203 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
4204 mHasRemoteSubmix = true;
4207 node = node->first_child;
4209 ALOGV("loadHwModule() loading output %s", node->name);
4210 status_t tmpStatus = loadOutput(node, module);
4211 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4217 node = config_find(root, INPUTS_TAG);
4219 node = node->first_child;
4221 ALOGV("loadHwModule() loading input %s", node->name);
4222 status_t tmpStatus = loadInput(node, module);
4223 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4229 if (status == NO_ERROR) {
4230 mHwModules.add(module);
4236 void AudioPolicyManagerBase::loadHwModules(cnode *root)
4238 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
4243 node = node->first_child;
4245 ALOGV("loadHwModules() loading module %s", node->name);
4251 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
4253 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4257 node = node->first_child;
4259 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
4260 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
4261 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
4262 "loadGlobalConfig() no attached output devices");
4263 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
4264 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
4265 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
4266 ARRAY_SIZE(sDeviceNameToEnumTable),
4267 (char *)node->value);
4268 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
4269 "loadGlobalConfig() default device not specified");
4270 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
4271 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
4272 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
4273 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
4274 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4275 mSpeakerDrcEnabled = stringToBool((char *)node->value);
4276 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4282 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
4287 data = (char *)load_file(path, NULL);
4291 root = config_node("", "");
4292 config_load(root, data);
4294 loadGlobalConfig(root);
4295 loadHwModules(root);
4301 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4306 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
4311 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
4312 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
4313 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
4315 module = new HwModule("primary");
4317 profile = new IOProfile(module);
4318 profile->mSamplingRates.add(44100);
4319 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4320 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4321 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
4322 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4323 module->mOutputProfiles.add(profile);
4325 profile = new IOProfile(module);
4326 profile->mSamplingRates.add(8000);
4327 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4328 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4329 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
4330 module->mInputProfiles.add(profile);
4332 mHwModules.add(module);
4335 }; // namespace android