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 // device_address can be NULL and should be handled as an empty string in this case,
57 // and it is not checked by AudioPolicyInterfaceImpl.cpp
58 if (device_address == NULL) {
61 ALOGV("setDeviceConnectionState() device: 0x%X, state %d, address %s", device, state, device_address);
63 // connect/disconnect only 1 device at a time
64 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
66 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
67 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
71 // handle output devices
72 if (audio_is_output_device(device)) {
73 SortedVector <audio_io_handle_t> outputs;
75 if (!mHasA2dp && audio_is_a2dp_out_device(device)) {
76 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
79 if (!mHasUsb && audio_is_usb_out_device(device)) {
80 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
83 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
84 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
88 // save a copy of the opened output descriptors before any output is opened or closed
89 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
90 mPreviousOutputs = mOutputs;
94 // handle output device connection
95 case AudioSystem::DEVICE_STATE_AVAILABLE:
96 if (mAvailableOutputDevices & device) {
97 ALOGW("setDeviceConnectionState() device already connected: %x", device);
98 return INVALID_OPERATION;
100 ALOGV("setDeviceConnectionState() connecting device %x", device);
102 if (mHasA2dp && audio_is_a2dp_out_device(device)) {
103 // handle A2DP device connection
104 AudioParameter param;
105 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
106 paramStr = param.toString();
107 } else if (mHasUsb && audio_is_usb_out_device(device)) {
108 // handle USB device connection
109 paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
112 if (checkOutputsForDevice(device, state, outputs, paramStr) != NO_ERROR) {
113 return INVALID_OPERATION;
115 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
117 // register new device as available
118 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
120 if (mHasA2dp && audio_is_a2dp_out_device(device)) {
121 // handle A2DP device connection
122 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
123 mA2dpSuspended = false;
124 } else if (audio_is_bluetooth_sco_device(device)) {
125 // handle SCO device connection
126 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
127 } else if (mHasUsb && audio_is_usb_out_device(device)) {
128 // handle USB device connection
129 mUsbOutCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
133 // handle output device disconnection
134 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
135 if (!(mAvailableOutputDevices & device)) {
136 ALOGW("setDeviceConnectionState() device not connected: %x", device);
137 return INVALID_OPERATION;
140 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
141 // remove device from available output devices
142 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
143 checkOutputsForDevice(device, state, outputs, paramStr);
145 if (mHasA2dp && audio_is_a2dp_out_device(device)) {
146 // handle A2DP device disconnection
147 mA2dpDeviceAddress = "";
148 mA2dpSuspended = false;
149 } else if (audio_is_bluetooth_sco_device(device)) {
150 // handle SCO device disconnection
151 mScoDeviceAddress = "";
152 } else if (mHasUsb && audio_is_usb_out_device(device)) {
153 // handle USB device disconnection
154 mUsbOutCardAndDevice = "";
156 // not currently handling multiple simultaneous submixes: ignoring remote submix
161 ALOGE("setDeviceConnectionState() invalid state: %x", state);
166 checkOutputForAllStrategies();
167 // outputs must be closed after checkOutputForAllStrategies() is executed
168 if (!outputs.isEmpty()) {
169 for (size_t i = 0; i < outputs.size(); i++) {
170 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
171 // close unused outputs after device disconnection or direct outputs that have been
172 // opened by checkOutputsForDevice() to query dynamic parameters
173 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
174 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
175 (desc->mDirectOpenCount == 0))) {
176 closeOutput(outputs[i]);
181 updateDevicesAndOutputs();
182 for (size_t i = 0; i < mOutputs.size(); i++) {
183 // do not force device change on duplicated output because if device is 0, it will
184 // also force a device 0 for the two outputs it is duplicated to which may override
185 // a valid device selection on those outputs.
186 setOutputDevice(mOutputs.keyAt(i),
187 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
188 !mOutputs.valueAt(i)->isDuplicated(),
193 } // end if is output device
195 // handle input devices
196 if (audio_is_input_device(device)) {
197 SortedVector <audio_io_handle_t> inputs;
202 // handle input device connection
203 case AudioSystem::DEVICE_STATE_AVAILABLE: {
204 if (mAvailableInputDevices & device) {
205 ALOGW("setDeviceConnectionState() device already connected: %d", device);
206 return INVALID_OPERATION;
209 if (mHasUsb && audio_is_usb_in_device(device)) {
210 // handle USB device connection
211 paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
212 } else if (mHasA2dp && audio_is_a2dp_in_device(device)) {
213 // handle A2DP device connection
214 AudioParameter param;
215 param.add(String8(AUDIO_PARAMETER_A2DP_SOURCE_ADDRESS), String8(device_address));
216 paramStr = param.toString();
219 if (checkInputsForDevice(device, state, inputs, paramStr) != NO_ERROR) {
220 return INVALID_OPERATION;
222 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
226 // handle input device disconnection
227 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
228 if (!(mAvailableInputDevices & device)) {
229 ALOGW("setDeviceConnectionState() device not connected: %d", device);
230 return INVALID_OPERATION;
232 checkInputsForDevice(device, state, inputs, paramStr);
233 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
237 ALOGE("setDeviceConnectionState() invalid state: %x", state);
244 } // end if is input device
246 ALOGW("setDeviceConnectionState() invalid device: %x", device);
250 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
251 const char *device_address)
253 // similar to setDeviceConnectionState
254 if (device_address == NULL) {
257 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
258 String8 address = String8(device_address);
259 if (audio_is_output_device(device)) {
260 if (device & mAvailableOutputDevices) {
261 if (audio_is_a2dp_out_device(device) &&
262 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
265 if (audio_is_bluetooth_sco_device(device) &&
266 address != "" && mScoDeviceAddress != address) {
269 if (audio_is_usb_out_device(device) &&
270 (!mHasUsb || (address != "" && mUsbOutCardAndDevice != address))) {
271 ALOGE("getDeviceConnectionState() invalid device: %x", device);
274 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
277 state = AudioSystem::DEVICE_STATE_AVAILABLE;
279 } else if (audio_is_input_device(device)) {
280 if (device & mAvailableInputDevices) {
281 state = AudioSystem::DEVICE_STATE_AVAILABLE;
288 void AudioPolicyManagerBase::setPhoneState(int state)
290 ALOGV("setPhoneState() state %d", state);
291 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
292 if (state < 0 || state >= AudioSystem::NUM_MODES) {
293 ALOGW("setPhoneState() invalid state %d", state);
297 if (state == mPhoneState ) {
298 ALOGW("setPhoneState() setting same state %d", state);
302 // if leaving call state, handle special case of active streams
303 // pertaining to sonification strategy see handleIncallSonification()
305 ALOGV("setPhoneState() in call state management: new state is %d", state);
306 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
307 handleIncallSonification(stream, false, true);
311 // store previous phone state for management of sonification strategy below
312 int oldState = mPhoneState;
316 // are we entering or starting a call
317 if (!isStateInCall(oldState) && isStateInCall(state)) {
318 ALOGV(" Entering call in setPhoneState()");
319 // force routing command to audio hardware when starting a call
320 // even if no device change is needed
322 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
323 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
324 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
326 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
327 ALOGV(" Exiting call in setPhoneState()");
328 // force routing command to audio hardware when exiting a call
329 // even if no device change is needed
331 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
332 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
333 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
335 } else if (isStateInCall(state) && (state != oldState)) {
336 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
337 // force routing command to audio hardware when switching between telephony and VoIP
338 // even if no device change is needed
342 // check for device and output changes triggered by new phone state
343 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
345 checkOutputForAllStrategies();
346 updateDevicesAndOutputs();
348 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
350 // force routing command to audio hardware when ending call
351 // even if no device change is needed
352 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
353 newDevice = hwOutputDesc->device();
357 if (isStateInCall(state)) {
358 nsecs_t sysTime = systemTime();
359 for (size_t i = 0; i < mOutputs.size(); i++) {
360 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
361 // mute media and sonification strategies and delay device switch by the largest
362 // latency of any output where either strategy is active.
363 // This avoid sending the ring tone or music tail into the earpiece or headset.
364 if ((desc->isStrategyActive(STRATEGY_MEDIA,
365 SONIFICATION_HEADSET_MUSIC_DELAY,
367 desc->isStrategyActive(STRATEGY_SONIFICATION,
368 SONIFICATION_HEADSET_MUSIC_DELAY,
370 (delayMs < (int)desc->mLatency*2)) {
371 delayMs = desc->mLatency*2;
373 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
374 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
375 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
376 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
377 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
378 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
382 // change routing is necessary
383 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
385 // if entering in call state, handle special case of active streams
386 // pertaining to sonification strategy see handleIncallSonification()
387 if (isStateInCall(state)) {
388 ALOGV("setPhoneState() in call state management: new state is %d", state);
389 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
390 handleIncallSonification(stream, true, true);
394 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
395 if (state == AudioSystem::MODE_RINGTONE &&
396 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
397 mLimitRingtoneVolume = true;
399 mLimitRingtoneVolume = false;
403 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
405 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
407 bool forceVolumeReeval = false;
409 case AudioSystem::FOR_COMMUNICATION:
410 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
411 config != AudioSystem::FORCE_NONE) {
412 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
415 forceVolumeReeval = true;
416 mForceUse[usage] = config;
418 case AudioSystem::FOR_MEDIA:
419 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
420 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
421 config != AudioSystem::FORCE_ANALOG_DOCK &&
422 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
423 config != AudioSystem::FORCE_NO_BT_A2DP) {
424 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
427 mForceUse[usage] = config;
429 case AudioSystem::FOR_RECORD:
430 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
431 config != AudioSystem::FORCE_NONE) {
432 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
435 mForceUse[usage] = config;
437 case AudioSystem::FOR_DOCK:
438 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
439 config != AudioSystem::FORCE_BT_DESK_DOCK &&
440 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
441 config != AudioSystem::FORCE_ANALOG_DOCK &&
442 config != AudioSystem::FORCE_DIGITAL_DOCK) {
443 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
445 forceVolumeReeval = true;
446 mForceUse[usage] = config;
448 case AudioSystem::FOR_SYSTEM:
449 if (config != AudioSystem::FORCE_NONE &&
450 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
451 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
453 forceVolumeReeval = true;
454 mForceUse[usage] = config;
457 ALOGW("setForceUse() invalid usage %d", usage);
461 // check for device and output changes triggered by new force usage
463 checkOutputForAllStrategies();
464 updateDevicesAndOutputs();
465 for (size_t i = 0; i < mOutputs.size(); i++) {
466 audio_io_handle_t output = mOutputs.keyAt(i);
467 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
468 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
469 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
470 applyStreamVolumes(output, newDevice, 0, true);
474 audio_io_handle_t activeInput = getActiveInput();
475 if (activeInput != 0) {
476 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
477 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
478 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
479 ALOGV("setForceUse() changing device from %x to %x for input %d",
480 inputDesc->mDevice, newDevice, activeInput);
481 inputDesc->mDevice = newDevice;
482 AudioParameter param = AudioParameter();
483 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
484 mpClientInterface->setParameters(activeInput, param.toString());
490 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
492 return mForceUse[usage];
495 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
497 ALOGV("setSystemProperty() property %s, value %s", property, value);
500 // Find a direct output profile compatible with the parameters passed, even if the input flags do
501 // not explicitly request a direct output
502 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
503 audio_devices_t device,
504 uint32_t samplingRate,
505 audio_format_t format,
506 audio_channel_mask_t channelMask,
507 audio_output_flags_t flags)
509 for (size_t i = 0; i < mHwModules.size(); i++) {
510 if (mHwModules[i]->mHandle == 0) {
513 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
514 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
515 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
516 if (profile->isCompatibleProfile(device, samplingRate, format,
518 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
519 if (mAvailableOutputDevices & profile->mSupportedDevices) {
520 return mHwModules[i]->mOutputProfiles[j];
524 if (profile->isCompatibleProfile(device, samplingRate, format,
526 AUDIO_OUTPUT_FLAG_DIRECT)) {
527 if (mAvailableOutputDevices & profile->mSupportedDevices) {
528 return mHwModules[i]->mOutputProfiles[j];
537 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
538 uint32_t samplingRate,
539 audio_format_t format,
540 audio_channel_mask_t channelMask,
541 AudioSystem::output_flags flags,
542 const audio_offload_info_t *offloadInfo)
544 audio_io_handle_t output = 0;
545 uint32_t latency = 0;
546 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
547 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
548 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
549 device, stream, samplingRate, format, channelMask, flags);
551 #ifdef AUDIO_POLICY_TEST
552 if (mCurOutput != 0) {
553 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
554 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
556 if (mTestOutputs[mCurOutput] == 0) {
557 ALOGV("getOutput() opening test output");
558 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
559 outputDesc->mDevice = mTestDevice;
560 outputDesc->mSamplingRate = mTestSamplingRate;
561 outputDesc->mFormat = mTestFormat;
562 outputDesc->mChannelMask = mTestChannels;
563 outputDesc->mLatency = mTestLatencyMs;
564 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
565 outputDesc->mRefCount[stream] = 0;
566 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
567 &outputDesc->mSamplingRate,
568 &outputDesc->mFormat,
569 &outputDesc->mChannelMask,
570 &outputDesc->mLatency,
573 if (mTestOutputs[mCurOutput]) {
574 AudioParameter outputCmd = AudioParameter();
575 outputCmd.addInt(String8("set_id"),mCurOutput);
576 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
577 addOutput(mTestOutputs[mCurOutput], outputDesc);
580 return mTestOutputs[mCurOutput];
582 #endif //AUDIO_POLICY_TEST
584 // open a direct output if required by specified parameters
585 //force direct flag if offload flag is set: offloading implies a direct output stream
586 // and all common behaviors are driven by checking only the direct flag
587 // this should normally be set appropriately in the policy configuration file
588 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
589 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
592 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
593 // creating an offloaded track and tearing it down immediately after start when audioflinger
594 // detects there is an active non offloadable effect.
595 // FIXME: We should check the audio session here but we do not have it in this context.
596 // This may prevent offloading in rare situations where effects are left active by apps
597 // in the background.
598 IOProfile *profile = NULL;
599 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
600 !isNonOffloadableEffectEnabled()) {
601 profile = getProfileForDirectOutput(device,
605 (audio_output_flags_t)flags);
608 if (profile != NULL) {
609 AudioOutputDescriptor *outputDesc = NULL;
611 for (size_t i = 0; i < mOutputs.size(); i++) {
612 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
613 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
615 // reuse direct output if currently open and configured with same parameters
616 if ((samplingRate == outputDesc->mSamplingRate) &&
617 (format == outputDesc->mFormat) &&
618 (channelMask == outputDesc->mChannelMask)) {
619 outputDesc->mDirectOpenCount++;
620 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
621 return mOutputs.keyAt(i);
625 // close direct output if currently open and configured with different parameters
626 if (outputDesc != NULL) {
627 closeOutput(outputDesc->mId);
629 outputDesc = new AudioOutputDescriptor(profile);
630 outputDesc->mDevice = device;
631 outputDesc->mSamplingRate = samplingRate;
632 outputDesc->mFormat = format;
633 outputDesc->mChannelMask = channelMask;
634 outputDesc->mLatency = 0;
635 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
636 outputDesc->mRefCount[stream] = 0;
637 outputDesc->mStopTime[stream] = 0;
638 outputDesc->mDirectOpenCount = 1;
639 output = mpClientInterface->openOutput(profile->mModule->mHandle,
640 &outputDesc->mDevice,
641 &outputDesc->mSamplingRate,
642 &outputDesc->mFormat,
643 &outputDesc->mChannelMask,
644 &outputDesc->mLatency,
648 // only accept an output with the requested parameters
650 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
651 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
652 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
653 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
654 "format %d %d, channelMask %04x %04x", output, samplingRate,
655 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
656 outputDesc->mChannelMask);
658 mpClientInterface->closeOutput(output);
663 audio_io_handle_t srcOutput = getOutputForEffect();
664 addOutput(output, outputDesc);
665 audio_io_handle_t dstOutput = getOutputForEffect();
666 if (dstOutput == output) {
667 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
669 mPreviousOutputs = mOutputs;
670 ALOGV("getOutput() returns new direct output %d", output);
674 // ignoring channel mask due to downmix capability in mixer
676 // open a non direct output
678 // for non direct outputs, only PCM is supported
679 if (audio_is_linear_pcm(format)) {
680 // get which output is suitable for the specified stream. The actual
681 // routing change will happen when startOutput() will be called
682 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
684 output = selectOutput(outputs, flags);
686 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
687 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
689 ALOGV("getOutput() returns output %d", output);
694 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
695 AudioSystem::output_flags flags)
697 // select one output among several that provide a path to a particular device or set of
698 // devices (the list was previously build by getOutputsForDevice()).
699 // The priority is as follows:
700 // 1: the output with the highest number of requested policy flags
701 // 2: the primary output
702 // 3: the first output in the list
704 if (outputs.size() == 0) {
707 if (outputs.size() == 1) {
711 int maxCommonFlags = 0;
712 audio_io_handle_t outputFlags = 0;
713 audio_io_handle_t outputPrimary = 0;
715 for (size_t i = 0; i < outputs.size(); i++) {
716 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
717 if (!outputDesc->isDuplicated()) {
718 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
719 if (commonFlags > maxCommonFlags) {
720 outputFlags = outputs[i];
721 maxCommonFlags = commonFlags;
722 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
724 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
725 outputPrimary = outputs[i];
730 if (outputFlags != 0) {
733 if (outputPrimary != 0) {
734 return outputPrimary;
740 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
741 AudioSystem::stream_type stream,
744 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
745 ssize_t index = mOutputs.indexOfKey(output);
747 ALOGW("startOutput() unknown output %d", output);
751 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
753 // increment usage count for this stream on the requested output:
754 // NOTE that the usage count is the same for duplicated output and hardware output which is
755 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
756 outputDesc->changeRefCount(stream, 1);
758 if (outputDesc->mRefCount[stream] == 1) {
759 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
760 routing_strategy strategy = getStrategy(stream);
761 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
762 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
765 for (size_t i = 0; i < mOutputs.size(); i++) {
766 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
767 if (desc != outputDesc) {
768 // force a device change if any other output is managed by the same hw
769 // module and has a current device selection that differs from selected device.
770 // In this case, the audio HAL must receive the new device selection so that it can
771 // change the device currently selected by the other active output.
772 if (outputDesc->sharesHwModuleWith(desc) &&
773 desc->device() != newDevice) {
776 // wait for audio on other active outputs to be presented when starting
777 // a notification so that audio focus effect can propagate.
778 uint32_t latency = desc->latency();
779 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
784 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
786 // handle special case for sonification while in call
788 handleIncallSonification(stream, true, false);
791 // apply volume rules for current stream and device if necessary
792 checkAndSetVolume(stream,
793 mStreams[stream].getVolumeIndex(newDevice),
797 // update the outputs if starting an output with a stream that can affect notification
799 handleNotificationRoutingForStream(stream);
800 if (waitMs > muteWaitMs) {
801 usleep((waitMs - muteWaitMs) * 2 * 1000);
808 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
809 AudioSystem::stream_type stream,
812 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
813 ssize_t index = mOutputs.indexOfKey(output);
815 ALOGW("stopOutput() unknown output %d", output);
819 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
821 // handle special case for sonification while in call
823 handleIncallSonification(stream, false, false);
826 if (outputDesc->mRefCount[stream] > 0) {
827 // decrement usage count of this stream on the output
828 outputDesc->changeRefCount(stream, -1);
829 // store time at which the stream was stopped - see isStreamActive()
830 if (outputDesc->mRefCount[stream] == 0) {
831 outputDesc->mStopTime[stream] = systemTime();
832 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
833 // delay the device switch by twice the latency because stopOutput() is executed when
834 // the track stop() command is received and at that time the audio track buffer can
835 // still contain data that needs to be drained. The latency only covers the audio HAL
836 // and kernel buffers. Also the latency does not always include additional delay in the
837 // audio path (audio DSP, CODEC ...)
838 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
840 // force restoring the device selection on other active outputs if it differs from the
841 // one being selected for this output
842 for (size_t i = 0; i < mOutputs.size(); i++) {
843 audio_io_handle_t curOutput = mOutputs.keyAt(i);
844 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
845 if (curOutput != output &&
847 outputDesc->sharesHwModuleWith(desc) &&
848 (newDevice != desc->device())) {
849 setOutputDevice(curOutput,
850 getNewDevice(curOutput, false /*fromCache*/),
852 outputDesc->mLatency*2);
855 // update the outputs if stopping one with a stream that can affect notification routing
856 handleNotificationRoutingForStream(stream);
860 ALOGW("stopOutput() refcount is already 0 for output %d", output);
861 return INVALID_OPERATION;
865 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
867 ALOGV("releaseOutput() %d", output);
868 ssize_t index = mOutputs.indexOfKey(output);
870 ALOGW("releaseOutput() releasing unknown output %d", output);
874 #ifdef AUDIO_POLICY_TEST
875 int testIndex = testOutputIndex(output);
876 if (testIndex != 0) {
877 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
878 if (outputDesc->isActive()) {
879 mpClientInterface->closeOutput(output);
880 delete mOutputs.valueAt(index);
881 mOutputs.removeItem(output);
882 mTestOutputs[testIndex] = 0;
886 #endif //AUDIO_POLICY_TEST
888 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
889 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
890 if (desc->mDirectOpenCount <= 0) {
891 ALOGW("releaseOutput() invalid open count %d for output %d",
892 desc->mDirectOpenCount, output);
895 if (--desc->mDirectOpenCount == 0) {
897 // If effects where present on the output, audioflinger moved them to the primary
898 // output by default: move them back to the appropriate output.
899 audio_io_handle_t dstOutput = getOutputForEffect();
900 if (dstOutput != mPrimaryOutput) {
901 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
908 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
909 uint32_t samplingRate,
910 audio_format_t format,
911 audio_channel_mask_t channelMask,
912 AudioSystem::audio_in_acoustics acoustics)
914 audio_io_handle_t input = 0;
915 audio_devices_t device = getDeviceForInputSource(inputSource);
917 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
918 inputSource, samplingRate, format, channelMask, acoustics);
920 if (device == AUDIO_DEVICE_NONE) {
921 ALOGW("getInput() could not find device for inputSource %d", inputSource);
925 // adapt channel selection to input source
926 switch(inputSource) {
927 case AUDIO_SOURCE_VOICE_UPLINK:
928 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
930 case AUDIO_SOURCE_VOICE_DOWNLINK:
931 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
933 case AUDIO_SOURCE_VOICE_CALL:
934 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
940 IOProfile *profile = getInputProfile(device,
944 if (profile == NULL) {
945 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %d, format %d, "
947 device, samplingRate, format, channelMask);
951 if (profile->mModule->mHandle == 0) {
952 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
956 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
958 inputDesc->mInputSource = inputSource;
959 inputDesc->mDevice = device;
960 inputDesc->mSamplingRate = samplingRate;
961 inputDesc->mFormat = format;
962 inputDesc->mChannelMask = channelMask;
963 inputDesc->mRefCount = 0;
965 input = mpClientInterface->openInput(profile->mModule->mHandle,
967 &inputDesc->mSamplingRate,
969 &inputDesc->mChannelMask);
971 // only accept input with the exact requested set of parameters
973 (samplingRate != inputDesc->mSamplingRate) ||
974 (format != inputDesc->mFormat) ||
975 (channelMask != inputDesc->mChannelMask)) {
976 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask 0x%X",
977 samplingRate, format, channelMask);
979 mpClientInterface->closeInput(input);
984 addInput(input, inputDesc);
989 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
991 ALOGV("startInput() input %d", input);
992 ssize_t index = mInputs.indexOfKey(input);
994 ALOGW("startInput() unknown input %d", input);
997 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
999 #ifdef AUDIO_POLICY_TEST
1000 if (mTestInput == 0)
1001 #endif //AUDIO_POLICY_TEST
1003 // refuse 2 active AudioRecord clients at the same time except if the active input
1004 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1005 audio_io_handle_t activeInput = getActiveInput();
1006 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1007 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1008 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1009 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1010 stopInput(activeInput);
1011 releaseInput(activeInput);
1013 ALOGW("startInput() input %d failed: other input already started", input);
1014 return INVALID_OPERATION;
1019 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1020 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1021 inputDesc->mDevice = newDevice;
1024 // automatically enable the remote submix output when input is started
1025 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1026 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1027 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1030 AudioParameter param = AudioParameter();
1031 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1033 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1034 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1036 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1037 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1039 mpClientInterface->setParameters(input, param.toString());
1041 inputDesc->mRefCount = 1;
1045 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
1047 ALOGV("stopInput() input %d", input);
1048 ssize_t index = mInputs.indexOfKey(input);
1050 ALOGW("stopInput() unknown input %d", input);
1053 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1055 if (inputDesc->mRefCount == 0) {
1056 ALOGW("stopInput() input %d already stopped", input);
1057 return INVALID_OPERATION;
1059 // automatically disable the remote submix output when input is stopped
1060 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1061 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1062 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1065 AudioParameter param = AudioParameter();
1066 param.addInt(String8(AudioParameter::keyRouting), 0);
1067 mpClientInterface->setParameters(input, param.toString());
1068 inputDesc->mRefCount = 0;
1073 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1075 ALOGV("releaseInput() %d", input);
1076 ssize_t index = mInputs.indexOfKey(input);
1078 ALOGW("releaseInput() releasing unknown input %d", input);
1081 mpClientInterface->closeInput(input);
1082 delete mInputs.valueAt(index);
1083 mInputs.removeItem(input);
1085 ALOGV("releaseInput() exit");
1088 void AudioPolicyManagerBase::closeAllInputs() {
1089 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1090 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1095 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1099 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1100 if (indexMin < 0 || indexMin >= indexMax) {
1101 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1104 mStreams[stream].mIndexMin = indexMin;
1105 mStreams[stream].mIndexMax = indexMax;
1108 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1110 audio_devices_t device)
1113 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1116 if (!audio_is_output_device(device)) {
1120 // Force max volume if stream cannot be muted
1121 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1123 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1124 stream, device, index);
1126 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1127 // clear all device specific values
1128 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1129 mStreams[stream].mIndexCur.clear();
1131 mStreams[stream].mIndexCur.add(device, index);
1133 // compute and apply stream volume on all outputs according to connected device
1134 status_t status = NO_ERROR;
1135 for (size_t i = 0; i < mOutputs.size(); i++) {
1136 audio_devices_t curDevice =
1137 getDeviceForVolume(mOutputs.valueAt(i)->device());
1138 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1139 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1140 if (volStatus != NO_ERROR) {
1148 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1150 audio_devices_t device)
1152 if (index == NULL) {
1155 if (!audio_is_output_device(device)) {
1158 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1159 // the strategy the stream belongs to.
1160 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1161 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1163 device = getDeviceForVolume(device);
1165 *index = mStreams[stream].getVolumeIndex(device);
1166 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1170 audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
1171 const SortedVector<audio_io_handle_t>& outputs)
1173 // select one output among several suitable for global effects.
1174 // The priority is as follows:
1175 // 1: An offloaded output. If the effect ends up not being offloadable,
1176 // AudioFlinger will invalidate the track and the offloaded output
1177 // will be closed causing the effect to be moved to a PCM output.
1178 // 2: A deep buffer output
1179 // 3: the first output in the list
1181 if (outputs.size() == 0) {
1185 audio_io_handle_t outputOffloaded = 0;
1186 audio_io_handle_t outputDeepBuffer = 0;
1188 for (size_t i = 0; i < outputs.size(); i++) {
1189 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1190 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1191 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1192 outputOffloaded = outputs[i];
1194 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1195 outputDeepBuffer = outputs[i];
1199 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1200 outputOffloaded, outputDeepBuffer);
1201 if (outputOffloaded != 0) {
1202 return outputOffloaded;
1204 if (outputDeepBuffer != 0) {
1205 return outputDeepBuffer;
1211 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1213 // apply simple rule where global effects are attached to the same output as MUSIC streams
1215 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1216 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1217 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1219 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1220 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1221 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1226 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1227 audio_io_handle_t io,
1232 ssize_t index = mOutputs.indexOfKey(io);
1234 index = mInputs.indexOfKey(io);
1236 ALOGW("registerEffect() unknown io %d", io);
1237 return INVALID_OPERATION;
1241 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1242 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1243 desc->name, desc->memoryUsage);
1244 return INVALID_OPERATION;
1246 mTotalEffectsMemory += desc->memoryUsage;
1247 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1248 desc->name, io, strategy, session, id);
1249 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1251 EffectDescriptor *pDesc = new EffectDescriptor();
1252 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1254 pDesc->mStrategy = (routing_strategy)strategy;
1255 pDesc->mSession = session;
1256 pDesc->mEnabled = false;
1258 mEffects.add(id, pDesc);
1263 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1265 ssize_t index = mEffects.indexOfKey(id);
1267 ALOGW("unregisterEffect() unknown effect ID %d", id);
1268 return INVALID_OPERATION;
1271 EffectDescriptor *pDesc = mEffects.valueAt(index);
1273 setEffectEnabled(pDesc, false);
1275 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1276 ALOGW("unregisterEffect() memory %d too big for total %d",
1277 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1278 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1280 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1281 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1282 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1284 mEffects.removeItem(id);
1290 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1292 ssize_t index = mEffects.indexOfKey(id);
1294 ALOGW("unregisterEffect() unknown effect ID %d", id);
1295 return INVALID_OPERATION;
1298 return setEffectEnabled(mEffects.valueAt(index), enabled);
1301 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1303 if (enabled == pDesc->mEnabled) {
1304 ALOGV("setEffectEnabled(%s) effect already %s",
1305 enabled?"true":"false", enabled?"enabled":"disabled");
1306 return INVALID_OPERATION;
1310 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1311 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1312 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1313 return INVALID_OPERATION;
1315 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1316 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1318 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1319 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1320 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1321 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1323 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1324 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1326 pDesc->mEnabled = enabled;
1330 bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled()
1332 for (size_t i = 0; i < mEffects.size(); i++) {
1333 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1334 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1335 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1336 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1337 pDesc->mDesc.name, pDesc->mSession);
1344 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1346 nsecs_t sysTime = systemTime();
1347 for (size_t i = 0; i < mOutputs.size(); i++) {
1348 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1349 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1356 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1358 nsecs_t sysTime = systemTime();
1359 for (size_t i = 0; i < mOutputs.size(); i++) {
1360 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1361 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1362 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1369 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1371 for (size_t i = 0; i < mInputs.size(); i++) {
1372 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1373 if ((inputDescriptor->mInputSource == (int)source ||
1374 (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
1375 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1376 && (inputDescriptor->mRefCount > 0)) {
1384 status_t AudioPolicyManagerBase::dump(int fd)
1386 const size_t SIZE = 256;
1390 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1391 result.append(buffer);
1393 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1394 result.append(buffer);
1395 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1396 result.append(buffer);
1397 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1398 result.append(buffer);
1399 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbOutCardAndDevice.string());
1400 result.append(buffer);
1401 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1402 result.append(buffer);
1403 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1404 result.append(buffer);
1405 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1406 result.append(buffer);
1407 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1408 result.append(buffer);
1409 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1410 result.append(buffer);
1411 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1412 result.append(buffer);
1413 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1414 result.append(buffer);
1415 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1416 result.append(buffer);
1417 write(fd, result.string(), result.size());
1420 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1421 write(fd, buffer, strlen(buffer));
1422 for (size_t i = 0; i < mHwModules.size(); i++) {
1423 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
1424 write(fd, buffer, strlen(buffer));
1425 mHwModules[i]->dump(fd);
1428 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1429 write(fd, buffer, strlen(buffer));
1430 for (size_t i = 0; i < mOutputs.size(); i++) {
1431 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1432 write(fd, buffer, strlen(buffer));
1433 mOutputs.valueAt(i)->dump(fd);
1436 snprintf(buffer, SIZE, "\nInputs dump:\n");
1437 write(fd, buffer, strlen(buffer));
1438 for (size_t i = 0; i < mInputs.size(); i++) {
1439 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1440 write(fd, buffer, strlen(buffer));
1441 mInputs.valueAt(i)->dump(fd);
1444 snprintf(buffer, SIZE, "\nStreams dump:\n");
1445 write(fd, buffer, strlen(buffer));
1446 snprintf(buffer, SIZE,
1447 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1448 write(fd, buffer, strlen(buffer));
1449 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1450 snprintf(buffer, SIZE, " %02zu ", i);
1451 write(fd, buffer, strlen(buffer));
1452 mStreams[i].dump(fd);
1455 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1456 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1457 write(fd, buffer, strlen(buffer));
1459 snprintf(buffer, SIZE, "Registered effects:\n");
1460 write(fd, buffer, strlen(buffer));
1461 for (size_t i = 0; i < mEffects.size(); i++) {
1462 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1463 write(fd, buffer, strlen(buffer));
1464 mEffects.valueAt(i)->dump(fd);
1471 // This function checks for the parameters which can be offloaded.
1472 // This can be enhanced depending on the capability of the DSP and policy
1474 bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1476 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1477 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
1478 offloadInfo.sample_rate, offloadInfo.channel_mask,
1480 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1481 offloadInfo.has_video);
1483 // Check if offload has been disabled
1484 char propValue[PROPERTY_VALUE_MAX];
1485 if (property_get("audio.offload.disable", propValue, "0")) {
1486 if (atoi(propValue) != 0) {
1487 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1492 // Check if stream type is music, then only allow offload as of now.
1493 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1495 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1499 //TODO: enable audio offloading with video when ready
1500 if (offloadInfo.has_video)
1502 ALOGV("isOffloadSupported: has_video == true, returning false");
1506 //If duration is less than minimum value defined in property, return false
1507 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1508 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1509 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1512 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1513 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1517 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1518 // creating an offloaded track and tearing it down immediately after start when audioflinger
1519 // detects there is an active non offloadable effect.
1520 // FIXME: We should check the audio session here but we do not have it in this context.
1521 // This may prevent offloading in rare situations where effects are left active by apps
1522 // in the background.
1523 if (isNonOffloadableEffectEnabled()) {
1527 // See if there is a profile to support this.
1528 // AUDIO_DEVICE_NONE
1529 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1530 offloadInfo.sample_rate,
1532 offloadInfo.channel_mask,
1533 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1534 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1535 return (profile != NULL);
1538 // ----------------------------------------------------------------------------
1539 // AudioPolicyManagerBase
1540 // ----------------------------------------------------------------------------
1542 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1544 #ifdef AUDIO_POLICY_TEST
1546 #endif //AUDIO_POLICY_TEST
1547 mPrimaryOutput((audio_io_handle_t)0),
1548 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1549 mPhoneState(AudioSystem::MODE_NORMAL),
1550 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1551 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1552 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),
1553 mSpeakerDrcEnabled(false)
1555 mpClientInterface = clientInterface;
1557 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1558 mForceUse[i] = AudioSystem::FORCE_NONE;
1561 mA2dpDeviceAddress = String8("");
1562 mScoDeviceAddress = String8("");
1563 mUsbOutCardAndDevice = String8("");
1565 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1566 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1567 ALOGE("could not load audio policy configuration file, setting defaults");
1568 defaultAudioPolicyConfig();
1572 // must be done after reading the policy
1573 initializeVolumeCurves();
1575 // open all output streams needed to access attached devices
1576 for (size_t i = 0; i < mHwModules.size(); i++) {
1577 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1578 if (mHwModules[i]->mHandle == 0) {
1579 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1582 // open all output streams needed to access attached devices
1583 // except for direct output streams that are only opened when they are actually
1584 // required by an app.
1585 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1587 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1589 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1590 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1591 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1592 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1593 outProfile->mSupportedDevices);
1594 audio_io_handle_t output = mpClientInterface->openOutput(
1595 outProfile->mModule->mHandle,
1596 &outputDesc->mDevice,
1597 &outputDesc->mSamplingRate,
1598 &outputDesc->mFormat,
1599 &outputDesc->mChannelMask,
1600 &outputDesc->mLatency,
1601 outputDesc->mFlags);
1605 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1606 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1607 if (mPrimaryOutput == 0 &&
1608 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1609 mPrimaryOutput = output;
1611 addOutput(output, outputDesc);
1612 setOutputDevice(output,
1613 (audio_devices_t)(mDefaultOutputDevice &
1614 outProfile->mSupportedDevices),
1621 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1622 "Not output found for attached devices %08x",
1623 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1625 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1627 updateDevicesAndOutputs();
1629 #ifdef AUDIO_POLICY_TEST
1630 if (mPrimaryOutput != 0) {
1631 AudioParameter outputCmd = AudioParameter();
1632 outputCmd.addInt(String8("set_id"), 0);
1633 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1635 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1636 mTestSamplingRate = 44100;
1637 mTestFormat = AudioSystem::PCM_16_BIT;
1638 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1641 mDirectOutput = false;
1642 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1643 mTestOutputs[i] = 0;
1646 const size_t SIZE = 256;
1648 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1649 run(buffer, ANDROID_PRIORITY_AUDIO);
1651 #endif //AUDIO_POLICY_TEST
1654 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1656 #ifdef AUDIO_POLICY_TEST
1658 #endif //AUDIO_POLICY_TEST
1659 for (size_t i = 0; i < mOutputs.size(); i++) {
1660 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1661 delete mOutputs.valueAt(i);
1663 for (size_t i = 0; i < mInputs.size(); i++) {
1664 mpClientInterface->closeInput(mInputs.keyAt(i));
1665 delete mInputs.valueAt(i);
1667 for (size_t i = 0; i < mHwModules.size(); i++) {
1668 delete mHwModules[i];
1672 status_t AudioPolicyManagerBase::initCheck()
1674 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1677 #ifdef AUDIO_POLICY_TEST
1678 bool AudioPolicyManagerBase::threadLoop()
1680 ALOGV("entering threadLoop()");
1681 while (!exitPending())
1687 Mutex::Autolock _l(mLock);
1688 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1690 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1691 AudioParameter param = AudioParameter(command);
1693 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1695 ALOGV("Test command %s received", command.string());
1697 if (param.get(String8("target"), target) != NO_ERROR) {
1700 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1701 param.remove(String8("test_cmd_policy_output"));
1702 mCurOutput = valueInt;
1704 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1705 param.remove(String8("test_cmd_policy_direct"));
1706 if (value == "false") {
1707 mDirectOutput = false;
1708 } else if (value == "true") {
1709 mDirectOutput = true;
1712 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1713 param.remove(String8("test_cmd_policy_input"));
1714 mTestInput = valueInt;
1717 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1718 param.remove(String8("test_cmd_policy_format"));
1719 int format = AudioSystem::INVALID_FORMAT;
1720 if (value == "PCM 16 bits") {
1721 format = AudioSystem::PCM_16_BIT;
1722 } else if (value == "PCM 8 bits") {
1723 format = AudioSystem::PCM_8_BIT;
1724 } else if (value == "Compressed MP3") {
1725 format = AudioSystem::MP3;
1727 if (format != AudioSystem::INVALID_FORMAT) {
1728 if (target == "Manager") {
1729 mTestFormat = format;
1730 } else if (mTestOutputs[mCurOutput] != 0) {
1731 AudioParameter outputParam = AudioParameter();
1732 outputParam.addInt(String8("format"), format);
1733 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1737 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1738 param.remove(String8("test_cmd_policy_channels"));
1741 if (value == "Channels Stereo") {
1742 channels = AudioSystem::CHANNEL_OUT_STEREO;
1743 } else if (value == "Channels Mono") {
1744 channels = AudioSystem::CHANNEL_OUT_MONO;
1746 if (channels != 0) {
1747 if (target == "Manager") {
1748 mTestChannels = channels;
1749 } else if (mTestOutputs[mCurOutput] != 0) {
1750 AudioParameter outputParam = AudioParameter();
1751 outputParam.addInt(String8("channels"), channels);
1752 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1756 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1757 param.remove(String8("test_cmd_policy_sampleRate"));
1758 if (valueInt >= 0 && valueInt <= 96000) {
1759 int samplingRate = valueInt;
1760 if (target == "Manager") {
1761 mTestSamplingRate = samplingRate;
1762 } else if (mTestOutputs[mCurOutput] != 0) {
1763 AudioParameter outputParam = AudioParameter();
1764 outputParam.addInt(String8("sampling_rate"), samplingRate);
1765 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1770 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1771 param.remove(String8("test_cmd_policy_reopen"));
1773 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1774 mpClientInterface->closeOutput(mPrimaryOutput);
1776 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1778 delete mOutputs.valueFor(mPrimaryOutput);
1779 mOutputs.removeItem(mPrimaryOutput);
1781 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1782 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1783 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1784 &outputDesc->mDevice,
1785 &outputDesc->mSamplingRate,
1786 &outputDesc->mFormat,
1787 &outputDesc->mChannelMask,
1788 &outputDesc->mLatency,
1789 outputDesc->mFlags);
1790 if (mPrimaryOutput == 0) {
1791 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1792 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1794 AudioParameter outputCmd = AudioParameter();
1795 outputCmd.addInt(String8("set_id"), 0);
1796 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1797 addOutput(mPrimaryOutput, outputDesc);
1802 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1808 void AudioPolicyManagerBase::exit()
1811 AutoMutex _l(mLock);
1813 mWaitWorkCV.signal();
1815 requestExitAndWait();
1818 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1820 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1821 if (output == mTestOutputs[i]) return i;
1825 #endif //AUDIO_POLICY_TEST
1829 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1831 outputDesc->mId = id;
1832 mOutputs.add(id, outputDesc);
1835 void AudioPolicyManagerBase::addInput(audio_io_handle_t id, AudioInputDescriptor *inputDesc)
1837 inputDesc->mId = id;
1838 mInputs.add(id, inputDesc);
1841 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1842 AudioSystem::device_connection_state state,
1843 SortedVector<audio_io_handle_t>& outputs,
1844 const String8 paramStr)
1846 AudioOutputDescriptor *desc;
1848 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1849 // first list already open outputs that can be routed to this device
1850 for (size_t i = 0; i < mOutputs.size(); i++) {
1851 desc = mOutputs.valueAt(i);
1852 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1853 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1854 outputs.add(mOutputs.keyAt(i));
1857 // then look for output profiles that can be routed to this device
1858 SortedVector<IOProfile *> profiles;
1859 for (size_t i = 0; i < mHwModules.size(); i++)
1861 if (mHwModules[i]->mHandle == 0) {
1864 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1866 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1867 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
1868 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1873 if (profiles.isEmpty() && outputs.isEmpty()) {
1874 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1878 // open outputs for matching profiles if needed. Direct outputs are also opened to
1879 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1880 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1881 IOProfile *profile = profiles[profile_index];
1883 // nothing to do if one output is already opened for this profile
1885 for (j = 0; j < mOutputs.size(); j++) {
1886 desc = mOutputs.valueAt(j);
1887 if (!desc->isDuplicated() && desc->mProfile == profile) {
1891 if (j != mOutputs.size()) {
1895 ALOGV("opening output for device %08x with params %s", device, paramStr.string());
1896 desc = new AudioOutputDescriptor(profile);
1897 desc->mDevice = device;
1898 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1899 offloadInfo.sample_rate = desc->mSamplingRate;
1900 offloadInfo.format = desc->mFormat;
1901 offloadInfo.channel_mask = desc->mChannelMask;
1903 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1905 &desc->mSamplingRate,
1907 &desc->mChannelMask,
1912 if (!paramStr.isEmpty()) {
1913 // Here is where the out_set_parameters() for card & device gets called
1914 mpClientInterface->setParameters(output, paramStr);
1917 // Here is where we step through and resolve any "dynamic" fields
1920 if (profile->mSamplingRates[0] == 0) {
1921 reply = mpClientInterface->getParameters(output,
1922 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1923 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1925 value = strpbrk((char *)reply.string(), "=");
1926 if (value != NULL) {
1927 loadSamplingRates(value + 1, profile);
1930 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
1931 reply = mpClientInterface->getParameters(output,
1932 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1933 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1935 value = strpbrk((char *)reply.string(), "=");
1936 if (value != NULL) {
1937 loadFormats(value + 1, profile);
1940 if (profile->mChannelMasks[0] == 0) {
1941 reply = mpClientInterface->getParameters(output,
1942 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1943 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1945 value = strpbrk((char *)reply.string(), "=");
1946 if (value != NULL) {
1947 loadOutChannels(value + 1, profile);
1950 if (((profile->mSamplingRates[0] == 0) &&
1951 (profile->mSamplingRates.size() < 2)) ||
1952 ((profile->mFormats[0] == 0) &&
1953 (profile->mFormats.size() < 2)) ||
1954 ((profile->mChannelMasks[0] == 0) &&
1955 (profile->mChannelMasks.size() < 2))) {
1956 ALOGW("checkOutputsForDevice() direct output missing param");
1957 mpClientInterface->closeOutput(output);
1959 } else if (profile->mSamplingRates[0] == 0) {
1960 mpClientInterface->closeOutput(output);
1961 desc->mSamplingRate = profile->mSamplingRates[1];
1962 offloadInfo.sample_rate = desc->mSamplingRate;
1963 output = mpClientInterface->openOutput(
1964 profile->mModule->mHandle,
1966 &desc->mSamplingRate,
1968 &desc->mChannelMask,
1975 addOutput(output, desc);
1976 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
1977 audio_io_handle_t duplicatedOutput = 0;
1979 // set initial stream volume for device
1980 applyStreamVolumes(output, device, 0, true);
1982 //TODO: configure audio effect output stage here
1984 // open a duplicating output thread for the new output and the primary output
1985 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1987 if (duplicatedOutput != 0) {
1988 // add duplicated output descriptor
1989 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1990 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1991 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1992 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1993 dupOutputDesc->mFormat = desc->mFormat;
1994 dupOutputDesc->mChannelMask = desc->mChannelMask;
1995 dupOutputDesc->mLatency = desc->mLatency;
1996 addOutput(duplicatedOutput, dupOutputDesc);
1997 applyStreamVolumes(duplicatedOutput, device, 0, true);
1999 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2000 mPrimaryOutput, output);
2001 mpClientInterface->closeOutput(output);
2002 mOutputs.removeItem(output);
2009 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2011 profiles.removeAt(profile_index);
2014 outputs.add(output);
2015 ALOGV("checkOutputsForDevice(): adding output %d", output);
2019 if (profiles.isEmpty()) {
2020 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2023 } else { // Disconnect
2024 // check if one opened output is not needed any more after disconnecting one device
2025 for (size_t i = 0; i < mOutputs.size(); i++) {
2026 desc = mOutputs.valueAt(i);
2027 if (!desc->isDuplicated() &&
2028 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
2029 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2030 outputs.add(mOutputs.keyAt(i));
2033 // Clear any profiles associated with the disconnected device.
2034 for (size_t i = 0; i < mHwModules.size(); i++)
2036 if (mHwModules[i]->mHandle == 0) {
2039 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2041 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
2042 if (profile->mSupportedDevices & device) {
2043 ALOGV("checkOutputsForDevice(): clearing direct output profile %zu on module %zu",
2045 if (profile->mSamplingRates[0] == 0) {
2046 profile->mSamplingRates.clear();
2047 profile->mSamplingRates.add(0);
2049 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2050 profile->mFormats.clear();
2051 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2053 if (profile->mChannelMasks[0] == 0) {
2054 profile->mChannelMasks.clear();
2055 profile->mChannelMasks.add(0);
2064 status_t AudioPolicyManagerBase::checkInputsForDevice(audio_devices_t device,
2065 AudioSystem::device_connection_state state,
2066 SortedVector<audio_io_handle_t>& inputs,
2067 const String8 paramStr)
2069 AudioInputDescriptor *desc;
2070 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
2071 // first list already open inputs that can be routed to this device
2072 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2073 desc = mInputs.valueAt(input_index);
2074 if (desc->mProfile->mSupportedDevices & (device & ~AUDIO_DEVICE_BIT_IN)) {
2075 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2076 inputs.add(mInputs.keyAt(input_index));
2080 // then look for input profiles that can be routed to this device
2081 SortedVector<IOProfile *> profiles;
2082 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
2084 if (mHwModules[module_index]->mHandle == 0) {
2087 for (size_t profile_index = 0;
2088 profile_index < mHwModules[module_index]->mInputProfiles.size();
2091 if (mHwModules[module_index]->mInputProfiles[profile_index]->mSupportedDevices
2092 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2093 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2094 profile_index, module_index);
2095 profiles.add(mHwModules[module_index]->mInputProfiles[profile_index]);
2100 if (profiles.isEmpty() && inputs.isEmpty()) {
2101 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2105 // open inputs for matching profiles if needed. Direct inputs are also opened to
2106 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2107 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2109 IOProfile *profile = profiles[profile_index];
2110 // nothing to do if one input is already opened for this profile
2112 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2113 desc = mInputs.valueAt(input_index);
2114 if (desc->mProfile == profile) {
2118 if (input_index != mInputs.size()) {
2122 ALOGV("opening input for device 0x%X with params %s", device, paramStr.string());
2123 desc = new AudioInputDescriptor(profile);
2124 desc->mDevice = device;
2126 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2128 &desc->mSamplingRate,
2130 &desc->mChannelMask);
2133 if (!paramStr.isEmpty()) {
2134 mpClientInterface->setParameters(input, paramStr);
2137 // Here is where we step through and resolve any "dynamic" fields
2140 if (profile->mSamplingRates[0] == 0) {
2141 reply = mpClientInterface->getParameters(input,
2142 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2143 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2145 value = strpbrk((char *)reply.string(), "=");
2146 if (value != NULL) {
2147 loadSamplingRates(value + 1, profile);
2150 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2151 reply = mpClientInterface->getParameters(input,
2152 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2153 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2154 value = strpbrk((char *)reply.string(), "=");
2155 if (value != NULL) {
2156 loadFormats(value + 1, profile);
2159 if (profile->mChannelMasks[0] == 0) {
2160 reply = mpClientInterface->getParameters(input,
2161 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2162 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2164 value = strpbrk((char *)reply.string(), "=");
2165 if (value != NULL) {
2166 loadInChannels(value + 1, profile);
2169 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2170 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2171 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2172 ALOGW("checkInputsForDevice() direct input missing param");
2173 mpClientInterface->closeInput(input);
2178 addInput(input, desc);
2180 } // endif input != 0
2183 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2185 profiles.removeAt(profile_index);
2189 ALOGV("checkInputsForDevice(): adding input %d", input);
2191 } // end scan profiles
2193 if (profiles.isEmpty()) {
2194 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2199 // check if one opened input is not needed any more after disconnecting one device
2200 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2201 desc = mInputs.valueAt(input_index);
2202 if (!(desc->mProfile->mSupportedDevices & mAvailableInputDevices)) {
2203 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2204 mInputs.keyAt(input_index));
2205 inputs.add(mInputs.keyAt(input_index));
2208 // Clear any profiles associated with the disconnected device.
2209 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
2211 if (mHwModules[module_index]->mHandle == 0) {
2214 for (size_t profile_index = 0;
2215 profile_index < mHwModules[module_index]->mInputProfiles.size();
2218 IOProfile *profile = mHwModules[module_index]->mInputProfiles[profile_index];
2219 if (profile->mSupportedDevices & device) {
2220 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2221 profile_index, module_index);
2222 if (profile->mSamplingRates[0] == 0) {
2223 profile->mSamplingRates.clear();
2224 profile->mSamplingRates.add(0);
2226 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2227 profile->mFormats.clear();
2228 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2230 if (profile->mChannelMasks[0] == 0) {
2231 profile->mChannelMasks.clear();
2232 profile->mChannelMasks.add(0);
2242 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
2244 ALOGV("closeOutput(%d)", output);
2246 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2247 if (outputDesc == NULL) {
2248 ALOGW("closeOutput() unknown output %d", output);
2252 // look for duplicated outputs connected to the output being removed.
2253 for (size_t i = 0; i < mOutputs.size(); i++) {
2254 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2255 if (dupOutputDesc->isDuplicated() &&
2256 (dupOutputDesc->mOutput1 == outputDesc ||
2257 dupOutputDesc->mOutput2 == outputDesc)) {
2258 AudioOutputDescriptor *outputDesc2;
2259 if (dupOutputDesc->mOutput1 == outputDesc) {
2260 outputDesc2 = dupOutputDesc->mOutput2;
2262 outputDesc2 = dupOutputDesc->mOutput1;
2264 // As all active tracks on duplicated output will be deleted,
2265 // and as they were also referenced on the other output, the reference
2266 // count for their stream type must be adjusted accordingly on
2267 // the other output.
2268 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
2269 int refCount = dupOutputDesc->mRefCount[j];
2270 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
2272 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2273 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2275 mpClientInterface->closeOutput(duplicatedOutput);
2276 delete mOutputs.valueFor(duplicatedOutput);
2277 mOutputs.removeItem(duplicatedOutput);
2281 AudioParameter param;
2282 param.add(String8("closing"), String8("true"));
2283 mpClientInterface->setParameters(output, param.toString());
2285 mpClientInterface->closeOutput(output);
2287 mOutputs.removeItem(output);
2288 mPreviousOutputs = mOutputs;
2291 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
2292 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2294 SortedVector<audio_io_handle_t> outputs;
2296 ALOGVV("getOutputsForDevice() device %04x", device);
2297 for (size_t i = 0; i < openOutputs.size(); i++) {
2298 ALOGVV("output %d isDuplicated=%d device=%04x",
2299 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2300 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2301 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2302 outputs.add(openOutputs.keyAt(i));
2308 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2309 SortedVector<audio_io_handle_t>& outputs2)
2311 if (outputs1.size() != outputs2.size()) {
2314 for (size_t i = 0; i < outputs1.size(); i++) {
2315 if (outputs1[i] != outputs2[i]) {
2322 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
2324 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2325 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2326 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2327 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2329 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2330 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2331 strategy, srcOutputs[0], dstOutputs[0]);
2332 // mute strategy while moving tracks from one output to another
2333 for (size_t i = 0; i < srcOutputs.size(); i++) {
2334 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2335 if (desc->isStrategyActive(strategy)) {
2336 setStrategyMute(strategy, true, srcOutputs[i]);
2337 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2341 // Move effects associated to this strategy from previous output to new output
2342 if (strategy == STRATEGY_MEDIA) {
2343 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2344 SortedVector<audio_io_handle_t> moved;
2345 for (size_t i = 0; i < mEffects.size(); i++) {
2346 EffectDescriptor *desc = mEffects.valueAt(i);
2347 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2348 desc->mIo != fxOutput) {
2349 if (moved.indexOf(desc->mIo) < 0) {
2350 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2351 mEffects.keyAt(i), fxOutput);
2352 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2354 moved.add(desc->mIo);
2356 desc->mIo = fxOutput;
2360 // Move tracks associated to this strategy from previous output to new output
2361 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2362 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2363 mpClientInterface->invalidateStream((AudioSystem::stream_type)i);
2369 void AudioPolicyManagerBase::checkOutputForAllStrategies()
2371 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2372 checkOutputForStrategy(STRATEGY_PHONE);
2373 checkOutputForStrategy(STRATEGY_SONIFICATION);
2374 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2375 checkOutputForStrategy(STRATEGY_MEDIA);
2376 checkOutputForStrategy(STRATEGY_DTMF);
2379 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2385 for (size_t i = 0; i < mOutputs.size(); i++) {
2386 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2387 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2388 return mOutputs.keyAt(i);
2395 void AudioPolicyManagerBase::checkA2dpSuspend()
2400 audio_io_handle_t a2dpOutput = getA2dpOutput();
2401 if (a2dpOutput == 0) {
2405 // suspend A2DP output if:
2406 // (NOT already suspended) &&
2407 // ((SCO device is connected &&
2408 // (forced usage for communication || for record is SCO))) ||
2409 // (phone state is ringing || in call)
2411 // restore A2DP output if:
2412 // (Already suspended) &&
2413 // ((SCO device is NOT connected ||
2414 // (forced usage NOT for communication && NOT for record is SCO))) &&
2415 // (phone state is NOT ringing && NOT in call)
2417 if (mA2dpSuspended) {
2418 if (((mScoDeviceAddress == "") ||
2419 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2420 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2421 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2422 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2424 mpClientInterface->restoreOutput(a2dpOutput);
2425 mA2dpSuspended = false;
2428 if (((mScoDeviceAddress != "") &&
2429 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2430 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2431 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2432 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2434 mpClientInterface->suspendOutput(a2dpOutput);
2435 mA2dpSuspended = true;
2440 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2442 audio_devices_t device = AUDIO_DEVICE_NONE;
2444 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2445 // check the following by order of priority to request a routing change if necessary:
2446 // 1: the strategy enforced audible is active on the output:
2447 // use device for strategy enforced audible
2448 // 2: we are in call or the strategy phone is active on the output:
2449 // use device for strategy phone
2450 // 3: the strategy sonification is active on the output:
2451 // use device for strategy sonification
2452 // 4: the strategy "respectful" sonification is active on the output:
2453 // use device for strategy "respectful" sonification
2454 // 5: the strategy media is active on the output:
2455 // use device for strategy media
2456 // 6: the strategy DTMF is active on the output:
2457 // use device for strategy DTMF
2458 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2459 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2460 } else if (isInCall() ||
2461 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2462 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2463 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2464 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2465 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2466 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2467 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2468 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2469 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2470 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2473 ALOGV("getNewDevice() selected device %x", device);
2477 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2478 return (uint32_t)getStrategy(stream);
2481 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2482 audio_devices_t devices;
2483 // By checking the range of stream before calling getStrategy, we avoid
2484 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2485 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2486 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2487 devices = AUDIO_DEVICE_NONE;
2489 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2490 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2495 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2496 AudioSystem::stream_type stream) {
2497 // stream to strategy mapping
2499 case AudioSystem::VOICE_CALL:
2500 case AudioSystem::BLUETOOTH_SCO:
2501 return STRATEGY_PHONE;
2502 case AudioSystem::RING:
2503 case AudioSystem::ALARM:
2504 return STRATEGY_SONIFICATION;
2505 case AudioSystem::NOTIFICATION:
2506 return STRATEGY_SONIFICATION_RESPECTFUL;
2507 case AudioSystem::DTMF:
2508 return STRATEGY_DTMF;
2510 ALOGE("unknown stream type");
2511 case AudioSystem::SYSTEM:
2512 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2513 // while key clicks are played produces a poor result
2514 case AudioSystem::TTS:
2515 case AudioSystem::MUSIC:
2516 return STRATEGY_MEDIA;
2517 case AudioSystem::ENFORCED_AUDIBLE:
2518 return STRATEGY_ENFORCED_AUDIBLE;
2522 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2524 case AudioSystem::MUSIC:
2525 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2526 updateDevicesAndOutputs();
2533 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2536 uint32_t device = AUDIO_DEVICE_NONE;
2539 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2540 strategy, mDeviceForStrategy[strategy]);
2541 return mDeviceForStrategy[strategy];
2546 case STRATEGY_SONIFICATION_RESPECTFUL:
2548 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2549 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2550 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2551 // while media is playing on a remote device, use the the sonification behavior.
2552 // Note that we test this usecase before testing if media is playing because
2553 // the isStreamActive() method only informs about the activity of a stream, not
2554 // if it's for local playback. Note also that we use the same delay between both tests
2555 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2556 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2557 // while media is playing (or has recently played), use the same device
2558 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2560 // when media is not playing anymore, fall back on the sonification behavior
2561 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2568 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2569 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2572 // when in call, DTMF and PHONE strategies follow the same rules
2575 case STRATEGY_PHONE:
2576 // for phone strategy, we first consider the forced use and then the available devices by order
2578 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2579 case AudioSystem::FORCE_BT_SCO:
2580 if (!isInCall() || strategy != STRATEGY_DTMF) {
2581 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2584 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2586 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2588 // if SCO device is requested but no SCO device is available, fall back to default case
2591 default: // FORCE_NONE
2592 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2593 if (mHasA2dp && !isInCall() &&
2594 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2595 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2596 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2598 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2601 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2603 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2605 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2606 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2608 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2610 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2612 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2614 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2617 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2619 device = mDefaultOutputDevice;
2620 if (device == AUDIO_DEVICE_NONE) {
2621 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2625 case AudioSystem::FORCE_SPEAKER:
2626 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2627 // A2DP speaker when forcing to speaker output
2628 if (mHasA2dp && !isInCall() &&
2629 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2630 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2631 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2634 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2635 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2637 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2639 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2641 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2643 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2646 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2648 device = mDefaultOutputDevice;
2649 if (device == AUDIO_DEVICE_NONE) {
2650 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2656 case STRATEGY_SONIFICATION:
2658 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2659 // handleIncallSonification().
2661 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2666 case STRATEGY_ENFORCED_AUDIBLE:
2667 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2669 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2670 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2672 if ((strategy == STRATEGY_SONIFICATION) ||
2673 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2674 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2675 if (device == AUDIO_DEVICE_NONE) {
2676 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2679 // The second device used for sonification is the same as the device used by media strategy
2682 case STRATEGY_MEDIA: {
2683 uint32_t device2 = AUDIO_DEVICE_NONE;
2684 if (strategy != STRATEGY_SONIFICATION) {
2685 // no sonification on remote submix (e.g. WFD)
2686 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2688 if ((device2 == AUDIO_DEVICE_NONE) &&
2689 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2690 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2691 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2692 if (device2 == AUDIO_DEVICE_NONE) {
2693 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2695 if (device2 == AUDIO_DEVICE_NONE) {
2696 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2699 if (device2 == AUDIO_DEVICE_NONE) {
2700 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2702 if (device2 == AUDIO_DEVICE_NONE) {
2703 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2705 if (device2 == AUDIO_DEVICE_NONE) {
2706 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2708 if (device2 == AUDIO_DEVICE_NONE) {
2709 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2711 if (device2 == AUDIO_DEVICE_NONE) {
2712 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2714 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2715 // no sonification on aux digital (e.g. HDMI)
2716 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2718 if ((device2 == AUDIO_DEVICE_NONE) &&
2719 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2720 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2722 if (device2 == AUDIO_DEVICE_NONE) {
2723 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2726 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2727 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2730 device = mDefaultOutputDevice;
2731 if (device == AUDIO_DEVICE_NONE) {
2732 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2737 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2741 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2745 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2747 for (int i = 0; i < NUM_STRATEGIES; i++) {
2748 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2750 mPreviousOutputs = mOutputs;
2753 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2754 audio_devices_t prevDevice,
2757 // mute/unmute strategies using an incompatible device combination
2758 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2759 // if unmuting, unmute only after the specified delay
2760 if (outputDesc->isDuplicated()) {
2764 uint32_t muteWaitMs = 0;
2765 audio_devices_t device = outputDesc->device();
2766 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2767 // temporary mute output if device selection changes to avoid volume bursts due to
2768 // different per device volumes
2769 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2771 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2772 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2773 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2774 bool doMute = false;
2776 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2778 outputDesc->mStrategyMutedByDevice[i] = true;
2779 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2781 outputDesc->mStrategyMutedByDevice[i] = false;
2783 if (doMute || tempMute) {
2784 for (size_t j = 0; j < mOutputs.size(); j++) {
2785 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2786 // skip output if it does not share any device with current output
2787 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2788 == AUDIO_DEVICE_NONE) {
2791 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2792 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2793 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2794 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2795 if (desc->isStrategyActive((routing_strategy)i)) {
2796 // do tempMute only for current output
2797 if (tempMute && (desc == outputDesc)) {
2798 setStrategyMute((routing_strategy)i, true, curOutput);
2799 setStrategyMute((routing_strategy)i, false, curOutput,
2800 desc->latency() * 2, device);
2802 if ((tempMute && (desc == outputDesc)) || mute) {
2803 if (muteWaitMs < desc->latency()) {
2804 muteWaitMs = desc->latency();
2812 // FIXME: should not need to double latency if volume could be applied immediately by the
2813 // audioflinger mixer. We must account for the delay between now and the next time
2814 // the audioflinger thread for this output will process a buffer (which corresponds to
2815 // one buffer size, usually 1/2 or 1/4 of the latency).
2817 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2818 if (muteWaitMs > delayMs) {
2819 muteWaitMs -= delayMs;
2820 usleep(muteWaitMs * 1000);
2826 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2827 audio_devices_t device,
2831 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2832 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2833 AudioParameter param;
2834 uint32_t muteWaitMs;
2836 if (outputDesc->isDuplicated()) {
2837 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2838 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2841 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2843 if ((device != AUDIO_DEVICE_NONE) &&
2844 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2848 // filter devices according to output selected
2849 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2851 audio_devices_t prevDevice = outputDesc->mDevice;
2853 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2855 if (device != AUDIO_DEVICE_NONE) {
2856 outputDesc->mDevice = device;
2858 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2860 // Do not change the routing if:
2861 // - the requested device is AUDIO_DEVICE_NONE
2862 // - the requested device is the same as current device and force is not specified.
2863 // Doing this check here allows the caller to call setOutputDevice() without conditions
2864 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2865 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2869 ALOGV("setOutputDevice() changing device");
2871 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2872 mpClientInterface->setParameters(output, param.toString(), delayMs);
2874 // update stream volumes according to new device
2875 applyStreamVolumes(output, device, delayMs);
2880 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2881 uint32_t samplingRate,
2882 audio_format_t format,
2883 audio_channel_mask_t channelMask)
2885 // Choose an input profile based on the requested capture parameters: select the first available
2886 // profile supporting all requested parameters.
2887 for (size_t i = 0; i < mHwModules.size(); i++)
2889 if (mHwModules[i]->mHandle == 0) {
2892 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2894 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2896 if (profile->isCompatibleProfile(device, samplingRate, format,
2897 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
2905 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2907 uint32_t device = AUDIO_DEVICE_NONE;
2909 switch (inputSource) {
2910 case AUDIO_SOURCE_VOICE_UPLINK:
2911 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2912 device = AUDIO_DEVICE_IN_VOICE_CALL;
2917 case AUDIO_SOURCE_DEFAULT:
2918 case AUDIO_SOURCE_MIC:
2919 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
2920 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
2925 case AUDIO_SOURCE_VOICE_RECOGNITION:
2926 case AUDIO_SOURCE_HOTWORD:
2927 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2928 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2929 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2930 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2931 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2932 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2933 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_USB_DEVICE) {
2934 device = AUDIO_DEVICE_IN_USB_DEVICE;
2935 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2936 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2939 case AUDIO_SOURCE_CAMCORDER:
2940 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2941 device = AUDIO_DEVICE_IN_BACK_MIC;
2942 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2943 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2946 case AUDIO_SOURCE_VOICE_DOWNLINK:
2947 case AUDIO_SOURCE_VOICE_CALL:
2948 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2949 device = AUDIO_DEVICE_IN_VOICE_CALL;
2952 case AUDIO_SOURCE_REMOTE_SUBMIX:
2953 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2954 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2958 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2961 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2965 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2967 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2968 device &= ~AUDIO_DEVICE_BIT_IN;
2969 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2975 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2977 for (size_t i = 0; i < mInputs.size(); i++) {
2978 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2979 if ((input_descriptor->mRefCount > 0)
2980 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2981 return mInputs.keyAt(i);
2988 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2990 if (device == AUDIO_DEVICE_NONE) {
2991 // this happens when forcing a route update and no track is active on an output.
2992 // In this case the returned category is not important.
2993 device = AUDIO_DEVICE_OUT_SPEAKER;
2994 } else if (AudioSystem::popCount(device) > 1) {
2995 // Multiple device selection is either:
2996 // - speaker + one other device: give priority to speaker in this case.
2997 // - one A2DP device + another device: happens with duplicated output. In this case
2998 // retain the device on the A2DP output as the other must not correspond to an active
2999 // selection if not the speaker.
3000 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3001 device = AUDIO_DEVICE_OUT_SPEAKER;
3003 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3007 ALOGW_IF(AudioSystem::popCount(device) != 1,
3008 "getDeviceForVolume() invalid device combination: %08x",
3014 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
3016 switch(getDeviceForVolume(device)) {
3017 case AUDIO_DEVICE_OUT_EARPIECE:
3018 return DEVICE_CATEGORY_EARPIECE;
3019 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3020 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3021 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3022 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3023 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3024 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3025 return DEVICE_CATEGORY_HEADSET;
3026 case AUDIO_DEVICE_OUT_SPEAKER:
3027 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3028 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3029 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3030 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3031 case AUDIO_DEVICE_OUT_USB_DEVICE:
3032 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3034 return DEVICE_CATEGORY_SPEAKER;
3038 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
3041 device_category deviceCategory = getDeviceCategory(device);
3042 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3044 // the volume index in the UI is relative to the min and max volume indices for this stream type
3045 int nbSteps = 1 + curve[VOLMAX].mIndex -
3046 curve[VOLMIN].mIndex;
3047 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3048 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3050 // find what part of the curve this index volume belongs to, or if it's out of bounds
3052 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3054 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3056 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3058 } else if (volIdx <= curve[VOLMAX].mIndex) {
3060 } else { // out of bounds
3064 // linear interpolation in the attenuation table in dB
3065 float decibels = curve[segment].mDBAttenuation +
3066 ((float)(volIdx - curve[segment].mIndex)) *
3067 ( (curve[segment+1].mDBAttenuation -
3068 curve[segment].mDBAttenuation) /
3069 ((float)(curve[segment+1].mIndex -
3070 curve[segment].mIndex)) );
3072 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3074 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3075 curve[segment].mIndex, volIdx,
3076 curve[segment+1].mIndex,
3077 curve[segment].mDBAttenuation,
3079 curve[segment+1].mDBAttenuation,
3082 return amplification;
3085 const AudioPolicyManagerBase::VolumeCurvePoint
3086 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3087 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3090 const AudioPolicyManagerBase::VolumeCurvePoint
3091 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3092 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3095 const AudioPolicyManagerBase::VolumeCurvePoint
3096 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3097 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3100 const AudioPolicyManagerBase::VolumeCurvePoint
3101 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3102 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3105 const AudioPolicyManagerBase::VolumeCurvePoint
3106 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
3107 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3110 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3111 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3112 // AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3113 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3115 const AudioPolicyManagerBase::VolumeCurvePoint
3116 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3117 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3120 const AudioPolicyManagerBase::VolumeCurvePoint
3121 AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
3122 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3125 const AudioPolicyManagerBase::VolumeCurvePoint
3126 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3127 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3130 const AudioPolicyManagerBase::VolumeCurvePoint
3131 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3132 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3135 const AudioPolicyManagerBase::VolumeCurvePoint
3136 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3137 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3140 const AudioPolicyManagerBase::VolumeCurvePoint
3141 *AudioPolicyManagerBase::sVolumeProfiles[AudioSystem::NUM_STREAM_TYPES]
3142 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
3143 { // AUDIO_STREAM_VOICE_CALL
3144 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3145 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3146 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3148 { // AUDIO_STREAM_SYSTEM
3149 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3150 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3151 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3153 { // AUDIO_STREAM_RING
3154 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3155 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3156 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3158 { // AUDIO_STREAM_MUSIC
3159 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3160 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3161 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3163 { // AUDIO_STREAM_ALARM
3164 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3165 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3166 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3168 { // AUDIO_STREAM_NOTIFICATION
3169 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3170 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3171 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3173 { // AUDIO_STREAM_BLUETOOTH_SCO
3174 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3175 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3176 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3178 { // AUDIO_STREAM_ENFORCED_AUDIBLE
3179 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3180 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3181 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3183 { // AUDIO_STREAM_DTMF
3184 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3185 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3186 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3188 { // AUDIO_STREAM_TTS
3189 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3190 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3191 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3195 void AudioPolicyManagerBase::initializeVolumeCurves()
3197 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3198 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
3199 mStreams[i].mVolumeCurve[j] =
3200 sVolumeProfiles[i][j];
3204 // Check availability of DRC on speaker path: if available, override some of the speaker curves
3205 if (mSpeakerDrcEnabled) {
3206 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3207 sDefaultSystemVolumeCurveDrc;
3208 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3209 sSpeakerSonificationVolumeCurveDrc;
3210 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3211 sSpeakerSonificationVolumeCurveDrc;
3212 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3213 sSpeakerSonificationVolumeCurveDrc;
3217 float AudioPolicyManagerBase::computeVolume(int stream,
3219 audio_io_handle_t output,
3220 audio_devices_t device)
3223 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3224 StreamDescriptor &streamDesc = mStreams[stream];
3226 if (device == AUDIO_DEVICE_NONE) {
3227 device = outputDesc->device();
3230 // if volume is not 0 (not muted), force media volume to max on digital output
3231 if (stream == AudioSystem::MUSIC &&
3232 index != mStreams[stream].mIndexMin &&
3233 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3234 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
3238 volume = volIndexToAmpl(device, streamDesc, index);
3240 // if a headset is connected, apply the following rules to ring tones and notifications
3241 // to avoid sound level bursts in user's ears:
3242 // - always attenuate ring tones and notifications volume by 6dB
3243 // - if music is playing, always limit the volume to current music volume,
3244 // with a minimum threshold at -36dB so that notification is always perceived.
3245 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3246 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3247 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3248 AUDIO_DEVICE_OUT_WIRED_HEADSET |
3249 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3250 ((stream_strategy == STRATEGY_SONIFICATION)
3251 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
3252 || (stream == AudioSystem::SYSTEM)
3253 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
3254 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
3255 streamDesc.mCanBeMuted) {
3256 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3257 // when the phone is ringing we must consider that music could have been paused just before
3258 // by the music application and behave as if music was active if the last music track was
3260 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
3261 mLimitRingtoneVolume) {
3262 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
3263 float musicVol = computeVolume(AudioSystem::MUSIC,
3264 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
3267 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3268 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3269 if (volume > minVol) {
3271 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3279 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
3281 audio_io_handle_t output,
3282 audio_devices_t device,
3287 // do not change actual stream volume if the stream is muted
3288 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3289 ALOGVV("checkAndSetVolume() stream %d muted count %d",
3290 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3294 // do not change in call volume if bluetooth is connected and vice versa
3295 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
3296 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
3297 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
3298 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
3299 return INVALID_OPERATION;
3302 float volume = computeVolume(stream, index, output, device);
3303 // We actually change the volume if:
3304 // - the float value returned by computeVolume() changed
3305 // - the force flag is set
3306 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3308 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3309 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3310 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3312 if (stream == AudioSystem::BLUETOOTH_SCO) {
3313 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
3315 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
3318 if (stream == AudioSystem::VOICE_CALL ||
3319 stream == AudioSystem::BLUETOOTH_SCO) {
3321 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3322 if (stream == AudioSystem::VOICE_CALL) {
3323 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3328 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3329 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3330 mLastVoiceVolume = voiceVolume;
3337 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
3338 audio_devices_t device,
3342 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3344 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3345 checkAndSetVolume(stream,
3346 mStreams[stream].getVolumeIndex(device),
3354 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
3356 audio_io_handle_t output,
3358 audio_devices_t device)
3360 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3361 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3362 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3363 setStreamMute(stream, on, output, delayMs, device);
3368 void AudioPolicyManagerBase::setStreamMute(int stream,
3370 audio_io_handle_t output,
3372 audio_devices_t device)
3374 StreamDescriptor &streamDesc = mStreams[stream];
3375 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3376 if (device == AUDIO_DEVICE_NONE) {
3377 device = outputDesc->device();
3380 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3381 stream, on, output, outputDesc->mMuteCount[stream], device);
3384 if (outputDesc->mMuteCount[stream] == 0) {
3385 if (streamDesc.mCanBeMuted &&
3386 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3387 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3388 checkAndSetVolume(stream, 0, output, device, delayMs);
3391 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3392 outputDesc->mMuteCount[stream]++;
3394 if (outputDesc->mMuteCount[stream] == 0) {
3395 ALOGV("setStreamMute() unmuting non muted stream!");
3398 if (--outputDesc->mMuteCount[stream] == 0) {
3399 checkAndSetVolume(stream,
3400 streamDesc.getVolumeIndex(device),
3408 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3410 // if the stream pertains to sonification strategy and we are in call we must
3411 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3412 // in the device used for phone strategy and play the tone if the selected device does not
3413 // interfere with the device used for phone strategy
3414 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3415 // many times as there are active tracks on the output
3416 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3417 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3418 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3419 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3420 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3421 stream, starting, outputDesc->mDevice, stateChange);
3422 if (outputDesc->mRefCount[stream]) {
3425 muteCount = outputDesc->mRefCount[stream];
3427 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3428 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3429 for (int i = 0; i < muteCount; i++) {
3430 setStreamMute(stream, starting, mPrimaryOutput);
3433 ALOGV("handleIncallSonification() high visibility");
3434 if (outputDesc->device() &
3435 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3436 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3437 for (int i = 0; i < muteCount; i++) {
3438 setStreamMute(stream, starting, mPrimaryOutput);
3442 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3444 mpClientInterface->stopTone();
3451 bool AudioPolicyManagerBase::isInCall()
3453 return isStateInCall(mPhoneState);
3456 bool AudioPolicyManagerBase::isStateInCall(int state) {
3457 return ((state == AudioSystem::MODE_IN_CALL) ||
3458 (state == AudioSystem::MODE_IN_COMMUNICATION));
3461 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3463 return MAX_EFFECTS_CPU_LOAD;
3466 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3468 return MAX_EFFECTS_MEMORY;
3471 // --- AudioOutputDescriptor class implementation
3473 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3474 const IOProfile *profile)
3475 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3476 mChannelMask(0), mLatency(0),
3477 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3478 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3480 // clear usage count for all stream types
3481 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3483 mCurVolume[i] = -1.0;
3487 for (int i = 0; i < NUM_STRATEGIES; i++) {
3488 mStrategyMutedByDevice[i] = false;
3490 if (profile != NULL) {
3491 mSamplingRate = profile->mSamplingRates[0];
3492 mFormat = profile->mFormats[0];
3493 mChannelMask = profile->mChannelMasks[0];
3494 mFlags = profile->mFlags;
3498 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3500 if (isDuplicated()) {
3501 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3507 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3509 if (isDuplicated()) {
3510 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3516 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3517 const AudioOutputDescriptor *outputDesc)
3519 if (isDuplicated()) {
3520 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3521 } else if (outputDesc->isDuplicated()){
3522 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3524 return (mProfile->mModule == outputDesc->mProfile->mModule);
3528 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3530 // forward usage count change to attached outputs
3531 if (isDuplicated()) {
3532 mOutput1->changeRefCount(stream, delta);
3533 mOutput2->changeRefCount(stream, delta);
3535 if ((delta + (int)mRefCount[stream]) < 0) {
3536 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3537 mRefCount[stream] = 0;
3540 mRefCount[stream] += delta;
3541 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3544 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3546 if (isDuplicated()) {
3547 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3549 return mProfile->mSupportedDevices ;
3553 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3555 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3558 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3560 nsecs_t sysTime) const
3562 if ((sysTime == 0) && (inPastMs != 0)) {
3563 sysTime = systemTime();
3565 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3566 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3567 (NUM_STRATEGIES == strategy)) &&
3568 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3575 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3577 nsecs_t sysTime) const
3579 if (mRefCount[stream] != 0) {
3582 if (inPastMs == 0) {
3586 sysTime = systemTime();
3588 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3595 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3597 const size_t SIZE = 256;
3601 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3602 result.append(buffer);
3603 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3604 result.append(buffer);
3605 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3606 result.append(buffer);
3607 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3608 result.append(buffer);
3609 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3610 result.append(buffer);
3611 snprintf(buffer, SIZE, " Devices %08x\n", device());
3612 result.append(buffer);
3613 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3614 result.append(buffer);
3615 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3616 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3617 result.append(buffer);
3619 write(fd, result.string(), result.size());
3624 // --- AudioInputDescriptor class implementation
3626 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3627 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
3628 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3629 mInputSource(0), mProfile(profile)
3631 if (profile != NULL) {
3632 mSamplingRate = profile->mSamplingRates[0];
3633 mFormat = profile->mFormats[0];
3634 mChannelMask = profile->mChannelMasks[0];
3638 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3640 const size_t SIZE = 256;
3644 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3645 result.append(buffer);
3646 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3647 result.append(buffer);
3648 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3649 result.append(buffer);
3650 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3651 result.append(buffer);
3652 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3653 result.append(buffer);
3654 write(fd, result.string(), result.size());
3659 // --- StreamDescriptor class implementation
3661 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3662 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3664 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3667 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3669 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3670 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3671 if (mIndexCur.indexOfKey(device) < 0) {
3672 device = AUDIO_DEVICE_OUT_DEFAULT;
3674 return mIndexCur.valueFor(device);
3677 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3679 const size_t SIZE = 256;
3683 snprintf(buffer, SIZE, "%s %02d %02d ",
3684 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3685 result.append(buffer);
3686 for (size_t i = 0; i < mIndexCur.size(); i++) {
3687 snprintf(buffer, SIZE, "%04x : %02d, ",
3689 mIndexCur.valueAt(i));
3690 result.append(buffer);
3692 result.append("\n");
3694 write(fd, result.string(), result.size());
3697 // --- EffectDescriptor class implementation
3699 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3701 const size_t SIZE = 256;
3705 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3706 result.append(buffer);
3707 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3708 result.append(buffer);
3709 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3710 result.append(buffer);
3711 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3712 result.append(buffer);
3713 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3714 result.append(buffer);
3715 write(fd, result.string(), result.size());
3720 // --- IOProfile class implementation
3722 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3723 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3727 AudioPolicyManagerBase::HwModule::~HwModule()
3729 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3730 delete mOutputProfiles[i];
3732 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3733 delete mInputProfiles[i];
3735 free((void *)mName);
3738 void AudioPolicyManagerBase::HwModule::dump(int fd)
3740 const size_t SIZE = 256;
3744 snprintf(buffer, SIZE, " - name: %s\n", mName);
3745 result.append(buffer);
3746 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3747 result.append(buffer);
3748 write(fd, result.string(), result.size());
3749 if (mOutputProfiles.size()) {
3750 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
3751 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3752 snprintf(buffer, SIZE, " output %zu:\n", i);
3753 write(fd, buffer, strlen(buffer));
3754 mOutputProfiles[i]->dump(fd);
3757 if (mInputProfiles.size()) {
3758 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
3759 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3760 snprintf(buffer, SIZE, " input %zu:\n", i);
3761 write(fd, buffer, strlen(buffer));
3762 mInputProfiles[i]->dump(fd);
3767 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3768 : mFlags((audio_output_flags_t)0), mModule(module)
3772 AudioPolicyManagerBase::IOProfile::~IOProfile()
3776 // checks if the IO profile is compatible with specified parameters.
3777 // Sampling rate, format and channel mask must be specified in order to
3778 // get a valid a match
3779 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3780 uint32_t samplingRate,
3781 audio_format_t format,
3782 audio_channel_mask_t channelMask,
3783 audio_output_flags_t flags) const
3785 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3789 if ((mSupportedDevices & device) != device) {
3792 if ((mFlags & flags) != flags) {
3796 for (i = 0; i < mSamplingRates.size(); i++)
3798 if (mSamplingRates[i] == samplingRate) {
3802 if (i == mSamplingRates.size()) {
3805 for (i = 0; i < mFormats.size(); i++)
3807 if (mFormats[i] == format) {
3811 if (i == mFormats.size()) {
3814 for (i = 0; i < mChannelMasks.size(); i++)
3816 if (mChannelMasks[i] == channelMask) {
3820 if (i == mChannelMasks.size()) {
3826 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3828 const size_t SIZE = 256;
3832 snprintf(buffer, SIZE, " - sampling rates: ");
3833 result.append(buffer);
3834 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3835 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3836 result.append(buffer);
3837 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3840 snprintf(buffer, SIZE, " - channel masks: ");
3841 result.append(buffer);
3842 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3843 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3844 result.append(buffer);
3845 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3848 snprintf(buffer, SIZE, " - formats: ");
3849 result.append(buffer);
3850 for (size_t i = 0; i < mFormats.size(); i++) {
3851 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3852 result.append(buffer);
3853 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3856 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
3857 result.append(buffer);
3858 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3859 result.append(buffer);
3861 write(fd, result.string(), result.size());
3864 void AudioPolicyManagerBase::IOProfile::log()
3866 const size_t SIZE = 256;
3870 ALOGV(" - sampling rates: ");
3871 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3872 ALOGV(" %d", mSamplingRates[i]);
3875 ALOGV(" - channel masks: ");
3876 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3877 ALOGV(" 0x%04x", mChannelMasks[i]);
3880 ALOGV(" - formats: ");
3881 for (size_t i = 0; i < mFormats.size(); i++) {
3882 ALOGV(" 0x%08x", mFormats[i]);
3885 ALOGV(" - devices: 0x%04x\n", mSupportedDevices);
3886 ALOGV(" - flags: 0x%04x\n", mFlags);
3889 // --- audio_policy.conf file parsing
3891 struct StringToEnum {
3896 #define STRING_TO_ENUM(string) { #string, string }
3897 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3899 const struct StringToEnum sDeviceNameToEnumTable[] = {
3900 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3901 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3902 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3903 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3904 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3905 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3906 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3907 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3908 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3909 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3910 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3911 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3912 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3913 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3914 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3915 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3916 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3917 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3918 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3919 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3920 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3921 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3922 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3923 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
3924 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
3927 const struct StringToEnum sFlagNameToEnumTable[] = {
3928 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3929 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3930 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3931 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3932 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3933 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3936 const struct StringToEnum sFormatNameToEnumTable[] = {
3937 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3938 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3939 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
3940 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
3941 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
3942 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
3943 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3944 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3945 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3946 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
3947 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
3948 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
3949 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
3950 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
3953 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3954 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3955 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3956 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3957 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3960 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3961 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3962 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3963 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3967 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3971 for (size_t i = 0; i < size; i++) {
3972 if (strcmp(table[i].name, name) == 0) {
3973 ALOGV("stringToEnum() found %s", table[i].name);
3974 return table[i].value;
3980 bool AudioPolicyManagerBase::stringToBool(const char *value)
3982 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
3985 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3989 // it is OK to cast name to non const here as we are not going to use it after
3990 // strtok() modifies it
3991 char *flagName = strtok(name, "|");
3992 while (flagName != NULL) {
3993 if (strlen(flagName) != 0) {
3994 flag |= stringToEnum(sFlagNameToEnumTable,
3995 ARRAY_SIZE(sFlagNameToEnumTable),
3998 flagName = strtok(NULL, "|");
4000 //force direct flag if offload flag is set: offloading implies a direct output stream
4001 // and all common behaviors are driven by checking only the direct flag
4002 // this should normally be set appropriately in the policy configuration file
4003 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
4004 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
4007 return (audio_output_flags_t)flag;
4010 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
4012 uint32_t device = 0;
4014 char *devName = strtok(name, "|");
4015 while (devName != NULL) {
4016 if (strlen(devName) != 0) {
4017 device |= stringToEnum(sDeviceNameToEnumTable,
4018 ARRAY_SIZE(sDeviceNameToEnumTable),
4021 devName = strtok(NULL, "|");
4026 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
4028 char *str = strtok(name, "|");
4030 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4031 // rates should be read from the output stream after it is opened for the first time
4032 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4033 profile->mSamplingRates.add(0);
4037 while (str != NULL) {
4038 uint32_t rate = atoi(str);
4040 ALOGV("loadSamplingRates() adding rate %d", rate);
4041 profile->mSamplingRates.add(rate);
4043 str = strtok(NULL, "|");
4048 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
4050 char *str = strtok(name, "|");
4052 // by convention, "0' in the first entry in mFormats indicates the supported formats
4053 // should be read from the output stream after it is opened for the first time
4054 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4055 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
4059 while (str != NULL) {
4060 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4061 ARRAY_SIZE(sFormatNameToEnumTable),
4063 if (format != AUDIO_FORMAT_DEFAULT) {
4064 profile->mFormats.add(format);
4066 str = strtok(NULL, "|");
4071 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
4073 const char *str = strtok(name, "|");
4075 ALOGV("loadInChannels() %s", name);
4077 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4078 profile->mChannelMasks.add(0);
4082 while (str != NULL) {
4083 audio_channel_mask_t channelMask =
4084 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4085 ARRAY_SIZE(sInChannelsNameToEnumTable),
4087 if (channelMask != 0) {
4088 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4089 profile->mChannelMasks.add(channelMask);
4091 str = strtok(NULL, "|");
4096 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
4098 const char *str = strtok(name, "|");
4100 ALOGV("loadOutChannels() %s", name);
4102 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4103 // masks should be read from the output stream after it is opened for the first time
4104 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4105 profile->mChannelMasks.add(0);
4109 while (str != NULL) {
4110 audio_channel_mask_t channelMask =
4111 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4112 ARRAY_SIZE(sOutChannelsNameToEnumTable),
4114 if (channelMask != 0) {
4115 profile->mChannelMasks.add(channelMask);
4117 str = strtok(NULL, "|");
4122 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
4124 cnode *node = root->first_child;
4126 IOProfile *profile = new IOProfile(module);
4129 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4130 loadSamplingRates((char *)node->value, profile);
4131 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4132 loadFormats((char *)node->value, profile);
4133 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4134 loadInChannels((char *)node->value, profile);
4135 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4136 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
4140 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
4141 "loadInput() invalid supported devices");
4142 ALOGW_IF(profile->mChannelMasks.size() == 0,
4143 "loadInput() invalid supported channel masks");
4144 ALOGW_IF(profile->mSamplingRates.size() == 0,
4145 "loadInput() invalid supported sampling rates");
4146 ALOGW_IF(profile->mFormats.size() == 0,
4147 "loadInput() invalid supported formats");
4148 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
4149 (profile->mChannelMasks.size() != 0) &&
4150 (profile->mSamplingRates.size() != 0) &&
4151 (profile->mFormats.size() != 0)) {
4153 ALOGV("loadInput() adding input mSupportedDevices 0x%X", profile->mSupportedDevices);
4155 module->mInputProfiles.add(profile);
4163 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
4165 cnode *node = root->first_child;
4167 IOProfile *profile = new IOProfile(module);
4170 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4171 loadSamplingRates((char *)node->value, profile);
4172 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4173 loadFormats((char *)node->value, profile);
4174 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4175 loadOutChannels((char *)node->value, profile);
4176 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4177 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
4178 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4179 profile->mFlags = parseFlagNames((char *)node->value);
4183 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
4184 "loadOutput() invalid supported devices");
4185 ALOGW_IF(profile->mChannelMasks.size() == 0,
4186 "loadOutput() invalid supported channel masks");
4187 ALOGW_IF(profile->mSamplingRates.size() == 0,
4188 "loadOutput() invalid supported sampling rates");
4189 ALOGW_IF(profile->mFormats.size() == 0,
4190 "loadOutput() invalid supported formats");
4191 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
4192 (profile->mChannelMasks.size() != 0) &&
4193 (profile->mSamplingRates.size() != 0) &&
4194 (profile->mFormats.size() != 0)) {
4196 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
4197 profile->mSupportedDevices, profile->mFlags);
4199 module->mOutputProfiles.add(profile);
4207 void AudioPolicyManagerBase::loadHwModule(cnode *root)
4209 cnode *node = config_find(root, OUTPUTS_TAG);
4210 status_t status = NAME_NOT_FOUND;
4212 HwModule *module = new HwModule(root->name);
4215 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
4217 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
4219 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
4220 mHasRemoteSubmix = true;
4223 node = node->first_child;
4225 ALOGV("loadHwModule() loading output %s", node->name);
4226 status_t tmpStatus = loadOutput(node, module);
4227 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4233 node = config_find(root, INPUTS_TAG);
4235 node = node->first_child;
4237 ALOGV("loadHwModule() loading input %s", node->name);
4238 status_t tmpStatus = loadInput(node, module);
4239 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4245 if (status == NO_ERROR) {
4246 mHwModules.add(module);
4252 void AudioPolicyManagerBase::loadHwModules(cnode *root)
4254 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
4259 node = node->first_child;
4261 ALOGV("loadHwModules() loading module %s", node->name);
4267 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
4269 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4273 node = node->first_child;
4275 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
4276 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
4277 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
4278 "loadGlobalConfig() no attached output devices");
4279 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
4280 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
4281 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
4282 ARRAY_SIZE(sDeviceNameToEnumTable),
4283 (char *)node->value);
4284 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
4285 "loadGlobalConfig() default device not specified");
4286 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
4287 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
4288 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
4289 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
4290 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4291 mSpeakerDrcEnabled = stringToBool((char *)node->value);
4292 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4298 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
4303 data = (char *)load_file(path, NULL);
4307 root = config_node("", "");
4308 config_load(root, data);
4310 loadGlobalConfig(root);
4311 loadHwModules(root);
4317 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4322 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
4327 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
4328 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
4329 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
4331 module = new HwModule("primary");
4333 profile = new IOProfile(module);
4334 profile->mSamplingRates.add(44100);
4335 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4336 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4337 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
4338 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4339 module->mOutputProfiles.add(profile);
4341 profile = new IOProfile(module);
4342 profile->mSamplingRates.add(8000);
4343 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4344 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4345 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
4346 module->mInputProfiles.add(profile);
4348 mHwModules.add(module);
4351 }; // namespace android