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 SortedVector <audio_io_handle_t> outputs;
58 ALOGV("setDeviceConnectionState() device: 0x%X, state %d, address %s", device, state, device_address);
60 // connect/disconnect only 1 device at a time
61 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
63 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
64 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
68 // handle output devices
69 if (audio_is_output_device(device)) {
71 if (!mHasA2dp && audio_is_a2dp_device(device)) {
72 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
75 if (!mHasUsb && audio_is_usb_device(device)) {
76 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
79 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
80 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
84 // save a copy of the opened output descriptors before any output is opened or closed
85 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
86 mPreviousOutputs = mOutputs;
90 // handle output device connection
91 case AudioSystem::DEVICE_STATE_AVAILABLE:
92 if (mAvailableOutputDevices & device) {
93 ALOGW("setDeviceConnectionState() device already connected: %x", device);
94 return INVALID_OPERATION;
96 ALOGV("setDeviceConnectionState() connecting device %x", device);
98 if (mHasA2dp && audio_is_a2dp_device(device)) {
99 // handle A2DP device connection
100 AudioParameter param;
101 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
102 paramStr = param.toString();
103 } else if (mHasUsb && audio_is_usb_device(device)) {
104 // handle USB device connection
105 paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
108 if (checkOutputsForDevice(device, state, outputs, paramStr) != NO_ERROR) {
109 return INVALID_OPERATION;
111 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
113 // register new device as available
114 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
116 if (mHasA2dp && audio_is_a2dp_device(device)) {
117 // handle A2DP device connection
118 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
119 mA2dpSuspended = false;
120 } else if (audio_is_bluetooth_sco_device(device)) {
121 // handle SCO device connection
122 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
123 } else if (mHasUsb && audio_is_usb_device(device)) {
124 // handle USB device connection
125 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
129 // handle output device disconnection
130 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
131 if (!(mAvailableOutputDevices & device)) {
132 ALOGW("setDeviceConnectionState() device not connected: %x", device);
133 return INVALID_OPERATION;
136 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
137 // remove device from available output devices
138 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
140 checkOutputsForDevice(device, state, outputs, paramStr);
141 if (mHasA2dp && audio_is_a2dp_device(device)) {
142 // handle A2DP device disconnection
143 mA2dpDeviceAddress = "";
144 mA2dpSuspended = false;
145 } else if (audio_is_bluetooth_sco_device(device)) {
146 // handle SCO device disconnection
147 mScoDeviceAddress = "";
148 } else if (mHasUsb && audio_is_usb_device(device)) {
149 // handle USB device disconnection
150 mUsbCardAndDevice = "";
152 // not currently handling multiple simultaneous submixes: ignoring remote submix
157 ALOGE("setDeviceConnectionState() invalid state: %x", state);
162 checkOutputForAllStrategies();
163 // outputs must be closed after checkOutputForAllStrategies() is executed
164 if (!outputs.isEmpty()) {
165 for (size_t i = 0; i < outputs.size(); i++) {
166 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
167 // close unused outputs after device disconnection or direct outputs that have been
168 // opened by checkOutputsForDevice() to query dynamic parameters
169 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
170 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
171 (desc->mDirectOpenCount == 0))) {
172 closeOutput(outputs[i]);
177 updateDevicesAndOutputs();
178 for (size_t i = 0; i < mOutputs.size(); i++) {
179 // do not force device change on duplicated output because if device is 0, it will
180 // also force a device 0 for the two outputs it is duplicated to which may override
181 // a valid device selection on those outputs.
182 setOutputDevice(mOutputs.keyAt(i),
183 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
184 !mOutputs.valueAt(i)->isDuplicated(),
188 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
189 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
190 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
191 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
192 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
193 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
198 // handle input devices
199 if (audio_is_input_device(device)) {
203 // handle input device connection
204 case AudioSystem::DEVICE_STATE_AVAILABLE: {
205 if (mAvailableInputDevices & device) {
206 ALOGW("setDeviceConnectionState() device already connected: %d", device);
207 return INVALID_OPERATION;
209 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
213 // handle input device disconnection
214 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
215 if (!(mAvailableInputDevices & device)) {
216 ALOGW("setDeviceConnectionState() device not connected: %d", device);
217 return INVALID_OPERATION;
219 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
223 ALOGE("setDeviceConnectionState() invalid state: %x", state);
227 audio_io_handle_t activeInput = getActiveInput();
228 if (activeInput != 0) {
229 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
230 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
231 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
232 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
233 inputDesc->mDevice, newDevice, activeInput);
234 inputDesc->mDevice = newDevice;
235 AudioParameter param = AudioParameter();
236 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
237 mpClientInterface->setParameters(activeInput, param.toString());
244 ALOGW("setDeviceConnectionState() invalid device: %x", device);
248 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
249 const char *device_address)
251 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
252 String8 address = String8(device_address);
253 if (audio_is_output_device(device)) {
254 if (device & mAvailableOutputDevices) {
255 if (audio_is_a2dp_device(device) &&
256 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
259 if (audio_is_bluetooth_sco_device(device) &&
260 address != "" && mScoDeviceAddress != address) {
263 if (audio_is_usb_device(device) &&
264 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
265 ALOGE("getDeviceConnectionState() invalid device: %x", device);
268 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
271 state = AudioSystem::DEVICE_STATE_AVAILABLE;
273 } else if (audio_is_input_device(device)) {
274 if (device & mAvailableInputDevices) {
275 state = AudioSystem::DEVICE_STATE_AVAILABLE;
282 void AudioPolicyManagerBase::setPhoneState(int state)
284 ALOGV("setPhoneState() state %d", state);
285 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
286 if (state < 0 || state >= AudioSystem::NUM_MODES) {
287 ALOGW("setPhoneState() invalid state %d", state);
291 if (state == mPhoneState ) {
292 ALOGW("setPhoneState() setting same state %d", state);
296 // if leaving call state, handle special case of active streams
297 // pertaining to sonification strategy see handleIncallSonification()
299 ALOGV("setPhoneState() in call state management: new state is %d", state);
300 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
301 handleIncallSonification(stream, false, true);
305 // store previous phone state for management of sonification strategy below
306 int oldState = mPhoneState;
310 // are we entering or starting a call
311 if (!isStateInCall(oldState) && isStateInCall(state)) {
312 ALOGV(" Entering call in setPhoneState()");
313 // force routing command to audio hardware when starting a call
314 // even if no device change is needed
316 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
317 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
318 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
320 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
321 ALOGV(" Exiting call in setPhoneState()");
322 // force routing command to audio hardware when exiting a call
323 // even if no device change is needed
325 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
326 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
327 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
329 } else if (isStateInCall(state) && (state != oldState)) {
330 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
331 // force routing command to audio hardware when switching between telephony and VoIP
332 // even if no device change is needed
336 // check for device and output changes triggered by new phone state
337 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
339 checkOutputForAllStrategies();
340 updateDevicesAndOutputs();
342 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
344 // force routing command to audio hardware when ending call
345 // even if no device change is needed
346 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
347 newDevice = hwOutputDesc->device();
351 if (isStateInCall(state)) {
352 nsecs_t sysTime = systemTime();
353 for (size_t i = 0; i < mOutputs.size(); i++) {
354 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
355 // mute media and sonification strategies and delay device switch by the largest
356 // latency of any output where either strategy is active.
357 // This avoid sending the ring tone or music tail into the earpiece or headset.
358 if ((desc->isStrategyActive(STRATEGY_MEDIA,
359 SONIFICATION_HEADSET_MUSIC_DELAY,
361 desc->isStrategyActive(STRATEGY_SONIFICATION,
362 SONIFICATION_HEADSET_MUSIC_DELAY,
364 (delayMs < (int)desc->mLatency*2)) {
365 delayMs = desc->mLatency*2;
367 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
368 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
369 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
370 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
371 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
372 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
376 // change routing is necessary
377 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
379 // if entering in call state, handle special case of active streams
380 // pertaining to sonification strategy see handleIncallSonification()
381 if (isStateInCall(state)) {
382 ALOGV("setPhoneState() in call state management: new state is %d", state);
383 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
384 handleIncallSonification(stream, true, true);
388 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
389 if (state == AudioSystem::MODE_RINGTONE &&
390 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
391 mLimitRingtoneVolume = true;
393 mLimitRingtoneVolume = false;
397 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
399 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
401 bool forceVolumeReeval = false;
403 case AudioSystem::FOR_COMMUNICATION:
404 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
405 config != AudioSystem::FORCE_NONE) {
406 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
409 forceVolumeReeval = true;
410 mForceUse[usage] = config;
412 case AudioSystem::FOR_MEDIA:
413 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
414 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
415 config != AudioSystem::FORCE_ANALOG_DOCK &&
416 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
417 config != AudioSystem::FORCE_NO_BT_A2DP) {
418 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
421 mForceUse[usage] = config;
423 case AudioSystem::FOR_RECORD:
424 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
425 config != AudioSystem::FORCE_NONE) {
426 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
429 mForceUse[usage] = config;
431 case AudioSystem::FOR_DOCK:
432 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
433 config != AudioSystem::FORCE_BT_DESK_DOCK &&
434 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
435 config != AudioSystem::FORCE_ANALOG_DOCK &&
436 config != AudioSystem::FORCE_DIGITAL_DOCK) {
437 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
439 forceVolumeReeval = true;
440 mForceUse[usage] = config;
442 case AudioSystem::FOR_SYSTEM:
443 if (config != AudioSystem::FORCE_NONE &&
444 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
445 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
447 forceVolumeReeval = true;
448 mForceUse[usage] = config;
451 ALOGW("setForceUse() invalid usage %d", usage);
455 // check for device and output changes triggered by new force usage
457 checkOutputForAllStrategies();
458 updateDevicesAndOutputs();
459 for (size_t i = 0; i < mOutputs.size(); i++) {
460 audio_io_handle_t output = mOutputs.keyAt(i);
461 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
462 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
463 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
464 applyStreamVolumes(output, newDevice, 0, true);
468 audio_io_handle_t activeInput = getActiveInput();
469 if (activeInput != 0) {
470 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
471 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
472 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
473 ALOGV("setForceUse() changing device from %x to %x for input %d",
474 inputDesc->mDevice, newDevice, activeInput);
475 inputDesc->mDevice = newDevice;
476 AudioParameter param = AudioParameter();
477 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
478 mpClientInterface->setParameters(activeInput, param.toString());
484 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
486 return mForceUse[usage];
489 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
491 ALOGV("setSystemProperty() property %s, value %s", property, value);
494 // Find a direct output profile compatible with the parameters passed, even if the input flags do
495 // not explicitly request a direct output
496 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
497 audio_devices_t device,
498 uint32_t samplingRate,
499 audio_format_t format,
500 audio_channel_mask_t channelMask,
501 audio_output_flags_t flags)
503 for (size_t i = 0; i < mHwModules.size(); i++) {
504 if (mHwModules[i]->mHandle == 0) {
507 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
508 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
509 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
510 if (profile->isCompatibleProfile(device, samplingRate, format,
512 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
513 if (mAvailableOutputDevices & profile->mSupportedDevices) {
514 return mHwModules[i]->mOutputProfiles[j];
518 if (profile->isCompatibleProfile(device, samplingRate, format,
520 AUDIO_OUTPUT_FLAG_DIRECT)) {
521 if (mAvailableOutputDevices & profile->mSupportedDevices) {
522 return mHwModules[i]->mOutputProfiles[j];
531 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
532 uint32_t samplingRate,
533 audio_format_t format,
534 audio_channel_mask_t channelMask,
535 AudioSystem::output_flags flags,
536 const audio_offload_info_t *offloadInfo)
538 audio_io_handle_t output = 0;
539 uint32_t latency = 0;
540 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
541 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
542 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
543 device, stream, samplingRate, format, channelMask, flags);
545 #ifdef AUDIO_POLICY_TEST
546 if (mCurOutput != 0) {
547 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
548 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
550 if (mTestOutputs[mCurOutput] == 0) {
551 ALOGV("getOutput() opening test output");
552 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
553 outputDesc->mDevice = mTestDevice;
554 outputDesc->mSamplingRate = mTestSamplingRate;
555 outputDesc->mFormat = mTestFormat;
556 outputDesc->mChannelMask = mTestChannels;
557 outputDesc->mLatency = mTestLatencyMs;
558 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
559 outputDesc->mRefCount[stream] = 0;
560 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
561 &outputDesc->mSamplingRate,
562 &outputDesc->mFormat,
563 &outputDesc->mChannelMask,
564 &outputDesc->mLatency,
567 if (mTestOutputs[mCurOutput]) {
568 AudioParameter outputCmd = AudioParameter();
569 outputCmd.addInt(String8("set_id"),mCurOutput);
570 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
571 addOutput(mTestOutputs[mCurOutput], outputDesc);
574 return mTestOutputs[mCurOutput];
576 #endif //AUDIO_POLICY_TEST
578 // open a direct output if required by specified parameters
579 //force direct flag if offload flag is set: offloading implies a direct output stream
580 // and all common behaviors are driven by checking only the direct flag
581 // this should normally be set appropriately in the policy configuration file
582 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
583 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
586 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
587 // creating an offloaded track and tearing it down immediately after start when audioflinger
588 // detects there is an active non offloadable effect.
589 // FIXME: We should check the audio session here but we do not have it in this context.
590 // This may prevent offloading in rare situations where effects are left active by apps
591 // in the background.
592 IOProfile *profile = NULL;
593 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
594 !isNonOffloadableEffectEnabled()) {
595 profile = getProfileForDirectOutput(device,
599 (audio_output_flags_t)flags);
602 if (profile != NULL) {
603 AudioOutputDescriptor *outputDesc = NULL;
605 for (size_t i = 0; i < mOutputs.size(); i++) {
606 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
607 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
609 // reuse direct output if currently open and configured with same parameters
610 if ((samplingRate == outputDesc->mSamplingRate) &&
611 (format == outputDesc->mFormat) &&
612 (channelMask == outputDesc->mChannelMask)) {
613 outputDesc->mDirectOpenCount++;
614 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
615 return mOutputs.keyAt(i);
619 // close direct output if currently open and configured with different parameters
620 if (outputDesc != NULL) {
621 closeOutput(outputDesc->mId);
623 outputDesc = new AudioOutputDescriptor(profile);
624 outputDesc->mDevice = device;
625 outputDesc->mSamplingRate = samplingRate;
626 outputDesc->mFormat = format;
627 outputDesc->mChannelMask = channelMask;
628 outputDesc->mLatency = 0;
629 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
630 outputDesc->mRefCount[stream] = 0;
631 outputDesc->mStopTime[stream] = 0;
632 outputDesc->mDirectOpenCount = 1;
633 output = mpClientInterface->openOutput(profile->mModule->mHandle,
634 &outputDesc->mDevice,
635 &outputDesc->mSamplingRate,
636 &outputDesc->mFormat,
637 &outputDesc->mChannelMask,
638 &outputDesc->mLatency,
642 // only accept an output with the requested parameters
644 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
645 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
646 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
647 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
648 "format %d %d, channelMask %04x %04x", output, samplingRate,
649 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
650 outputDesc->mChannelMask);
652 mpClientInterface->closeOutput(output);
657 audio_io_handle_t srcOutput = getOutputForEffect();
658 addOutput(output, outputDesc);
659 audio_io_handle_t dstOutput = getOutputForEffect();
660 if (dstOutput == output) {
661 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
663 mPreviousOutputs = mOutputs;
664 ALOGV("getOutput() returns new direct output %d", output);
668 // ignoring channel mask due to downmix capability in mixer
670 // open a non direct output
672 // for non direct outputs, only PCM is supported
673 if (audio_is_linear_pcm(format)) {
674 // get which output is suitable for the specified stream. The actual
675 // routing change will happen when startOutput() will be called
676 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
678 output = selectOutput(outputs, flags);
680 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
681 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
683 ALOGV("getOutput() returns output %d", output);
688 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
689 AudioSystem::output_flags flags)
691 // select one output among several that provide a path to a particular device or set of
692 // devices (the list was previously build by getOutputsForDevice()).
693 // The priority is as follows:
694 // 1: the output with the highest number of requested policy flags
695 // 2: the primary output
696 // 3: the first output in the list
698 if (outputs.size() == 0) {
701 if (outputs.size() == 1) {
705 int maxCommonFlags = 0;
706 audio_io_handle_t outputFlags = 0;
707 audio_io_handle_t outputPrimary = 0;
709 for (size_t i = 0; i < outputs.size(); i++) {
710 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
711 if (!outputDesc->isDuplicated()) {
712 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
713 if (commonFlags > maxCommonFlags) {
714 outputFlags = outputs[i];
715 maxCommonFlags = commonFlags;
716 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
718 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
719 outputPrimary = outputs[i];
724 if (outputFlags != 0) {
727 if (outputPrimary != 0) {
728 return outputPrimary;
734 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
735 AudioSystem::stream_type stream,
738 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
739 ssize_t index = mOutputs.indexOfKey(output);
741 ALOGW("startOutput() unknown output %d", output);
745 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
747 // increment usage count for this stream on the requested output:
748 // NOTE that the usage count is the same for duplicated output and hardware output which is
749 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
750 outputDesc->changeRefCount(stream, 1);
752 if (outputDesc->mRefCount[stream] == 1) {
753 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
754 routing_strategy strategy = getStrategy(stream);
755 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
756 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
759 for (size_t i = 0; i < mOutputs.size(); i++) {
760 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
761 if (desc != outputDesc) {
762 // force a device change if any other output is managed by the same hw
763 // module and has a current device selection that differs from selected device.
764 // In this case, the audio HAL must receive the new device selection so that it can
765 // change the device currently selected by the other active output.
766 if (outputDesc->sharesHwModuleWith(desc) &&
767 desc->device() != newDevice) {
770 // wait for audio on other active outputs to be presented when starting
771 // a notification so that audio focus effect can propagate.
772 uint32_t latency = desc->latency();
773 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
778 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
780 // handle special case for sonification while in call
782 handleIncallSonification(stream, true, false);
785 // apply volume rules for current stream and device if necessary
786 checkAndSetVolume(stream,
787 mStreams[stream].getVolumeIndex(newDevice),
791 // update the outputs if starting an output with a stream that can affect notification
793 handleNotificationRoutingForStream(stream);
794 if (waitMs > muteWaitMs) {
795 usleep((waitMs - muteWaitMs) * 2 * 1000);
802 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
803 AudioSystem::stream_type stream,
806 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
807 ssize_t index = mOutputs.indexOfKey(output);
809 ALOGW("stopOutput() unknown output %d", output);
813 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
815 // handle special case for sonification while in call
817 handleIncallSonification(stream, false, false);
820 if (outputDesc->mRefCount[stream] > 0) {
821 // decrement usage count of this stream on the output
822 outputDesc->changeRefCount(stream, -1);
823 // store time at which the stream was stopped - see isStreamActive()
824 if (outputDesc->mRefCount[stream] == 0) {
825 outputDesc->mStopTime[stream] = systemTime();
826 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
827 // delay the device switch by twice the latency because stopOutput() is executed when
828 // the track stop() command is received and at that time the audio track buffer can
829 // still contain data that needs to be drained. The latency only covers the audio HAL
830 // and kernel buffers. Also the latency does not always include additional delay in the
831 // audio path (audio DSP, CODEC ...)
832 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
834 // force restoring the device selection on other active outputs if it differs from the
835 // one being selected for this output
836 for (size_t i = 0; i < mOutputs.size(); i++) {
837 audio_io_handle_t curOutput = mOutputs.keyAt(i);
838 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
839 if (curOutput != output &&
841 outputDesc->sharesHwModuleWith(desc) &&
842 (newDevice != desc->device())) {
843 setOutputDevice(curOutput,
844 getNewDevice(curOutput, false /*fromCache*/),
846 outputDesc->mLatency*2);
849 // update the outputs if stopping one with a stream that can affect notification routing
850 handleNotificationRoutingForStream(stream);
854 ALOGW("stopOutput() refcount is already 0 for output %d", output);
855 return INVALID_OPERATION;
859 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
861 ALOGV("releaseOutput() %d", output);
862 ssize_t index = mOutputs.indexOfKey(output);
864 ALOGW("releaseOutput() releasing unknown output %d", output);
868 #ifdef AUDIO_POLICY_TEST
869 int testIndex = testOutputIndex(output);
870 if (testIndex != 0) {
871 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
872 if (outputDesc->isActive()) {
873 mpClientInterface->closeOutput(output);
874 delete mOutputs.valueAt(index);
875 mOutputs.removeItem(output);
876 mTestOutputs[testIndex] = 0;
880 #endif //AUDIO_POLICY_TEST
882 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
883 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
884 if (desc->mDirectOpenCount <= 0) {
885 ALOGW("releaseOutput() invalid open count %d for output %d",
886 desc->mDirectOpenCount, output);
889 if (--desc->mDirectOpenCount == 0) {
891 // If effects where present on the output, audioflinger moved them to the primary
892 // output by default: move them back to the appropriate output.
893 audio_io_handle_t dstOutput = getOutputForEffect();
894 if (dstOutput != mPrimaryOutput) {
895 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
902 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
903 uint32_t samplingRate,
904 audio_format_t format,
905 audio_channel_mask_t channelMask,
906 AudioSystem::audio_in_acoustics acoustics)
908 audio_io_handle_t input = 0;
909 audio_devices_t device = getDeviceForInputSource(inputSource);
911 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
912 inputSource, samplingRate, format, channelMask, acoustics);
914 if (device == AUDIO_DEVICE_NONE) {
915 ALOGW("getInput() could not find device for inputSource %d", inputSource);
919 // adapt channel selection to input source
920 switch(inputSource) {
921 case AUDIO_SOURCE_VOICE_UPLINK:
922 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
924 case AUDIO_SOURCE_VOICE_DOWNLINK:
925 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
927 case AUDIO_SOURCE_VOICE_CALL:
928 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
934 IOProfile *profile = getInputProfile(device,
938 if (profile == NULL) {
939 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
941 device, samplingRate, format, channelMask);
945 if (profile->mModule->mHandle == 0) {
946 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
950 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
952 inputDesc->mInputSource = inputSource;
953 inputDesc->mDevice = device;
954 inputDesc->mSamplingRate = samplingRate;
955 inputDesc->mFormat = format;
956 inputDesc->mChannelMask = channelMask;
957 inputDesc->mRefCount = 0;
958 input = mpClientInterface->openInput(profile->mModule->mHandle,
960 &inputDesc->mSamplingRate,
962 &inputDesc->mChannelMask);
964 // only accept input with the exact requested set of parameters
966 (samplingRate != inputDesc->mSamplingRate) ||
967 (format != inputDesc->mFormat) ||
968 (channelMask != inputDesc->mChannelMask)) {
969 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
970 samplingRate, format, channelMask);
972 mpClientInterface->closeInput(input);
977 mInputs.add(input, inputDesc);
981 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
983 ALOGV("startInput() input %d", input);
984 ssize_t index = mInputs.indexOfKey(input);
986 ALOGW("startInput() unknown input %d", input);
989 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
991 #ifdef AUDIO_POLICY_TEST
993 #endif //AUDIO_POLICY_TEST
995 // refuse 2 active AudioRecord clients at the same time except if the active input
996 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
997 audio_io_handle_t activeInput = getActiveInput();
998 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
999 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1000 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1001 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1002 stopInput(activeInput);
1003 releaseInput(activeInput);
1005 ALOGW("startInput() input %d failed: other input already started", input);
1006 return INVALID_OPERATION;
1011 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1012 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1013 inputDesc->mDevice = newDevice;
1016 // automatically enable the remote submix output when input is started
1017 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1018 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1019 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1022 AudioParameter param = AudioParameter();
1023 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1025 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1026 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1028 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1029 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1031 mpClientInterface->setParameters(input, param.toString());
1033 inputDesc->mRefCount = 1;
1037 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
1039 ALOGV("stopInput() input %d", input);
1040 ssize_t index = mInputs.indexOfKey(input);
1042 ALOGW("stopInput() unknown input %d", input);
1045 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1047 if (inputDesc->mRefCount == 0) {
1048 ALOGW("stopInput() input %d already stopped", input);
1049 return INVALID_OPERATION;
1051 // automatically disable the remote submix output when input is stopped
1052 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1053 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1054 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1057 AudioParameter param = AudioParameter();
1058 param.addInt(String8(AudioParameter::keyRouting), 0);
1059 mpClientInterface->setParameters(input, param.toString());
1060 inputDesc->mRefCount = 0;
1065 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1067 ALOGV("releaseInput() %d", input);
1068 ssize_t index = mInputs.indexOfKey(input);
1070 ALOGW("releaseInput() releasing unknown input %d", input);
1073 mpClientInterface->closeInput(input);
1074 delete mInputs.valueAt(index);
1075 mInputs.removeItem(input);
1076 ALOGV("releaseInput() exit");
1079 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1083 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1084 if (indexMin < 0 || indexMin >= indexMax) {
1085 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1088 mStreams[stream].mIndexMin = indexMin;
1089 mStreams[stream].mIndexMax = indexMax;
1092 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1094 audio_devices_t device)
1097 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1100 if (!audio_is_output_device(device)) {
1104 // Force max volume if stream cannot be muted
1105 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1107 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1108 stream, device, index);
1110 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1111 // clear all device specific values
1112 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1113 mStreams[stream].mIndexCur.clear();
1115 mStreams[stream].mIndexCur.add(device, index);
1117 // compute and apply stream volume on all outputs according to connected device
1118 status_t status = NO_ERROR;
1119 for (size_t i = 0; i < mOutputs.size(); i++) {
1120 audio_devices_t curDevice =
1121 getDeviceForVolume(mOutputs.valueAt(i)->device());
1122 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1123 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1124 if (volStatus != NO_ERROR) {
1132 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1134 audio_devices_t device)
1136 if (index == NULL) {
1139 if (!audio_is_output_device(device)) {
1142 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1143 // the strategy the stream belongs to.
1144 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1145 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1147 device = getDeviceForVolume(device);
1149 *index = mStreams[stream].getVolumeIndex(device);
1150 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1154 audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
1155 const SortedVector<audio_io_handle_t>& outputs)
1157 // select one output among several suitable for global effects.
1158 // The priority is as follows:
1159 // 1: An offloaded output. If the effect ends up not being offloadable,
1160 // AudioFlinger will invalidate the track and the offloaded output
1161 // will be closed causing the effect to be moved to a PCM output.
1162 // 2: A deep buffer output
1163 // 3: the first output in the list
1165 if (outputs.size() == 0) {
1169 audio_io_handle_t outputOffloaded = 0;
1170 audio_io_handle_t outputDeepBuffer = 0;
1172 for (size_t i = 0; i < outputs.size(); i++) {
1173 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1174 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1175 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1176 outputOffloaded = outputs[i];
1178 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1179 outputDeepBuffer = outputs[i];
1183 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1184 outputOffloaded, outputDeepBuffer);
1185 if (outputOffloaded != 0) {
1186 return outputOffloaded;
1188 if (outputDeepBuffer != 0) {
1189 return outputDeepBuffer;
1195 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1197 // apply simple rule where global effects are attached to the same output as MUSIC streams
1199 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1200 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1201 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1203 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1204 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1205 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1210 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1211 audio_io_handle_t io,
1216 ssize_t index = mOutputs.indexOfKey(io);
1218 index = mInputs.indexOfKey(io);
1220 ALOGW("registerEffect() unknown io %d", io);
1221 return INVALID_OPERATION;
1225 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1226 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1227 desc->name, desc->memoryUsage);
1228 return INVALID_OPERATION;
1230 mTotalEffectsMemory += desc->memoryUsage;
1231 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1232 desc->name, io, strategy, session, id);
1233 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1235 EffectDescriptor *pDesc = new EffectDescriptor();
1236 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1238 pDesc->mStrategy = (routing_strategy)strategy;
1239 pDesc->mSession = session;
1240 pDesc->mEnabled = false;
1242 mEffects.add(id, pDesc);
1247 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1249 ssize_t index = mEffects.indexOfKey(id);
1251 ALOGW("unregisterEffect() unknown effect ID %d", id);
1252 return INVALID_OPERATION;
1255 EffectDescriptor *pDesc = mEffects.valueAt(index);
1257 setEffectEnabled(pDesc, false);
1259 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1260 ALOGW("unregisterEffect() memory %d too big for total %d",
1261 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1262 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1264 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1265 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1266 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1268 mEffects.removeItem(id);
1274 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1276 ssize_t index = mEffects.indexOfKey(id);
1278 ALOGW("unregisterEffect() unknown effect ID %d", id);
1279 return INVALID_OPERATION;
1282 return setEffectEnabled(mEffects.valueAt(index), enabled);
1285 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1287 if (enabled == pDesc->mEnabled) {
1288 ALOGV("setEffectEnabled(%s) effect already %s",
1289 enabled?"true":"false", enabled?"enabled":"disabled");
1290 return INVALID_OPERATION;
1294 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1295 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1296 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1297 return INVALID_OPERATION;
1299 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1300 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1302 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1303 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1304 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1305 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1307 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1308 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1310 pDesc->mEnabled = enabled;
1314 bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled()
1316 for (size_t i = 0; i < mEffects.size(); i++) {
1317 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1318 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1319 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1320 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1321 pDesc->mDesc.name, pDesc->mSession);
1328 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1330 nsecs_t sysTime = systemTime();
1331 for (size_t i = 0; i < mOutputs.size(); i++) {
1332 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1333 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1340 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1342 nsecs_t sysTime = systemTime();
1343 for (size_t i = 0; i < mOutputs.size(); i++) {
1344 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1345 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1346 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1353 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1355 for (size_t i = 0; i < mInputs.size(); i++) {
1356 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1357 if ((inputDescriptor->mInputSource == (int)source ||
1358 (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
1359 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1360 && (inputDescriptor->mRefCount > 0)) {
1368 status_t AudioPolicyManagerBase::dump(int fd)
1370 const size_t SIZE = 256;
1374 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1375 result.append(buffer);
1377 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1378 result.append(buffer);
1379 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1380 result.append(buffer);
1381 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1382 result.append(buffer);
1383 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1384 result.append(buffer);
1385 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1386 result.append(buffer);
1387 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1388 result.append(buffer);
1389 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1390 result.append(buffer);
1391 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1392 result.append(buffer);
1393 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1394 result.append(buffer);
1395 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1396 result.append(buffer);
1397 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1398 result.append(buffer);
1399 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1400 result.append(buffer);
1401 write(fd, result.string(), result.size());
1404 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1405 write(fd, buffer, strlen(buffer));
1406 for (size_t i = 0; i < mHwModules.size(); i++) {
1407 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
1408 write(fd, buffer, strlen(buffer));
1409 mHwModules[i]->dump(fd);
1412 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1413 write(fd, buffer, strlen(buffer));
1414 for (size_t i = 0; i < mOutputs.size(); i++) {
1415 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1416 write(fd, buffer, strlen(buffer));
1417 mOutputs.valueAt(i)->dump(fd);
1420 snprintf(buffer, SIZE, "\nInputs dump:\n");
1421 write(fd, buffer, strlen(buffer));
1422 for (size_t i = 0; i < mInputs.size(); i++) {
1423 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1424 write(fd, buffer, strlen(buffer));
1425 mInputs.valueAt(i)->dump(fd);
1428 snprintf(buffer, SIZE, "\nStreams dump:\n");
1429 write(fd, buffer, strlen(buffer));
1430 snprintf(buffer, SIZE,
1431 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1432 write(fd, buffer, strlen(buffer));
1433 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1434 snprintf(buffer, SIZE, " %02zu ", i);
1435 write(fd, buffer, strlen(buffer));
1436 mStreams[i].dump(fd);
1439 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1440 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1441 write(fd, buffer, strlen(buffer));
1443 snprintf(buffer, SIZE, "Registered effects:\n");
1444 write(fd, buffer, strlen(buffer));
1445 for (size_t i = 0; i < mEffects.size(); i++) {
1446 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1447 write(fd, buffer, strlen(buffer));
1448 mEffects.valueAt(i)->dump(fd);
1455 // This function checks for the parameters which can be offloaded.
1456 // This can be enhanced depending on the capability of the DSP and policy
1458 bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1460 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1461 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
1462 offloadInfo.sample_rate, offloadInfo.channel_mask,
1464 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1465 offloadInfo.has_video);
1467 // Check if offload has been disabled
1468 char propValue[PROPERTY_VALUE_MAX];
1469 if (property_get("audio.offload.disable", propValue, "0")) {
1470 if (atoi(propValue) != 0) {
1471 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1476 // Check if stream type is music, then only allow offload as of now.
1477 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1479 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1483 //TODO: enable audio offloading with video when ready
1484 if (offloadInfo.has_video)
1486 ALOGV("isOffloadSupported: has_video == true, returning false");
1490 //If duration is less than minimum value defined in property, return false
1491 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1492 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1493 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1496 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1497 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1501 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1502 // creating an offloaded track and tearing it down immediately after start when audioflinger
1503 // detects there is an active non offloadable effect.
1504 // FIXME: We should check the audio session here but we do not have it in this context.
1505 // This may prevent offloading in rare situations where effects are left active by apps
1506 // in the background.
1507 if (isNonOffloadableEffectEnabled()) {
1511 // See if there is a profile to support this.
1512 // AUDIO_DEVICE_NONE
1513 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1514 offloadInfo.sample_rate,
1516 offloadInfo.channel_mask,
1517 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1518 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1519 return (profile != NULL);
1522 // ----------------------------------------------------------------------------
1523 // AudioPolicyManagerBase
1524 // ----------------------------------------------------------------------------
1526 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1528 #ifdef AUDIO_POLICY_TEST
1530 #endif //AUDIO_POLICY_TEST
1531 mPrimaryOutput((audio_io_handle_t)0),
1532 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1533 mPhoneState(AudioSystem::MODE_NORMAL),
1534 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1535 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1536 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),
1537 mSpeakerDrcEnabled(false)
1539 mpClientInterface = clientInterface;
1541 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1542 mForceUse[i] = AudioSystem::FORCE_NONE;
1545 mA2dpDeviceAddress = String8("");
1546 mScoDeviceAddress = String8("");
1547 mUsbCardAndDevice = String8("");
1549 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1550 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1551 ALOGE("could not load audio policy configuration file, setting defaults");
1552 defaultAudioPolicyConfig();
1556 // must be done after reading the policy
1557 initializeVolumeCurves();
1559 // open all output streams needed to access attached devices
1560 for (size_t i = 0; i < mHwModules.size(); i++) {
1561 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1562 if (mHwModules[i]->mHandle == 0) {
1563 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1566 // open all output streams needed to access attached devices
1567 // except for direct output streams that are only opened when they are actually
1568 // required by an app.
1569 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1571 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1573 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1574 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1575 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1576 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1577 outProfile->mSupportedDevices);
1578 audio_io_handle_t output = mpClientInterface->openOutput(
1579 outProfile->mModule->mHandle,
1580 &outputDesc->mDevice,
1581 &outputDesc->mSamplingRate,
1582 &outputDesc->mFormat,
1583 &outputDesc->mChannelMask,
1584 &outputDesc->mLatency,
1585 outputDesc->mFlags);
1589 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1590 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1591 if (mPrimaryOutput == 0 &&
1592 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1593 mPrimaryOutput = output;
1595 addOutput(output, outputDesc);
1596 setOutputDevice(output,
1597 (audio_devices_t)(mDefaultOutputDevice &
1598 outProfile->mSupportedDevices),
1605 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1606 "Not output found for attached devices %08x",
1607 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1609 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1611 updateDevicesAndOutputs();
1613 #ifdef AUDIO_POLICY_TEST
1614 if (mPrimaryOutput != 0) {
1615 AudioParameter outputCmd = AudioParameter();
1616 outputCmd.addInt(String8("set_id"), 0);
1617 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1619 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1620 mTestSamplingRate = 44100;
1621 mTestFormat = AudioSystem::PCM_16_BIT;
1622 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1625 mDirectOutput = false;
1626 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1627 mTestOutputs[i] = 0;
1630 const size_t SIZE = 256;
1632 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1633 run(buffer, ANDROID_PRIORITY_AUDIO);
1635 #endif //AUDIO_POLICY_TEST
1638 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1640 #ifdef AUDIO_POLICY_TEST
1642 #endif //AUDIO_POLICY_TEST
1643 for (size_t i = 0; i < mOutputs.size(); i++) {
1644 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1645 delete mOutputs.valueAt(i);
1647 for (size_t i = 0; i < mInputs.size(); i++) {
1648 mpClientInterface->closeInput(mInputs.keyAt(i));
1649 delete mInputs.valueAt(i);
1651 for (size_t i = 0; i < mHwModules.size(); i++) {
1652 delete mHwModules[i];
1656 status_t AudioPolicyManagerBase::initCheck()
1658 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1661 #ifdef AUDIO_POLICY_TEST
1662 bool AudioPolicyManagerBase::threadLoop()
1664 ALOGV("entering threadLoop()");
1665 while (!exitPending())
1671 Mutex::Autolock _l(mLock);
1672 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1674 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1675 AudioParameter param = AudioParameter(command);
1677 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1679 ALOGV("Test command %s received", command.string());
1681 if (param.get(String8("target"), target) != NO_ERROR) {
1684 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1685 param.remove(String8("test_cmd_policy_output"));
1686 mCurOutput = valueInt;
1688 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1689 param.remove(String8("test_cmd_policy_direct"));
1690 if (value == "false") {
1691 mDirectOutput = false;
1692 } else if (value == "true") {
1693 mDirectOutput = true;
1696 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1697 param.remove(String8("test_cmd_policy_input"));
1698 mTestInput = valueInt;
1701 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1702 param.remove(String8("test_cmd_policy_format"));
1703 int format = AudioSystem::INVALID_FORMAT;
1704 if (value == "PCM 16 bits") {
1705 format = AudioSystem::PCM_16_BIT;
1706 } else if (value == "PCM 8 bits") {
1707 format = AudioSystem::PCM_8_BIT;
1708 } else if (value == "Compressed MP3") {
1709 format = AudioSystem::MP3;
1711 if (format != AudioSystem::INVALID_FORMAT) {
1712 if (target == "Manager") {
1713 mTestFormat = format;
1714 } else if (mTestOutputs[mCurOutput] != 0) {
1715 AudioParameter outputParam = AudioParameter();
1716 outputParam.addInt(String8("format"), format);
1717 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1721 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1722 param.remove(String8("test_cmd_policy_channels"));
1725 if (value == "Channels Stereo") {
1726 channels = AudioSystem::CHANNEL_OUT_STEREO;
1727 } else if (value == "Channels Mono") {
1728 channels = AudioSystem::CHANNEL_OUT_MONO;
1730 if (channels != 0) {
1731 if (target == "Manager") {
1732 mTestChannels = channels;
1733 } else if (mTestOutputs[mCurOutput] != 0) {
1734 AudioParameter outputParam = AudioParameter();
1735 outputParam.addInt(String8("channels"), channels);
1736 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1740 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1741 param.remove(String8("test_cmd_policy_sampleRate"));
1742 if (valueInt >= 0 && valueInt <= 96000) {
1743 int samplingRate = valueInt;
1744 if (target == "Manager") {
1745 mTestSamplingRate = samplingRate;
1746 } else if (mTestOutputs[mCurOutput] != 0) {
1747 AudioParameter outputParam = AudioParameter();
1748 outputParam.addInt(String8("sampling_rate"), samplingRate);
1749 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1754 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1755 param.remove(String8("test_cmd_policy_reopen"));
1757 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1758 mpClientInterface->closeOutput(mPrimaryOutput);
1760 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1762 delete mOutputs.valueFor(mPrimaryOutput);
1763 mOutputs.removeItem(mPrimaryOutput);
1765 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1766 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1767 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1768 &outputDesc->mDevice,
1769 &outputDesc->mSamplingRate,
1770 &outputDesc->mFormat,
1771 &outputDesc->mChannelMask,
1772 &outputDesc->mLatency,
1773 outputDesc->mFlags);
1774 if (mPrimaryOutput == 0) {
1775 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1776 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1778 AudioParameter outputCmd = AudioParameter();
1779 outputCmd.addInt(String8("set_id"), 0);
1780 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1781 addOutput(mPrimaryOutput, outputDesc);
1786 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1792 void AudioPolicyManagerBase::exit()
1795 AutoMutex _l(mLock);
1797 mWaitWorkCV.signal();
1799 requestExitAndWait();
1802 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1804 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1805 if (output == mTestOutputs[i]) return i;
1809 #endif //AUDIO_POLICY_TEST
1813 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1815 outputDesc->mId = id;
1816 mOutputs.add(id, outputDesc);
1820 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1821 AudioSystem::device_connection_state state,
1822 SortedVector<audio_io_handle_t>& outputs,
1823 const String8 paramStr)
1825 AudioOutputDescriptor *desc;
1827 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1828 // first list already open outputs that can be routed to this device
1829 for (size_t i = 0; i < mOutputs.size(); i++) {
1830 desc = mOutputs.valueAt(i);
1831 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1832 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1833 outputs.add(mOutputs.keyAt(i));
1836 // then look for output profiles that can be routed to this device
1837 SortedVector<IOProfile *> profiles;
1838 for (size_t i = 0; i < mHwModules.size(); i++)
1840 if (mHwModules[i]->mHandle == 0) {
1843 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1845 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1846 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
1847 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1852 if (profiles.isEmpty() && outputs.isEmpty()) {
1853 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1857 // open outputs for matching profiles if needed. Direct outputs are also opened to
1858 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1859 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1860 IOProfile *profile = profiles[profile_index];
1862 // nothing to do if one output is already opened for this profile
1864 for (j = 0; j < mOutputs.size(); j++) {
1865 desc = mOutputs.valueAt(j);
1866 if (!desc->isDuplicated() && desc->mProfile == profile) {
1870 if (j != mOutputs.size()) {
1874 ALOGV("opening output for device %08x with params %s", device, paramStr.string());
1875 desc = new AudioOutputDescriptor(profile);
1876 desc->mDevice = device;
1877 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1878 offloadInfo.sample_rate = desc->mSamplingRate;
1879 offloadInfo.format = desc->mFormat;
1880 offloadInfo.channel_mask = desc->mChannelMask;
1882 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1884 &desc->mSamplingRate,
1886 &desc->mChannelMask,
1891 if (!paramStr.isEmpty()) {
1892 mpClientInterface->setParameters(output, paramStr);
1897 if (profile->mSamplingRates[0] == 0) {
1898 reply = mpClientInterface->getParameters(output,
1899 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1900 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1902 value = strpbrk((char *)reply.string(), "=");
1903 if (value != NULL) {
1904 loadSamplingRates(value + 1, profile);
1907 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
1908 reply = mpClientInterface->getParameters(output,
1909 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1910 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1912 value = strpbrk((char *)reply.string(), "=");
1913 if (value != NULL) {
1914 loadFormats(value + 1, profile);
1917 if (profile->mChannelMasks[0] == 0) {
1918 reply = mpClientInterface->getParameters(output,
1919 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1920 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1922 value = strpbrk((char *)reply.string(), "=");
1923 if (value != NULL) {
1924 loadOutChannels(value + 1, profile);
1927 if (((profile->mSamplingRates[0] == 0) &&
1928 (profile->mSamplingRates.size() < 2)) ||
1929 ((profile->mFormats[0] == 0) &&
1930 (profile->mFormats.size() < 2)) ||
1931 ((profile->mChannelMasks[0] == 0) &&
1932 (profile->mChannelMasks.size() < 2))) {
1933 ALOGW("checkOutputsForDevice() direct output missing param");
1934 mpClientInterface->closeOutput(output);
1936 } else if (profile->mSamplingRates[0] == 0) {
1937 mpClientInterface->closeOutput(output);
1938 desc->mSamplingRate = profile->mSamplingRates[1];
1939 offloadInfo.sample_rate = desc->mSamplingRate;
1940 output = mpClientInterface->openOutput(
1941 profile->mModule->mHandle,
1943 &desc->mSamplingRate,
1945 &desc->mChannelMask,
1952 addOutput(output, desc);
1953 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
1954 audio_io_handle_t duplicatedOutput = 0;
1956 // set initial stream volume for device
1957 applyStreamVolumes(output, device, 0, true);
1959 //TODO: configure audio effect output stage here
1961 // open a duplicating output thread for the new output and the primary output
1962 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1964 if (duplicatedOutput != 0) {
1965 // add duplicated output descriptor
1966 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1967 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1968 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1969 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1970 dupOutputDesc->mFormat = desc->mFormat;
1971 dupOutputDesc->mChannelMask = desc->mChannelMask;
1972 dupOutputDesc->mLatency = desc->mLatency;
1973 addOutput(duplicatedOutput, dupOutputDesc);
1974 applyStreamVolumes(duplicatedOutput, device, 0, true);
1976 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1977 mPrimaryOutput, output);
1978 mpClientInterface->closeOutput(output);
1979 mOutputs.removeItem(output);
1986 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1988 profiles.removeAt(profile_index);
1991 outputs.add(output);
1992 ALOGV("checkOutputsForDevice(): adding output %d", output);
1996 if (profiles.isEmpty()) {
1997 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2001 // check if one opened output is not needed any more after disconnecting one device
2002 for (size_t i = 0; i < mOutputs.size(); i++) {
2003 desc = mOutputs.valueAt(i);
2004 if (!desc->isDuplicated() &&
2005 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
2006 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2007 outputs.add(mOutputs.keyAt(i));
2010 for (size_t i = 0; i < mHwModules.size(); i++)
2012 if (mHwModules[i]->mHandle == 0) {
2015 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2017 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
2018 if (profile->mSupportedDevices & device) {
2019 ALOGV("checkOutputsForDevice(): clearing direct output profile %zu on module %zu",
2021 if (profile->mSamplingRates[0] == 0) {
2022 profile->mSamplingRates.clear();
2023 profile->mSamplingRates.add(0);
2025 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2026 profile->mFormats.clear();
2027 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2029 if (profile->mChannelMasks[0] == 0) {
2030 profile->mChannelMasks.clear();
2031 profile->mChannelMasks.add(0);
2040 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
2042 ALOGV("closeOutput(%d)", output);
2044 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2045 if (outputDesc == NULL) {
2046 ALOGW("closeOutput() unknown output %d", output);
2050 // look for duplicated outputs connected to the output being removed.
2051 for (size_t i = 0; i < mOutputs.size(); i++) {
2052 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2053 if (dupOutputDesc->isDuplicated() &&
2054 (dupOutputDesc->mOutput1 == outputDesc ||
2055 dupOutputDesc->mOutput2 == outputDesc)) {
2056 AudioOutputDescriptor *outputDesc2;
2057 if (dupOutputDesc->mOutput1 == outputDesc) {
2058 outputDesc2 = dupOutputDesc->mOutput2;
2060 outputDesc2 = dupOutputDesc->mOutput1;
2062 // As all active tracks on duplicated output will be deleted,
2063 // and as they were also referenced on the other output, the reference
2064 // count for their stream type must be adjusted accordingly on
2065 // the other output.
2066 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
2067 int refCount = dupOutputDesc->mRefCount[j];
2068 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
2070 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2071 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2073 mpClientInterface->closeOutput(duplicatedOutput);
2074 delete mOutputs.valueFor(duplicatedOutput);
2075 mOutputs.removeItem(duplicatedOutput);
2079 AudioParameter param;
2080 param.add(String8("closing"), String8("true"));
2081 mpClientInterface->setParameters(output, param.toString());
2083 mpClientInterface->closeOutput(output);
2085 mOutputs.removeItem(output);
2086 mPreviousOutputs = mOutputs;
2089 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
2090 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2092 SortedVector<audio_io_handle_t> outputs;
2094 ALOGVV("getOutputsForDevice() device %04x", device);
2095 for (size_t i = 0; i < openOutputs.size(); i++) {
2096 ALOGVV("output %d isDuplicated=%d device=%04x",
2097 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2098 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2099 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2100 outputs.add(openOutputs.keyAt(i));
2106 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2107 SortedVector<audio_io_handle_t>& outputs2)
2109 if (outputs1.size() != outputs2.size()) {
2112 for (size_t i = 0; i < outputs1.size(); i++) {
2113 if (outputs1[i] != outputs2[i]) {
2120 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
2122 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2123 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2124 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2125 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2127 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2128 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2129 strategy, srcOutputs[0], dstOutputs[0]);
2130 // mute strategy while moving tracks from one output to another
2131 for (size_t i = 0; i < srcOutputs.size(); i++) {
2132 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2133 if (desc->isStrategyActive(strategy)) {
2134 setStrategyMute(strategy, true, srcOutputs[i]);
2135 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2139 // Move effects associated to this strategy from previous output to new output
2140 if (strategy == STRATEGY_MEDIA) {
2141 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2142 SortedVector<audio_io_handle_t> moved;
2143 for (size_t i = 0; i < mEffects.size(); i++) {
2144 EffectDescriptor *desc = mEffects.valueAt(i);
2145 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2146 desc->mIo != fxOutput) {
2147 if (moved.indexOf(desc->mIo) < 0) {
2148 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2149 mEffects.keyAt(i), fxOutput);
2150 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2152 moved.add(desc->mIo);
2154 desc->mIo = fxOutput;
2158 // Move tracks associated to this strategy from previous output to new output
2159 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2160 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2161 mpClientInterface->invalidateStream((AudioSystem::stream_type)i);
2167 void AudioPolicyManagerBase::checkOutputForAllStrategies()
2169 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2170 checkOutputForStrategy(STRATEGY_PHONE);
2171 checkOutputForStrategy(STRATEGY_SONIFICATION);
2172 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2173 checkOutputForStrategy(STRATEGY_MEDIA);
2174 checkOutputForStrategy(STRATEGY_DTMF);
2177 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2183 for (size_t i = 0; i < mOutputs.size(); i++) {
2184 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2185 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2186 return mOutputs.keyAt(i);
2193 void AudioPolicyManagerBase::checkA2dpSuspend()
2198 audio_io_handle_t a2dpOutput = getA2dpOutput();
2199 if (a2dpOutput == 0) {
2203 // suspend A2DP output if:
2204 // (NOT already suspended) &&
2205 // ((SCO device is connected &&
2206 // (forced usage for communication || for record is SCO))) ||
2207 // (phone state is ringing || in call)
2209 // restore A2DP output if:
2210 // (Already suspended) &&
2211 // ((SCO device is NOT connected ||
2212 // (forced usage NOT for communication && NOT for record is SCO))) &&
2213 // (phone state is NOT ringing && NOT in call)
2215 if (mA2dpSuspended) {
2216 if (((mScoDeviceAddress == "") ||
2217 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2218 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2219 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2220 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2222 mpClientInterface->restoreOutput(a2dpOutput);
2223 mA2dpSuspended = false;
2226 if (((mScoDeviceAddress != "") &&
2227 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2228 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2229 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2230 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2232 mpClientInterface->suspendOutput(a2dpOutput);
2233 mA2dpSuspended = true;
2238 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2240 audio_devices_t device = AUDIO_DEVICE_NONE;
2242 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2243 // check the following by order of priority to request a routing change if necessary:
2244 // 1: the strategy enforced audible is active on the output:
2245 // use device for strategy enforced audible
2246 // 2: we are in call or the strategy phone is active on the output:
2247 // use device for strategy phone
2248 // 3: the strategy sonification is active on the output:
2249 // use device for strategy sonification
2250 // 4: the strategy "respectful" sonification is active on the output:
2251 // use device for strategy "respectful" sonification
2252 // 5: the strategy media is active on the output:
2253 // use device for strategy media
2254 // 6: the strategy DTMF is active on the output:
2255 // use device for strategy DTMF
2256 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2257 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2258 } else if (isInCall() ||
2259 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2260 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2261 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2262 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2263 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2264 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2265 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2266 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2267 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2268 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2271 ALOGV("getNewDevice() selected device %x", device);
2275 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2276 return (uint32_t)getStrategy(stream);
2279 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2280 audio_devices_t devices;
2281 // By checking the range of stream before calling getStrategy, we avoid
2282 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2283 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2284 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2285 devices = AUDIO_DEVICE_NONE;
2287 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2288 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2293 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2294 AudioSystem::stream_type stream) {
2295 // stream to strategy mapping
2297 case AudioSystem::VOICE_CALL:
2298 case AudioSystem::BLUETOOTH_SCO:
2299 return STRATEGY_PHONE;
2300 case AudioSystem::RING:
2301 case AudioSystem::ALARM:
2302 return STRATEGY_SONIFICATION;
2303 case AudioSystem::NOTIFICATION:
2304 return STRATEGY_SONIFICATION_RESPECTFUL;
2305 case AudioSystem::DTMF:
2306 return STRATEGY_DTMF;
2308 ALOGE("unknown stream type");
2309 case AudioSystem::SYSTEM:
2310 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2311 // while key clicks are played produces a poor result
2312 case AudioSystem::TTS:
2313 case AudioSystem::MUSIC:
2314 return STRATEGY_MEDIA;
2315 case AudioSystem::ENFORCED_AUDIBLE:
2316 return STRATEGY_ENFORCED_AUDIBLE;
2320 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2322 case AudioSystem::MUSIC:
2323 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2324 updateDevicesAndOutputs();
2331 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2334 uint32_t device = AUDIO_DEVICE_NONE;
2337 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2338 strategy, mDeviceForStrategy[strategy]);
2339 return mDeviceForStrategy[strategy];
2344 case STRATEGY_SONIFICATION_RESPECTFUL:
2346 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2347 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2348 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2349 // while media is playing on a remote device, use the the sonification behavior.
2350 // Note that we test this usecase before testing if media is playing because
2351 // the isStreamActive() method only informs about the activity of a stream, not
2352 // if it's for local playback. Note also that we use the same delay between both tests
2353 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2354 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2355 // while media is playing (or has recently played), use the same device
2356 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2358 // when media is not playing anymore, fall back on the sonification behavior
2359 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2366 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2367 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2370 // when in call, DTMF and PHONE strategies follow the same rules
2373 case STRATEGY_PHONE:
2374 // for phone strategy, we first consider the forced use and then the available devices by order
2376 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2377 case AudioSystem::FORCE_BT_SCO:
2378 if (!isInCall() || strategy != STRATEGY_DTMF) {
2379 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2382 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2384 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2386 // if SCO device is requested but no SCO device is available, fall back to default case
2389 default: // FORCE_NONE
2390 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2391 if (mHasA2dp && !isInCall() &&
2392 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2393 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2394 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2396 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2399 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2401 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2403 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2404 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2406 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2408 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2410 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2412 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2415 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2417 device = mDefaultOutputDevice;
2418 if (device == AUDIO_DEVICE_NONE) {
2419 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2423 case AudioSystem::FORCE_SPEAKER:
2424 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2425 // A2DP speaker when forcing to speaker output
2426 if (mHasA2dp && !isInCall() &&
2427 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2428 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2429 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2432 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2433 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2435 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2437 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2439 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2441 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2444 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2446 device = mDefaultOutputDevice;
2447 if (device == AUDIO_DEVICE_NONE) {
2448 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2454 case STRATEGY_SONIFICATION:
2456 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2457 // handleIncallSonification().
2459 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2464 case STRATEGY_ENFORCED_AUDIBLE:
2465 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2467 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2468 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2470 if ((strategy == STRATEGY_SONIFICATION) ||
2471 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2472 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2473 if (device == AUDIO_DEVICE_NONE) {
2474 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2477 // The second device used for sonification is the same as the device used by media strategy
2480 case STRATEGY_MEDIA: {
2481 uint32_t device2 = AUDIO_DEVICE_NONE;
2482 if (strategy != STRATEGY_SONIFICATION) {
2483 // no sonification on remote submix (e.g. WFD)
2484 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2486 if ((device2 == AUDIO_DEVICE_NONE) &&
2487 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2488 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2489 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2490 if (device2 == AUDIO_DEVICE_NONE) {
2491 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2493 if (device2 == AUDIO_DEVICE_NONE) {
2494 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2497 if (device2 == AUDIO_DEVICE_NONE) {
2498 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2500 if (device2 == AUDIO_DEVICE_NONE) {
2501 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2503 if (device2 == AUDIO_DEVICE_NONE) {
2504 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2506 if (device2 == AUDIO_DEVICE_NONE) {
2507 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2509 if (device2 == AUDIO_DEVICE_NONE) {
2510 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2512 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2513 // no sonification on aux digital (e.g. HDMI)
2514 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2516 if ((device2 == AUDIO_DEVICE_NONE) &&
2517 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2518 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2520 if (device2 == AUDIO_DEVICE_NONE) {
2521 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2524 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2525 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2528 device = mDefaultOutputDevice;
2529 if (device == AUDIO_DEVICE_NONE) {
2530 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2535 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2539 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2543 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2545 for (int i = 0; i < NUM_STRATEGIES; i++) {
2546 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2548 mPreviousOutputs = mOutputs;
2551 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2552 audio_devices_t prevDevice,
2555 // mute/unmute strategies using an incompatible device combination
2556 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2557 // if unmuting, unmute only after the specified delay
2558 if (outputDesc->isDuplicated()) {
2562 uint32_t muteWaitMs = 0;
2563 audio_devices_t device = outputDesc->device();
2564 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2565 // temporary mute output if device selection changes to avoid volume bursts due to
2566 // different per device volumes
2567 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2569 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2570 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2571 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2572 bool doMute = false;
2574 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2576 outputDesc->mStrategyMutedByDevice[i] = true;
2577 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2579 outputDesc->mStrategyMutedByDevice[i] = false;
2581 if (doMute || tempMute) {
2582 for (size_t j = 0; j < mOutputs.size(); j++) {
2583 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2584 // skip output if it does not share any device with current output
2585 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2586 == AUDIO_DEVICE_NONE) {
2589 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2590 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2591 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2592 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2593 if (desc->isStrategyActive((routing_strategy)i)) {
2594 // do tempMute only for current output
2595 if (tempMute && (desc == outputDesc)) {
2596 setStrategyMute((routing_strategy)i, true, curOutput);
2597 setStrategyMute((routing_strategy)i, false, curOutput,
2598 desc->latency() * 2, device);
2600 if ((tempMute && (desc == outputDesc)) || mute) {
2601 if (muteWaitMs < desc->latency()) {
2602 muteWaitMs = desc->latency();
2610 // FIXME: should not need to double latency if volume could be applied immediately by the
2611 // audioflinger mixer. We must account for the delay between now and the next time
2612 // the audioflinger thread for this output will process a buffer (which corresponds to
2613 // one buffer size, usually 1/2 or 1/4 of the latency).
2615 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2616 if (muteWaitMs > delayMs) {
2617 muteWaitMs -= delayMs;
2618 usleep(muteWaitMs * 1000);
2624 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2625 audio_devices_t device,
2629 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2630 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2631 AudioParameter param;
2632 uint32_t muteWaitMs;
2634 if (outputDesc->isDuplicated()) {
2635 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2636 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2639 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2641 if ((device != AUDIO_DEVICE_NONE) &&
2642 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2646 // filter devices according to output selected
2647 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2649 audio_devices_t prevDevice = outputDesc->mDevice;
2651 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2653 if (device != AUDIO_DEVICE_NONE) {
2654 outputDesc->mDevice = device;
2656 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2658 // Do not change the routing if:
2659 // - the requested device is AUDIO_DEVICE_NONE
2660 // - the requested device is the same as current device and force is not specified.
2661 // Doing this check here allows the caller to call setOutputDevice() without conditions
2662 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2663 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2667 ALOGV("setOutputDevice() changing device");
2669 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2670 mpClientInterface->setParameters(output, param.toString(), delayMs);
2672 // update stream volumes according to new device
2673 applyStreamVolumes(output, device, delayMs);
2678 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2679 uint32_t samplingRate,
2680 audio_format_t format,
2681 audio_channel_mask_t channelMask)
2683 // Choose an input profile based on the requested capture parameters: select the first available
2684 // profile supporting all requested parameters.
2686 for (size_t i = 0; i < mHwModules.size(); i++)
2688 if (mHwModules[i]->mHandle == 0) {
2691 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2693 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2694 if (profile->isCompatibleProfile(device, samplingRate, format,
2695 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
2703 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2705 uint32_t device = AUDIO_DEVICE_NONE;
2707 switch (inputSource) {
2708 case AUDIO_SOURCE_VOICE_UPLINK:
2709 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2710 device = AUDIO_DEVICE_IN_VOICE_CALL;
2715 case AUDIO_SOURCE_DEFAULT:
2716 case AUDIO_SOURCE_MIC:
2717 case AUDIO_SOURCE_VOICE_RECOGNITION:
2718 case AUDIO_SOURCE_HOTWORD:
2719 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2720 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2721 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2722 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2723 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2724 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2725 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2726 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2729 case AUDIO_SOURCE_CAMCORDER:
2730 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2731 device = AUDIO_DEVICE_IN_BACK_MIC;
2732 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2733 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2736 case AUDIO_SOURCE_VOICE_DOWNLINK:
2737 case AUDIO_SOURCE_VOICE_CALL:
2738 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2739 device = AUDIO_DEVICE_IN_VOICE_CALL;
2742 case AUDIO_SOURCE_REMOTE_SUBMIX:
2743 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2744 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2748 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2751 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2755 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2757 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2758 device &= ~AUDIO_DEVICE_BIT_IN;
2759 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2765 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2767 for (size_t i = 0; i < mInputs.size(); i++) {
2768 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2769 if ((input_descriptor->mRefCount > 0)
2770 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2771 return mInputs.keyAt(i);
2778 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2780 if (device == AUDIO_DEVICE_NONE) {
2781 // this happens when forcing a route update and no track is active on an output.
2782 // In this case the returned category is not important.
2783 device = AUDIO_DEVICE_OUT_SPEAKER;
2784 } else if (AudioSystem::popCount(device) > 1) {
2785 // Multiple device selection is either:
2786 // - speaker + one other device: give priority to speaker in this case.
2787 // - one A2DP device + another device: happens with duplicated output. In this case
2788 // retain the device on the A2DP output as the other must not correspond to an active
2789 // selection if not the speaker.
2790 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2791 device = AUDIO_DEVICE_OUT_SPEAKER;
2793 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2797 ALOGW_IF(AudioSystem::popCount(device) != 1,
2798 "getDeviceForVolume() invalid device combination: %08x",
2804 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2806 switch(getDeviceForVolume(device)) {
2807 case AUDIO_DEVICE_OUT_EARPIECE:
2808 return DEVICE_CATEGORY_EARPIECE;
2809 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2810 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2811 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2812 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2813 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2814 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2815 return DEVICE_CATEGORY_HEADSET;
2816 case AUDIO_DEVICE_OUT_SPEAKER:
2817 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2818 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2819 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2820 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2821 case AUDIO_DEVICE_OUT_USB_DEVICE:
2822 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
2824 return DEVICE_CATEGORY_SPEAKER;
2828 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2831 device_category deviceCategory = getDeviceCategory(device);
2832 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2834 // the volume index in the UI is relative to the min and max volume indices for this stream type
2835 int nbSteps = 1 + curve[VOLMAX].mIndex -
2836 curve[VOLMIN].mIndex;
2837 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2838 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2840 // find what part of the curve this index volume belongs to, or if it's out of bounds
2842 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2844 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2846 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2848 } else if (volIdx <= curve[VOLMAX].mIndex) {
2850 } else { // out of bounds
2854 // linear interpolation in the attenuation table in dB
2855 float decibels = curve[segment].mDBAttenuation +
2856 ((float)(volIdx - curve[segment].mIndex)) *
2857 ( (curve[segment+1].mDBAttenuation -
2858 curve[segment].mDBAttenuation) /
2859 ((float)(curve[segment+1].mIndex -
2860 curve[segment].mIndex)) );
2862 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2864 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2865 curve[segment].mIndex, volIdx,
2866 curve[segment+1].mIndex,
2867 curve[segment].mDBAttenuation,
2869 curve[segment+1].mDBAttenuation,
2872 return amplification;
2875 const AudioPolicyManagerBase::VolumeCurvePoint
2876 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2877 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2880 const AudioPolicyManagerBase::VolumeCurvePoint
2881 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2882 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2885 const AudioPolicyManagerBase::VolumeCurvePoint
2886 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2887 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2890 const AudioPolicyManagerBase::VolumeCurvePoint
2891 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2892 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2895 const AudioPolicyManagerBase::VolumeCurvePoint
2896 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
2897 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
2900 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2901 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
2902 // AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
2903 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2905 const AudioPolicyManagerBase::VolumeCurvePoint
2906 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2907 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2910 const AudioPolicyManagerBase::VolumeCurvePoint
2911 AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
2912 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
2915 const AudioPolicyManagerBase::VolumeCurvePoint
2916 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2917 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2920 const AudioPolicyManagerBase::VolumeCurvePoint
2921 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2922 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
2925 const AudioPolicyManagerBase::VolumeCurvePoint
2926 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2927 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
2930 const AudioPolicyManagerBase::VolumeCurvePoint
2931 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2932 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2933 { // AUDIO_STREAM_VOICE_CALL
2934 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2935 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2936 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2938 { // AUDIO_STREAM_SYSTEM
2939 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2940 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2941 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2943 { // AUDIO_STREAM_RING
2944 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2945 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2946 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2948 { // AUDIO_STREAM_MUSIC
2949 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2950 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2951 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2953 { // AUDIO_STREAM_ALARM
2954 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2955 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2956 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2958 { // AUDIO_STREAM_NOTIFICATION
2959 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2960 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2961 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2963 { // AUDIO_STREAM_BLUETOOTH_SCO
2964 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2965 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2966 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2968 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2969 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2970 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2971 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2973 { // AUDIO_STREAM_DTMF
2974 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2975 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2976 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2978 { // AUDIO_STREAM_TTS
2979 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2980 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2981 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2985 void AudioPolicyManagerBase::initializeVolumeCurves()
2987 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2988 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2989 mStreams[i].mVolumeCurve[j] =
2990 sVolumeProfiles[i][j];
2994 // Check availability of DRC on speaker path: if available, override some of the speaker curves
2995 if (mSpeakerDrcEnabled) {
2996 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2997 sDefaultSystemVolumeCurveDrc;
2998 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2999 sSpeakerSonificationVolumeCurveDrc;
3000 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3001 sSpeakerSonificationVolumeCurveDrc;
3002 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3003 sSpeakerSonificationVolumeCurveDrc;
3007 float AudioPolicyManagerBase::computeVolume(int stream,
3009 audio_io_handle_t output,
3010 audio_devices_t device)
3013 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3014 StreamDescriptor &streamDesc = mStreams[stream];
3016 if (device == AUDIO_DEVICE_NONE) {
3017 device = outputDesc->device();
3020 // if volume is not 0 (not muted), force media volume to max on digital output
3021 if (stream == AudioSystem::MUSIC &&
3022 index != mStreams[stream].mIndexMin &&
3023 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3024 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
3025 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
3026 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
3030 volume = volIndexToAmpl(device, streamDesc, index);
3032 // if a headset is connected, apply the following rules to ring tones and notifications
3033 // to avoid sound level bursts in user's ears:
3034 // - always attenuate ring tones and notifications volume by 6dB
3035 // - if music is playing, always limit the volume to current music volume,
3036 // with a minimum threshold at -36dB so that notification is always perceived.
3037 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3038 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3039 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3040 AUDIO_DEVICE_OUT_WIRED_HEADSET |
3041 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3042 ((stream_strategy == STRATEGY_SONIFICATION)
3043 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
3044 || (stream == AudioSystem::SYSTEM)
3045 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
3046 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
3047 streamDesc.mCanBeMuted) {
3048 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3049 // when the phone is ringing we must consider that music could have been paused just before
3050 // by the music application and behave as if music was active if the last music track was
3052 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
3053 mLimitRingtoneVolume) {
3054 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
3055 float musicVol = computeVolume(AudioSystem::MUSIC,
3056 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
3059 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3060 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3061 if (volume > minVol) {
3063 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3071 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
3073 audio_io_handle_t output,
3074 audio_devices_t device,
3079 // do not change actual stream volume if the stream is muted
3080 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3081 ALOGVV("checkAndSetVolume() stream %d muted count %d",
3082 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3086 // do not change in call volume if bluetooth is connected and vice versa
3087 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
3088 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
3089 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
3090 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
3091 return INVALID_OPERATION;
3094 float volume = computeVolume(stream, index, output, device);
3095 // We actually change the volume if:
3096 // - the float value returned by computeVolume() changed
3097 // - the force flag is set
3098 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3100 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3101 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3102 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3104 if (stream == AudioSystem::BLUETOOTH_SCO) {
3105 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
3107 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
3110 if (stream == AudioSystem::VOICE_CALL ||
3111 stream == AudioSystem::BLUETOOTH_SCO) {
3113 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3114 if (stream == AudioSystem::VOICE_CALL) {
3115 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3120 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3121 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3122 mLastVoiceVolume = voiceVolume;
3129 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
3130 audio_devices_t device,
3134 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3136 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3137 checkAndSetVolume(stream,
3138 mStreams[stream].getVolumeIndex(device),
3146 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
3148 audio_io_handle_t output,
3150 audio_devices_t device)
3152 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3153 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3154 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3155 setStreamMute(stream, on, output, delayMs, device);
3160 void AudioPolicyManagerBase::setStreamMute(int stream,
3162 audio_io_handle_t output,
3164 audio_devices_t device)
3166 StreamDescriptor &streamDesc = mStreams[stream];
3167 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3168 if (device == AUDIO_DEVICE_NONE) {
3169 device = outputDesc->device();
3172 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3173 stream, on, output, outputDesc->mMuteCount[stream], device);
3176 if (outputDesc->mMuteCount[stream] == 0) {
3177 if (streamDesc.mCanBeMuted &&
3178 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3179 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3180 checkAndSetVolume(stream, 0, output, device, delayMs);
3183 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3184 outputDesc->mMuteCount[stream]++;
3186 if (outputDesc->mMuteCount[stream] == 0) {
3187 ALOGV("setStreamMute() unmuting non muted stream!");
3190 if (--outputDesc->mMuteCount[stream] == 0) {
3191 checkAndSetVolume(stream,
3192 streamDesc.getVolumeIndex(device),
3200 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3202 // if the stream pertains to sonification strategy and we are in call we must
3203 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3204 // in the device used for phone strategy and play the tone if the selected device does not
3205 // interfere with the device used for phone strategy
3206 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3207 // many times as there are active tracks on the output
3208 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3209 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3210 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3211 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3212 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3213 stream, starting, outputDesc->mDevice, stateChange);
3214 if (outputDesc->mRefCount[stream]) {
3217 muteCount = outputDesc->mRefCount[stream];
3219 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3220 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3221 for (int i = 0; i < muteCount; i++) {
3222 setStreamMute(stream, starting, mPrimaryOutput);
3225 ALOGV("handleIncallSonification() high visibility");
3226 if (outputDesc->device() &
3227 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3228 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3229 for (int i = 0; i < muteCount; i++) {
3230 setStreamMute(stream, starting, mPrimaryOutput);
3234 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3236 mpClientInterface->stopTone();
3243 bool AudioPolicyManagerBase::isInCall()
3245 return isStateInCall(mPhoneState);
3248 bool AudioPolicyManagerBase::isStateInCall(int state) {
3249 return ((state == AudioSystem::MODE_IN_CALL) ||
3250 (state == AudioSystem::MODE_IN_COMMUNICATION));
3253 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3255 return MAX_EFFECTS_CPU_LOAD;
3258 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3260 return MAX_EFFECTS_MEMORY;
3263 // --- AudioOutputDescriptor class implementation
3265 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3266 const IOProfile *profile)
3267 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3268 mChannelMask(0), mLatency(0),
3269 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3270 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3272 // clear usage count for all stream types
3273 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3275 mCurVolume[i] = -1.0;
3279 for (int i = 0; i < NUM_STRATEGIES; i++) {
3280 mStrategyMutedByDevice[i] = false;
3282 if (profile != NULL) {
3283 mSamplingRate = profile->mSamplingRates[0];
3284 mFormat = profile->mFormats[0];
3285 mChannelMask = profile->mChannelMasks[0];
3286 mFlags = profile->mFlags;
3290 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3292 if (isDuplicated()) {
3293 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3299 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3301 if (isDuplicated()) {
3302 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3308 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3309 const AudioOutputDescriptor *outputDesc)
3311 if (isDuplicated()) {
3312 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3313 } else if (outputDesc->isDuplicated()){
3314 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3316 return (mProfile->mModule == outputDesc->mProfile->mModule);
3320 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3322 // forward usage count change to attached outputs
3323 if (isDuplicated()) {
3324 mOutput1->changeRefCount(stream, delta);
3325 mOutput2->changeRefCount(stream, delta);
3327 if ((delta + (int)mRefCount[stream]) < 0) {
3328 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3329 mRefCount[stream] = 0;
3332 mRefCount[stream] += delta;
3333 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3336 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3338 if (isDuplicated()) {
3339 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3341 return mProfile->mSupportedDevices ;
3345 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3347 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3350 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3352 nsecs_t sysTime) const
3354 if ((sysTime == 0) && (inPastMs != 0)) {
3355 sysTime = systemTime();
3357 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3358 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3359 (NUM_STRATEGIES == strategy)) &&
3360 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3367 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3369 nsecs_t sysTime) const
3371 if (mRefCount[stream] != 0) {
3374 if (inPastMs == 0) {
3378 sysTime = systemTime();
3380 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3387 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3389 const size_t SIZE = 256;
3393 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3394 result.append(buffer);
3395 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3396 result.append(buffer);
3397 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3398 result.append(buffer);
3399 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3400 result.append(buffer);
3401 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3402 result.append(buffer);
3403 snprintf(buffer, SIZE, " Devices %08x\n", device());
3404 result.append(buffer);
3405 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3406 result.append(buffer);
3407 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3408 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3409 result.append(buffer);
3411 write(fd, result.string(), result.size());
3416 // --- AudioInputDescriptor class implementation
3418 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3419 : mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
3420 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3421 mInputSource(0), mProfile(profile)
3425 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3427 const size_t SIZE = 256;
3431 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3432 result.append(buffer);
3433 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3434 result.append(buffer);
3435 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3436 result.append(buffer);
3437 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3438 result.append(buffer);
3439 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3440 result.append(buffer);
3441 write(fd, result.string(), result.size());
3446 // --- StreamDescriptor class implementation
3448 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3449 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3451 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3454 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3456 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3457 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3458 if (mIndexCur.indexOfKey(device) < 0) {
3459 device = AUDIO_DEVICE_OUT_DEFAULT;
3461 return mIndexCur.valueFor(device);
3464 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3466 const size_t SIZE = 256;
3470 snprintf(buffer, SIZE, "%s %02d %02d ",
3471 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3472 result.append(buffer);
3473 for (size_t i = 0; i < mIndexCur.size(); i++) {
3474 snprintf(buffer, SIZE, "%04x : %02d, ",
3476 mIndexCur.valueAt(i));
3477 result.append(buffer);
3479 result.append("\n");
3481 write(fd, result.string(), result.size());
3484 // --- EffectDescriptor class implementation
3486 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3488 const size_t SIZE = 256;
3492 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3493 result.append(buffer);
3494 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3495 result.append(buffer);
3496 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3497 result.append(buffer);
3498 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3499 result.append(buffer);
3500 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3501 result.append(buffer);
3502 write(fd, result.string(), result.size());
3507 // --- IOProfile class implementation
3509 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3510 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3514 AudioPolicyManagerBase::HwModule::~HwModule()
3516 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3517 delete mOutputProfiles[i];
3519 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3520 delete mInputProfiles[i];
3522 free((void *)mName);
3525 void AudioPolicyManagerBase::HwModule::dump(int fd)
3527 const size_t SIZE = 256;
3531 snprintf(buffer, SIZE, " - name: %s\n", mName);
3532 result.append(buffer);
3533 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3534 result.append(buffer);
3535 write(fd, result.string(), result.size());
3536 if (mOutputProfiles.size()) {
3537 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
3538 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3539 snprintf(buffer, SIZE, " output %zu:\n", i);
3540 write(fd, buffer, strlen(buffer));
3541 mOutputProfiles[i]->dump(fd);
3544 if (mInputProfiles.size()) {
3545 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
3546 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3547 snprintf(buffer, SIZE, " input %zu:\n", i);
3548 write(fd, buffer, strlen(buffer));
3549 mInputProfiles[i]->dump(fd);
3554 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3555 : mFlags((audio_output_flags_t)0), mModule(module)
3559 AudioPolicyManagerBase::IOProfile::~IOProfile()
3563 // checks if the IO profile is compatible with specified parameters.
3564 // Sampling rate, format and channel mask must be specified in order to
3565 // get a valid a match
3566 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3567 uint32_t samplingRate,
3568 audio_format_t format,
3569 audio_channel_mask_t channelMask,
3570 audio_output_flags_t flags) const
3572 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3576 if ((mSupportedDevices & device) != device) {
3579 if ((mFlags & flags) != flags) {
3583 for (i = 0; i < mSamplingRates.size(); i++)
3585 if (mSamplingRates[i] == samplingRate) {
3589 if (i == mSamplingRates.size()) {
3592 for (i = 0; i < mFormats.size(); i++)
3594 if (mFormats[i] == format) {
3598 if (i == mFormats.size()) {
3601 for (i = 0; i < mChannelMasks.size(); i++)
3603 if (mChannelMasks[i] == channelMask) {
3607 if (i == mChannelMasks.size()) {
3613 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3615 const size_t SIZE = 256;
3619 snprintf(buffer, SIZE, " - sampling rates: ");
3620 result.append(buffer);
3621 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3622 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3623 result.append(buffer);
3624 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3627 snprintf(buffer, SIZE, " - channel masks: ");
3628 result.append(buffer);
3629 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3630 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3631 result.append(buffer);
3632 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3635 snprintf(buffer, SIZE, " - formats: ");
3636 result.append(buffer);
3637 for (size_t i = 0; i < mFormats.size(); i++) {
3638 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3639 result.append(buffer);
3640 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3643 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
3644 result.append(buffer);
3645 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3646 result.append(buffer);
3648 write(fd, result.string(), result.size());
3651 // --- audio_policy.conf file parsing
3653 struct StringToEnum {
3658 #define STRING_TO_ENUM(string) { #string, string }
3659 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3661 const struct StringToEnum sDeviceNameToEnumTable[] = {
3662 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3663 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3664 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3665 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3666 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3667 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3668 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3669 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3670 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3671 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3672 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3673 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3674 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3675 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3676 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3677 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3678 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3679 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3680 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3681 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3682 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3683 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3684 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3685 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
3688 const struct StringToEnum sFlagNameToEnumTable[] = {
3689 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3690 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3691 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3692 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3693 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3694 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3697 const struct StringToEnum sFormatNameToEnumTable[] = {
3698 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3699 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3700 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
3701 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
3702 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
3703 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
3704 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3705 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3706 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3709 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3710 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3711 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3712 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3713 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3716 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3717 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3718 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3719 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3723 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3727 for (size_t i = 0; i < size; i++) {
3728 if (strcmp(table[i].name, name) == 0) {
3729 ALOGV("stringToEnum() found %s", table[i].name);
3730 return table[i].value;
3736 bool AudioPolicyManagerBase::stringToBool(const char *value)
3738 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
3741 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3745 // it is OK to cast name to non const here as we are not going to use it after
3746 // strtok() modifies it
3747 char *flagName = strtok(name, "|");
3748 while (flagName != NULL) {
3749 if (strlen(flagName) != 0) {
3750 flag |= stringToEnum(sFlagNameToEnumTable,
3751 ARRAY_SIZE(sFlagNameToEnumTable),
3754 flagName = strtok(NULL, "|");
3756 //force direct flag if offload flag is set: offloading implies a direct output stream
3757 // and all common behaviors are driven by checking only the direct flag
3758 // this should normally be set appropriately in the policy configuration file
3759 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3760 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
3763 return (audio_output_flags_t)flag;
3766 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3768 uint32_t device = 0;
3770 char *devName = strtok(name, "|");
3771 while (devName != NULL) {
3772 if (strlen(devName) != 0) {
3773 device |= stringToEnum(sDeviceNameToEnumTable,
3774 ARRAY_SIZE(sDeviceNameToEnumTable),
3777 devName = strtok(NULL, "|");
3782 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3784 char *str = strtok(name, "|");
3786 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3787 // rates should be read from the output stream after it is opened for the first time
3788 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3789 profile->mSamplingRates.add(0);
3793 while (str != NULL) {
3794 uint32_t rate = atoi(str);
3796 ALOGV("loadSamplingRates() adding rate %d", rate);
3797 profile->mSamplingRates.add(rate);
3799 str = strtok(NULL, "|");
3804 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3806 char *str = strtok(name, "|");
3808 // by convention, "0' in the first entry in mFormats indicates the supported formats
3809 // should be read from the output stream after it is opened for the first time
3810 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3811 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3815 while (str != NULL) {
3816 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3817 ARRAY_SIZE(sFormatNameToEnumTable),
3819 if (format != AUDIO_FORMAT_DEFAULT) {
3820 profile->mFormats.add(format);
3822 str = strtok(NULL, "|");
3827 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3829 const char *str = strtok(name, "|");
3831 ALOGV("loadInChannels() %s", name);
3833 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3834 profile->mChannelMasks.add(0);
3838 while (str != NULL) {
3839 audio_channel_mask_t channelMask =
3840 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3841 ARRAY_SIZE(sInChannelsNameToEnumTable),
3843 if (channelMask != 0) {
3844 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3845 profile->mChannelMasks.add(channelMask);
3847 str = strtok(NULL, "|");
3852 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3854 const char *str = strtok(name, "|");
3856 ALOGV("loadOutChannels() %s", name);
3858 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3859 // masks should be read from the output stream after it is opened for the first time
3860 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3861 profile->mChannelMasks.add(0);
3865 while (str != NULL) {
3866 audio_channel_mask_t channelMask =
3867 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3868 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3870 if (channelMask != 0) {
3871 profile->mChannelMasks.add(channelMask);
3873 str = strtok(NULL, "|");
3878 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3880 cnode *node = root->first_child;
3882 IOProfile *profile = new IOProfile(module);
3885 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3886 loadSamplingRates((char *)node->value, profile);
3887 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3888 loadFormats((char *)node->value, profile);
3889 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3890 loadInChannels((char *)node->value, profile);
3891 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3892 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3896 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3897 "loadInput() invalid supported devices");
3898 ALOGW_IF(profile->mChannelMasks.size() == 0,
3899 "loadInput() invalid supported channel masks");
3900 ALOGW_IF(profile->mSamplingRates.size() == 0,
3901 "loadInput() invalid supported sampling rates");
3902 ALOGW_IF(profile->mFormats.size() == 0,
3903 "loadInput() invalid supported formats");
3904 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3905 (profile->mChannelMasks.size() != 0) &&
3906 (profile->mSamplingRates.size() != 0) &&
3907 (profile->mFormats.size() != 0)) {
3909 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3911 module->mInputProfiles.add(profile);
3919 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3921 cnode *node = root->first_child;
3923 IOProfile *profile = new IOProfile(module);
3926 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3927 loadSamplingRates((char *)node->value, profile);
3928 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3929 loadFormats((char *)node->value, profile);
3930 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3931 loadOutChannels((char *)node->value, profile);
3932 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3933 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3934 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3935 profile->mFlags = parseFlagNames((char *)node->value);
3939 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3940 "loadOutput() invalid supported devices");
3941 ALOGW_IF(profile->mChannelMasks.size() == 0,
3942 "loadOutput() invalid supported channel masks");
3943 ALOGW_IF(profile->mSamplingRates.size() == 0,
3944 "loadOutput() invalid supported sampling rates");
3945 ALOGW_IF(profile->mFormats.size() == 0,
3946 "loadOutput() invalid supported formats");
3947 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3948 (profile->mChannelMasks.size() != 0) &&
3949 (profile->mSamplingRates.size() != 0) &&
3950 (profile->mFormats.size() != 0)) {
3952 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3953 profile->mSupportedDevices, profile->mFlags);
3955 module->mOutputProfiles.add(profile);
3963 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3965 cnode *node = config_find(root, OUTPUTS_TAG);
3966 status_t status = NAME_NOT_FOUND;
3968 HwModule *module = new HwModule(root->name);
3971 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3973 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3975 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
3976 mHasRemoteSubmix = true;
3979 node = node->first_child;
3981 ALOGV("loadHwModule() loading output %s", node->name);
3982 status_t tmpStatus = loadOutput(node, module);
3983 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3989 node = config_find(root, INPUTS_TAG);
3991 node = node->first_child;
3993 ALOGV("loadHwModule() loading input %s", node->name);
3994 status_t tmpStatus = loadInput(node, module);
3995 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4001 if (status == NO_ERROR) {
4002 mHwModules.add(module);
4008 void AudioPolicyManagerBase::loadHwModules(cnode *root)
4010 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
4015 node = node->first_child;
4017 ALOGV("loadHwModules() loading module %s", node->name);
4023 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
4025 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4029 node = node->first_child;
4031 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
4032 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
4033 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
4034 "loadGlobalConfig() no attached output devices");
4035 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
4036 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
4037 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
4038 ARRAY_SIZE(sDeviceNameToEnumTable),
4039 (char *)node->value);
4040 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
4041 "loadGlobalConfig() default device not specified");
4042 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
4043 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
4044 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
4045 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
4046 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4047 mSpeakerDrcEnabled = stringToBool((char *)node->value);
4048 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4054 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
4059 data = (char *)load_file(path, NULL);
4063 root = config_node("", "");
4064 config_load(root, data);
4066 loadGlobalConfig(root);
4067 loadHwModules(root);
4073 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4078 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
4083 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
4084 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
4085 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
4087 module = new HwModule("primary");
4089 profile = new IOProfile(module);
4090 profile->mSamplingRates.add(44100);
4091 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4092 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4093 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
4094 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4095 module->mOutputProfiles.add(profile);
4097 profile = new IOProfile(module);
4098 profile->mSamplingRates.add(8000);
4099 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4100 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4101 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
4102 module->mInputProfiles.add(profile);
4104 mHwModules.add(module);
4107 }; // namespace android