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
34 #include <utils/Log.h>
35 #include <hardware_legacy/AudioPolicyManagerBase.h>
36 #include <hardware/audio_effect.h>
37 #include <hardware/audio.h>
39 #include <hardware_legacy/audio_policy_conf.h>
40 #include <cutils/properties.h>
42 namespace android_audio_legacy {
44 // ----------------------------------------------------------------------------
45 // AudioPolicyInterface implementation
46 // ----------------------------------------------------------------------------
49 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
50 AudioSystem::device_connection_state state,
51 const char *device_address)
53 SortedVector <audio_io_handle_t> outputs;
55 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
57 // connect/disconnect only 1 device at a time
58 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
60 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
61 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
65 // handle output devices
66 if (audio_is_output_device(device)) {
68 if (!mHasA2dp && audio_is_a2dp_device(device)) {
69 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
72 if (!mHasUsb && audio_is_usb_device(device)) {
73 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
76 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
77 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
81 // save a copy of the opened output descriptors before any output is opened or closed
82 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
83 mPreviousOutputs = mOutputs;
86 // handle output device connection
87 case AudioSystem::DEVICE_STATE_AVAILABLE:
88 if (mAvailableOutputDevices & device) {
89 ALOGW("setDeviceConnectionState() device already connected: %x", device);
90 return INVALID_OPERATION;
92 ALOGV("setDeviceConnectionState() connecting device %x", device);
94 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
95 return INVALID_OPERATION;
97 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
99 // register new device as available
100 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
102 if (!outputs.isEmpty()) {
104 if (mHasA2dp && audio_is_a2dp_device(device)) {
105 // handle A2DP device connection
106 AudioParameter param;
107 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
108 paramStr = param.toString();
109 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
110 mA2dpSuspended = false;
111 } else if (audio_is_bluetooth_sco_device(device)) {
112 // handle SCO device connection
113 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
114 } else if (mHasUsb && audio_is_usb_device(device)) {
115 // handle USB device connection
116 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
117 paramStr = mUsbCardAndDevice;
119 // not currently handling multiple simultaneous submixes: ignoring remote submix
121 if (!paramStr.isEmpty()) {
122 for (size_t i = 0; i < outputs.size(); i++) {
123 mpClientInterface->setParameters(outputs[i], paramStr);
128 // handle output device disconnection
129 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
130 if (!(mAvailableOutputDevices & device)) {
131 ALOGW("setDeviceConnectionState() device not connected: %x", device);
132 return INVALID_OPERATION;
135 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
136 // remove device from available output devices
137 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
139 checkOutputsForDevice(device, state, outputs);
140 if (mHasA2dp && audio_is_a2dp_device(device)) {
141 // handle A2DP device disconnection
142 mA2dpDeviceAddress = "";
143 mA2dpSuspended = false;
144 } else if (audio_is_bluetooth_sco_device(device)) {
145 // handle SCO device disconnection
146 mScoDeviceAddress = "";
147 } else if (mHasUsb && audio_is_usb_device(device)) {
148 // handle USB device disconnection
149 mUsbCardAndDevice = "";
151 // not currently handling multiple simultaneous submixes: ignoring remote submix
156 ALOGE("setDeviceConnectionState() invalid state: %x", state);
161 checkOutputForAllStrategies();
162 // outputs must be closed after checkOutputForAllStrategies() is executed
163 if (!outputs.isEmpty()) {
164 for (size_t i = 0; i < outputs.size(); i++) {
165 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
166 // close unused outputs after device disconnection or direct outputs that have been
167 // opened by checkOutputsForDevice() to query dynamic parameters
168 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
169 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
170 (desc->mDirectOpenCount == 0))) {
171 closeOutput(outputs[i]);
176 updateDevicesAndOutputs();
177 for (size_t i = 0; i < mOutputs.size(); i++) {
178 // do not force device change on duplicated output because if device is 0, it will
179 // also force a device 0 for the two outputs it is duplicated to which may override
180 // a valid device selection on those outputs.
181 setOutputDevice(mOutputs.keyAt(i),
182 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
183 !mOutputs.valueAt(i)->isDuplicated(),
187 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
188 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
189 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
190 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
191 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
192 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
197 // handle input devices
198 if (audio_is_input_device(device)) {
202 // handle input device connection
203 case AudioSystem::DEVICE_STATE_AVAILABLE: {
204 if (mAvailableInputDevices & device) {
205 ALOGW("setDeviceConnectionState() device already connected: %d", device);
206 return INVALID_OPERATION;
208 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
212 // handle input device disconnection
213 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
214 if (!(mAvailableInputDevices & device)) {
215 ALOGW("setDeviceConnectionState() device not connected: %d", device);
216 return INVALID_OPERATION;
218 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
222 ALOGE("setDeviceConnectionState() invalid state: %x", state);
226 audio_io_handle_t activeInput = getActiveInput();
227 if (activeInput != 0) {
228 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
229 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
230 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
231 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
232 inputDesc->mDevice, newDevice, activeInput);
233 inputDesc->mDevice = newDevice;
234 AudioParameter param = AudioParameter();
235 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
236 mpClientInterface->setParameters(activeInput, param.toString());
243 ALOGW("setDeviceConnectionState() invalid device: %x", device);
247 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
248 const char *device_address)
250 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
251 String8 address = String8(device_address);
252 if (audio_is_output_device(device)) {
253 if (device & mAvailableOutputDevices) {
254 if (audio_is_a2dp_device(device) &&
255 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
258 if (audio_is_bluetooth_sco_device(device) &&
259 address != "" && mScoDeviceAddress != address) {
262 if (audio_is_usb_device(device) &&
263 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
264 ALOGE("getDeviceConnectionState() invalid device: %x", device);
267 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
270 state = AudioSystem::DEVICE_STATE_AVAILABLE;
272 } else if (audio_is_input_device(device)) {
273 if (device & mAvailableInputDevices) {
274 state = AudioSystem::DEVICE_STATE_AVAILABLE;
281 void AudioPolicyManagerBase::setPhoneState(int state)
283 ALOGV("setPhoneState() state %d", state);
284 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
285 if (state < 0 || state >= AudioSystem::NUM_MODES) {
286 ALOGW("setPhoneState() invalid state %d", state);
290 if (state == mPhoneState ) {
291 ALOGW("setPhoneState() setting same state %d", state);
295 // if leaving call state, handle special case of active streams
296 // pertaining to sonification strategy see handleIncallSonification()
298 ALOGV("setPhoneState() in call state management: new state is %d", state);
299 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
300 handleIncallSonification(stream, false, true);
304 // store previous phone state for management of sonification strategy below
305 int oldState = mPhoneState;
309 // are we entering or starting a call
310 if (!isStateInCall(oldState) && isStateInCall(state)) {
311 ALOGV(" Entering call in setPhoneState()");
312 // force routing command to audio hardware when starting a call
313 // even if no device change is needed
315 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
316 ALOGV(" Exiting call in setPhoneState()");
317 // force routing command to audio hardware when exiting a call
318 // even if no device change is needed
320 } else if (isStateInCall(state) && (state != oldState)) {
321 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
322 // force routing command to audio hardware when switching between telephony and VoIP
323 // even if no device change is needed
327 // check for device and output changes triggered by new phone state
328 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
330 checkOutputForAllStrategies();
331 updateDevicesAndOutputs();
333 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
335 // force routing command to audio hardware when ending call
336 // even if no device change is needed
337 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
338 newDevice = hwOutputDesc->device();
342 if (isStateInCall(state)) {
343 nsecs_t sysTime = systemTime();
344 for (size_t i = 0; i < mOutputs.size(); i++) {
345 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
346 // mute media and sonification strategies and delay device switch by the largest
347 // latency of any output where either strategy is active.
348 // This avoid sending the ring tone or music tail into the earpiece or headset.
349 if ((desc->isStrategyActive(STRATEGY_MEDIA,
350 SONIFICATION_HEADSET_MUSIC_DELAY,
352 desc->isStrategyActive(STRATEGY_SONIFICATION,
353 SONIFICATION_HEADSET_MUSIC_DELAY,
355 (delayMs < (int)desc->mLatency*2)) {
356 delayMs = desc->mLatency*2;
358 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
359 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
360 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
361 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
362 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
363 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
367 // change routing is necessary
368 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
370 // if entering in call state, handle special case of active streams
371 // pertaining to sonification strategy see handleIncallSonification()
372 if (isStateInCall(state)) {
373 ALOGV("setPhoneState() in call state management: new state is %d", state);
374 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
375 handleIncallSonification(stream, true, true);
379 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
380 if (state == AudioSystem::MODE_RINGTONE &&
381 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
382 mLimitRingtoneVolume = true;
384 mLimitRingtoneVolume = false;
388 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
390 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
392 bool forceVolumeReeval = false;
394 case AudioSystem::FOR_COMMUNICATION:
395 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
396 config != AudioSystem::FORCE_NONE) {
397 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
400 forceVolumeReeval = true;
401 mForceUse[usage] = config;
403 case AudioSystem::FOR_MEDIA:
404 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
405 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
406 config != AudioSystem::FORCE_ANALOG_DOCK &&
407 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
408 config != AudioSystem::FORCE_NO_BT_A2DP) {
409 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
412 mForceUse[usage] = config;
414 case AudioSystem::FOR_RECORD:
415 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
416 config != AudioSystem::FORCE_NONE) {
417 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
420 mForceUse[usage] = config;
422 case AudioSystem::FOR_DOCK:
423 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
424 config != AudioSystem::FORCE_BT_DESK_DOCK &&
425 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
426 config != AudioSystem::FORCE_ANALOG_DOCK &&
427 config != AudioSystem::FORCE_DIGITAL_DOCK) {
428 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
430 forceVolumeReeval = true;
431 mForceUse[usage] = config;
433 case AudioSystem::FOR_SYSTEM:
434 if (config != AudioSystem::FORCE_NONE &&
435 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
436 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
438 forceVolumeReeval = true;
439 mForceUse[usage] = config;
442 ALOGW("setForceUse() invalid usage %d", usage);
446 // check for device and output changes triggered by new force usage
448 checkOutputForAllStrategies();
449 updateDevicesAndOutputs();
450 for (size_t i = 0; i < mOutputs.size(); i++) {
451 audio_io_handle_t output = mOutputs.keyAt(i);
452 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
453 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
454 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
455 applyStreamVolumes(output, newDevice, 0, true);
459 audio_io_handle_t activeInput = getActiveInput();
460 if (activeInput != 0) {
461 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
462 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
463 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
464 ALOGV("setForceUse() changing device from %x to %x for input %d",
465 inputDesc->mDevice, newDevice, activeInput);
466 inputDesc->mDevice = newDevice;
467 AudioParameter param = AudioParameter();
468 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
469 mpClientInterface->setParameters(activeInput, param.toString());
475 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
477 return mForceUse[usage];
480 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
482 ALOGV("setSystemProperty() property %s, value %s", property, value);
485 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
486 audio_devices_t device,
487 uint32_t samplingRate,
489 uint32_t channelMask,
490 audio_output_flags_t flags)
492 for (size_t i = 0; i < mHwModules.size(); i++) {
493 if (mHwModules[i]->mHandle == 0) {
496 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
497 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
498 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
499 if (profile->isCompatibleProfile(device, samplingRate, format,
501 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
502 if (mAvailableOutputDevices & profile->mSupportedDevices) {
503 return mHwModules[i]->mOutputProfiles[j];
506 } else if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
507 if (profile->isCompatibleProfile(device, samplingRate, format,
509 AUDIO_OUTPUT_FLAG_DIRECT)) {
510 if (mAvailableOutputDevices & profile->mSupportedDevices) {
511 return mHwModules[i]->mOutputProfiles[j];
520 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
521 uint32_t samplingRate,
523 uint32_t channelMask,
524 AudioSystem::output_flags flags,
525 const audio_offload_info_t *offloadInfo)
527 audio_io_handle_t output = 0;
528 uint32_t latency = 0;
529 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
530 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
531 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
532 device, stream, samplingRate, format, channelMask, flags);
534 #ifdef AUDIO_POLICY_TEST
535 if (mCurOutput != 0) {
536 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
537 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
539 if (mTestOutputs[mCurOutput] == 0) {
540 ALOGV("getOutput() opening test output");
541 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
542 outputDesc->mDevice = mTestDevice;
543 outputDesc->mSamplingRate = mTestSamplingRate;
544 outputDesc->mFormat = mTestFormat;
545 outputDesc->mChannelMask = mTestChannels;
546 outputDesc->mLatency = mTestLatencyMs;
547 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
548 outputDesc->mRefCount[stream] = 0;
549 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
550 &outputDesc->mSamplingRate,
551 &outputDesc->mFormat,
552 &outputDesc->mChannelMask,
553 &outputDesc->mLatency,
556 if (mTestOutputs[mCurOutput]) {
557 AudioParameter outputCmd = AudioParameter();
558 outputCmd.addInt(String8("set_id"),mCurOutput);
559 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
560 addOutput(mTestOutputs[mCurOutput], outputDesc);
563 return mTestOutputs[mCurOutput];
565 #endif //AUDIO_POLICY_TEST
567 // open a direct output if required by specified parameters
568 //force direct flag if offload flag is set: offloading implies a direct output stream
569 // and all common behaviors are driven by checking only the direct flag
570 // this should normally be set appropriately in the policy configuration file
571 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
572 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
575 IOProfile *profile = getProfileForDirectOutput(device,
579 (audio_output_flags_t)flags);
580 if (profile != NULL) {
581 AudioOutputDescriptor *outputDesc = NULL;
583 for (size_t i = 0; i < mOutputs.size(); i++) {
584 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
585 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
587 // reuse direct output if currently open and configured with same parameters
588 if ((samplingRate == outputDesc->mSamplingRate) &&
589 (format == outputDesc->mFormat) &&
590 (channelMask == outputDesc->mChannelMask)) {
591 outputDesc->mDirectOpenCount++;
592 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
593 return mOutputs.keyAt(i);
597 // close direct output if currently open and configured with different parameters
598 if (outputDesc != NULL) {
599 closeOutput(outputDesc->mId);
601 outputDesc = new AudioOutputDescriptor(profile);
602 outputDesc->mDevice = device;
603 outputDesc->mSamplingRate = samplingRate;
604 outputDesc->mFormat = (audio_format_t)format;
605 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
606 outputDesc->mLatency = 0;
607 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
608 outputDesc->mRefCount[stream] = 0;
609 outputDesc->mStopTime[stream] = 0;
610 outputDesc->mDirectOpenCount = 1;
611 output = mpClientInterface->openOutput(profile->mModule->mHandle,
612 &outputDesc->mDevice,
613 &outputDesc->mSamplingRate,
614 &outputDesc->mFormat,
615 &outputDesc->mChannelMask,
616 &outputDesc->mLatency,
620 // only accept an output with the requested parameters
622 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
623 (format != 0 && format != outputDesc->mFormat) ||
624 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
625 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
626 "format %d %d, channelMask %04x %04x", output, samplingRate,
627 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
628 outputDesc->mChannelMask);
630 mpClientInterface->closeOutput(output);
635 addOutput(output, outputDesc);
636 mPreviousOutputs = mOutputs;
637 ALOGV("getOutput() returns new direct output %d", output);
641 // ignoring channel mask due to downmix capability in mixer
643 // open a non direct output
645 // for non direct outputs, only PCM is supported
646 if (audio_is_linear_pcm((audio_format_t)format)) {
647 // get which output is suitable for the specified stream. The actual
648 // routing change will happen when startOutput() will be called
649 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
651 output = selectOutput(outputs, flags);
653 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
654 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
656 ALOGV("getOutput() returns output %d", output);
661 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
662 AudioSystem::output_flags flags)
664 // select one output among several that provide a path to a particular device or set of
665 // devices (the list was previously build by getOutputsForDevice()).
666 // The priority is as follows:
667 // 1: the output with the highest number of requested policy flags
668 // 2: the primary output
669 // 3: the first output in the list
671 if (outputs.size() == 0) {
674 if (outputs.size() == 1) {
678 int maxCommonFlags = 0;
679 audio_io_handle_t outputFlags = 0;
680 audio_io_handle_t outputPrimary = 0;
682 for (size_t i = 0; i < outputs.size(); i++) {
683 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
684 if (!outputDesc->isDuplicated()) {
685 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
686 if (commonFlags > maxCommonFlags) {
687 outputFlags = outputs[i];
688 maxCommonFlags = commonFlags;
689 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
691 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
692 outputPrimary = outputs[i];
697 if (outputFlags != 0) {
700 if (outputPrimary != 0) {
701 return outputPrimary;
707 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
708 AudioSystem::stream_type stream,
711 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
712 ssize_t index = mOutputs.indexOfKey(output);
714 ALOGW("startOutput() unknow output %d", output);
718 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
720 // increment usage count for this stream on the requested output:
721 // NOTE that the usage count is the same for duplicated output and hardware output which is
722 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
723 outputDesc->changeRefCount(stream, 1);
725 if (outputDesc->mRefCount[stream] == 1) {
726 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
727 routing_strategy strategy = getStrategy(stream);
728 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
729 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
732 for (size_t i = 0; i < mOutputs.size(); i++) {
733 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
734 if (desc != outputDesc) {
735 // force a device change if any other output is managed by the same hw
736 // module and has a current device selection that differs from selected device.
737 // In this case, the audio HAL must receive the new device selection so that it can
738 // change the device currently selected by the other active output.
739 if (outputDesc->sharesHwModuleWith(desc) &&
740 desc->device() != newDevice) {
743 // wait for audio on other active outputs to be presented when starting
744 // a notification so that audio focus effect can propagate.
745 uint32_t latency = desc->latency();
746 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
751 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
753 // handle special case for sonification while in call
755 handleIncallSonification(stream, true, false);
758 // apply volume rules for current stream and device if necessary
759 checkAndSetVolume(stream,
760 mStreams[stream].getVolumeIndex(newDevice),
764 // update the outputs if starting an output with a stream that can affect notification
766 handleNotificationRoutingForStream(stream);
767 if (waitMs > muteWaitMs) {
768 usleep((waitMs - muteWaitMs) * 2 * 1000);
775 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
776 AudioSystem::stream_type stream,
779 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
780 ssize_t index = mOutputs.indexOfKey(output);
782 ALOGW("stopOutput() unknow output %d", output);
786 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
788 // handle special case for sonification while in call
790 handleIncallSonification(stream, false, false);
793 if (outputDesc->mRefCount[stream] > 0) {
794 // decrement usage count of this stream on the output
795 outputDesc->changeRefCount(stream, -1);
796 // store time at which the stream was stopped - see isStreamActive()
797 if (outputDesc->mRefCount[stream] == 0) {
798 outputDesc->mStopTime[stream] = systemTime();
799 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
800 // delay the device switch by twice the latency because stopOutput() is executed when
801 // the track stop() command is received and at that time the audio track buffer can
802 // still contain data that needs to be drained. The latency only covers the audio HAL
803 // and kernel buffers. Also the latency does not always include additional delay in the
804 // audio path (audio DSP, CODEC ...)
805 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
807 // force restoring the device selection on other active outputs if it differs from the
808 // one being selected for this output
809 for (size_t i = 0; i < mOutputs.size(); i++) {
810 audio_io_handle_t curOutput = mOutputs.keyAt(i);
811 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
812 if (curOutput != output &&
814 outputDesc->sharesHwModuleWith(desc) &&
815 (newDevice != desc->device())) {
816 setOutputDevice(curOutput,
817 getNewDevice(curOutput, false /*fromCache*/),
819 outputDesc->mLatency*2);
822 // update the outputs if stopping one with a stream that can affect notification routing
823 handleNotificationRoutingForStream(stream);
827 ALOGW("stopOutput() refcount is already 0 for output %d", output);
828 return INVALID_OPERATION;
832 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
834 ALOGV("releaseOutput() %d", output);
835 ssize_t index = mOutputs.indexOfKey(output);
837 ALOGW("releaseOutput() releasing unknown output %d", output);
841 #ifdef AUDIO_POLICY_TEST
842 int testIndex = testOutputIndex(output);
843 if (testIndex != 0) {
844 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
845 if (outputDesc->isActive()) {
846 mpClientInterface->closeOutput(output);
847 delete mOutputs.valueAt(index);
848 mOutputs.removeItem(output);
849 mTestOutputs[testIndex] = 0;
853 #endif //AUDIO_POLICY_TEST
855 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
856 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
857 if (desc->mDirectOpenCount <= 0) {
858 ALOGW("releaseOutput() invalid open count %d for output %d",
859 desc->mDirectOpenCount, output);
862 if (--desc->mDirectOpenCount == 0) {
868 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
869 uint32_t samplingRate,
871 uint32_t channelMask,
872 AudioSystem::audio_in_acoustics acoustics)
874 audio_io_handle_t input = 0;
875 audio_devices_t device = getDeviceForInputSource(inputSource);
877 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
878 inputSource, samplingRate, format, channelMask, acoustics);
880 if (device == AUDIO_DEVICE_NONE) {
881 ALOGW("getInput() could not find device for inputSource %d", inputSource);
885 // adapt channel selection to input source
886 switch(inputSource) {
887 case AUDIO_SOURCE_VOICE_UPLINK:
888 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
890 case AUDIO_SOURCE_VOICE_DOWNLINK:
891 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
893 case AUDIO_SOURCE_VOICE_CALL:
894 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
900 IOProfile *profile = getInputProfile(device,
904 if (profile == NULL) {
905 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
907 device, samplingRate, format, channelMask);
911 if (profile->mModule->mHandle == 0) {
912 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
916 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
918 inputDesc->mInputSource = inputSource;
919 inputDesc->mDevice = device;
920 inputDesc->mSamplingRate = samplingRate;
921 inputDesc->mFormat = (audio_format_t)format;
922 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
923 inputDesc->mRefCount = 0;
924 input = mpClientInterface->openInput(profile->mModule->mHandle,
926 &inputDesc->mSamplingRate,
928 &inputDesc->mChannelMask);
930 // only accept input with the exact requested set of parameters
932 (samplingRate != inputDesc->mSamplingRate) ||
933 (format != inputDesc->mFormat) ||
934 (channelMask != inputDesc->mChannelMask)) {
935 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
936 samplingRate, format, channelMask);
938 mpClientInterface->closeInput(input);
943 mInputs.add(input, inputDesc);
947 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
949 ALOGV("startInput() input %d", input);
950 ssize_t index = mInputs.indexOfKey(input);
952 ALOGW("startInput() unknow input %d", input);
955 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
957 #ifdef AUDIO_POLICY_TEST
959 #endif //AUDIO_POLICY_TEST
961 // refuse 2 active AudioRecord clients at the same time
962 if (!isVirtualInputDevice(inputDesc->mDevice) && getActiveInput(true) != 0) {
963 ALOGW("startInput() input %d failed: other input already started", input);
964 return INVALID_OPERATION;
968 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
969 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
970 inputDesc->mDevice = newDevice;
973 // automatically enable the remote submix output when input is started
974 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
975 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
976 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
979 AudioParameter param = AudioParameter();
980 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
982 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
983 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
985 mpClientInterface->setParameters(input, param.toString());
987 inputDesc->mRefCount = 1;
991 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
993 ALOGV("stopInput() input %d", input);
994 ssize_t index = mInputs.indexOfKey(input);
996 ALOGW("stopInput() unknow input %d", input);
999 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1001 if (inputDesc->mRefCount == 0) {
1002 ALOGW("stopInput() input %d already stopped", input);
1003 return INVALID_OPERATION;
1005 // automatically disable the remote submix output when input is stopped
1006 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1007 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1008 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1011 AudioParameter param = AudioParameter();
1012 param.addInt(String8(AudioParameter::keyRouting), 0);
1013 mpClientInterface->setParameters(input, param.toString());
1014 inputDesc->mRefCount = 0;
1019 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1021 ALOGV("releaseInput() %d", input);
1022 ssize_t index = mInputs.indexOfKey(input);
1024 ALOGW("releaseInput() releasing unknown input %d", input);
1027 mpClientInterface->closeInput(input);
1028 delete mInputs.valueAt(index);
1029 mInputs.removeItem(input);
1030 ALOGV("releaseInput() exit");
1033 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1037 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1038 if (indexMin < 0 || indexMin >= indexMax) {
1039 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1042 mStreams[stream].mIndexMin = indexMin;
1043 mStreams[stream].mIndexMax = indexMax;
1046 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1048 audio_devices_t device)
1051 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1054 if (!audio_is_output_device(device)) {
1058 // Force max volume if stream cannot be muted
1059 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1061 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1062 stream, device, index);
1064 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1065 // clear all device specific values
1066 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1067 mStreams[stream].mIndexCur.clear();
1069 mStreams[stream].mIndexCur.add(device, index);
1071 // compute and apply stream volume on all outputs according to connected device
1072 status_t status = NO_ERROR;
1073 for (size_t i = 0; i < mOutputs.size(); i++) {
1074 audio_devices_t curDevice =
1075 getDeviceForVolume(mOutputs.valueAt(i)->device());
1076 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1077 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1078 if (volStatus != NO_ERROR) {
1086 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1088 audio_devices_t device)
1090 if (index == NULL) {
1093 if (!audio_is_output_device(device)) {
1096 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1097 // the strategy the stream belongs to.
1098 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1099 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1101 device = getDeviceForVolume(device);
1103 *index = mStreams[stream].getVolumeIndex(device);
1104 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1108 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1110 ALOGV("getOutputForEffect()");
1111 // apply simple rule where global effects are attached to the same output as MUSIC streams
1113 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1114 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1115 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1117 for (size_t i = 0; i < dstOutputs.size(); i++) {
1118 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1119 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1123 return dstOutputs[outIdx];
1126 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1127 audio_io_handle_t io,
1132 ssize_t index = mOutputs.indexOfKey(io);
1134 index = mInputs.indexOfKey(io);
1136 ALOGW("registerEffect() unknown io %d", io);
1137 return INVALID_OPERATION;
1141 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1142 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1143 desc->name, desc->memoryUsage);
1144 return INVALID_OPERATION;
1146 mTotalEffectsMemory += desc->memoryUsage;
1147 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1148 desc->name, io, strategy, session, id);
1149 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1151 EffectDescriptor *pDesc = new EffectDescriptor();
1152 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1154 pDesc->mStrategy = (routing_strategy)strategy;
1155 pDesc->mSession = session;
1156 pDesc->mEnabled = false;
1158 mEffects.add(id, pDesc);
1163 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1165 ssize_t index = mEffects.indexOfKey(id);
1167 ALOGW("unregisterEffect() unknown effect ID %d", id);
1168 return INVALID_OPERATION;
1171 EffectDescriptor *pDesc = mEffects.valueAt(index);
1173 setEffectEnabled(pDesc, false);
1175 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1176 ALOGW("unregisterEffect() memory %d too big for total %d",
1177 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1178 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1180 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1181 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1182 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1184 mEffects.removeItem(id);
1190 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1192 ssize_t index = mEffects.indexOfKey(id);
1194 ALOGW("unregisterEffect() unknown effect ID %d", id);
1195 return INVALID_OPERATION;
1198 return setEffectEnabled(mEffects.valueAt(index), enabled);
1201 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1203 if (enabled == pDesc->mEnabled) {
1204 ALOGV("setEffectEnabled(%s) effect already %s",
1205 enabled?"true":"false", enabled?"enabled":"disabled");
1206 return INVALID_OPERATION;
1210 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1211 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1212 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1213 return INVALID_OPERATION;
1215 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1216 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1218 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1219 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1220 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1221 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1223 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1224 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1226 pDesc->mEnabled = enabled;
1230 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1232 nsecs_t sysTime = systemTime();
1233 for (size_t i = 0; i < mOutputs.size(); i++) {
1234 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1235 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1242 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1244 nsecs_t sysTime = systemTime();
1245 for (size_t i = 0; i < mOutputs.size(); i++) {
1246 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1247 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1248 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1255 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1257 for (size_t i = 0; i < mInputs.size(); i++) {
1258 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1259 if ((inputDescriptor->mInputSource == (int) source)
1260 && (inputDescriptor->mRefCount > 0)) {
1269 status_t AudioPolicyManagerBase::dump(int fd)
1271 const size_t SIZE = 256;
1275 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1276 result.append(buffer);
1278 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1279 result.append(buffer);
1280 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1281 result.append(buffer);
1282 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1283 result.append(buffer);
1284 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1285 result.append(buffer);
1286 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1287 result.append(buffer);
1288 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1289 result.append(buffer);
1290 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1291 result.append(buffer);
1292 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1293 result.append(buffer);
1294 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1295 result.append(buffer);
1296 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1297 result.append(buffer);
1298 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1299 result.append(buffer);
1300 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1301 result.append(buffer);
1302 write(fd, result.string(), result.size());
1305 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1306 write(fd, buffer, strlen(buffer));
1307 for (size_t i = 0; i < mHwModules.size(); i++) {
1308 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1309 write(fd, buffer, strlen(buffer));
1310 mHwModules[i]->dump(fd);
1313 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1314 write(fd, buffer, strlen(buffer));
1315 for (size_t i = 0; i < mOutputs.size(); i++) {
1316 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1317 write(fd, buffer, strlen(buffer));
1318 mOutputs.valueAt(i)->dump(fd);
1321 snprintf(buffer, SIZE, "\nInputs dump:\n");
1322 write(fd, buffer, strlen(buffer));
1323 for (size_t i = 0; i < mInputs.size(); i++) {
1324 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1325 write(fd, buffer, strlen(buffer));
1326 mInputs.valueAt(i)->dump(fd);
1329 snprintf(buffer, SIZE, "\nStreams dump:\n");
1330 write(fd, buffer, strlen(buffer));
1331 snprintf(buffer, SIZE,
1332 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1333 write(fd, buffer, strlen(buffer));
1334 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1335 snprintf(buffer, SIZE, " %02d ", i);
1336 write(fd, buffer, strlen(buffer));
1337 mStreams[i].dump(fd);
1340 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1341 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1342 write(fd, buffer, strlen(buffer));
1344 snprintf(buffer, SIZE, "Registered effects:\n");
1345 write(fd, buffer, strlen(buffer));
1346 for (size_t i = 0; i < mEffects.size(); i++) {
1347 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1348 write(fd, buffer, strlen(buffer));
1349 mEffects.valueAt(i)->dump(fd);
1356 // This function checks for the parameters which can be offloaded.
1357 // This can be enhanced depending on the capability of the DSP and policy
1359 bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1361 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1362 " BitRate=%u, duration=%lld us, has_video=%d",
1363 offloadInfo.sample_rate, offloadInfo.channel_mask,
1365 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1366 offloadInfo.has_video);
1368 // Check if offload has been disabled
1369 char propValue[PROPERTY_VALUE_MAX];
1370 if (property_get("audio.offload.disable", propValue, "0")) {
1371 if (atoi(propValue) != 0) {
1372 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1377 // Check if stream type is music, then only allow offload as of now.
1378 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1380 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1384 //TODO: enable audio offloading with video when ready
1385 if (offloadInfo.has_video)
1387 ALOGV("isOffloadSupported: has_video == true, returning false");
1391 //If duration is less than minimum value defined in property, return false
1392 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1393 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1394 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1397 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1398 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1402 // See if there is a profile to support this.
1403 // AUDIO_DEVICE_NONE
1404 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1405 offloadInfo.sample_rate,
1407 offloadInfo.channel_mask,
1408 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1409 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1410 return (profile != NULL);
1413 // ----------------------------------------------------------------------------
1414 // AudioPolicyManagerBase
1415 // ----------------------------------------------------------------------------
1417 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1419 #ifdef AUDIO_POLICY_TEST
1421 #endif //AUDIO_POLICY_TEST
1422 mPrimaryOutput((audio_io_handle_t)0),
1423 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1424 mPhoneState(AudioSystem::MODE_NORMAL),
1425 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1426 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1427 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false)
1429 mpClientInterface = clientInterface;
1431 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1432 mForceUse[i] = AudioSystem::FORCE_NONE;
1435 initializeVolumeCurves();
1437 mA2dpDeviceAddress = String8("");
1438 mScoDeviceAddress = String8("");
1439 mUsbCardAndDevice = String8("");
1441 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1442 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1443 ALOGE("could not load audio policy configuration file, setting defaults");
1444 defaultAudioPolicyConfig();
1448 // open all output streams needed to access attached devices
1449 for (size_t i = 0; i < mHwModules.size(); i++) {
1450 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1451 if (mHwModules[i]->mHandle == 0) {
1452 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1455 // open all output streams needed to access attached devices
1456 // except for direct output streams that are only opened when they are actually
1457 // required by an app.
1458 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1460 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1462 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1463 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1464 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1465 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1466 outProfile->mSupportedDevices);
1467 audio_io_handle_t output = mpClientInterface->openOutput(
1468 outProfile->mModule->mHandle,
1469 &outputDesc->mDevice,
1470 &outputDesc->mSamplingRate,
1471 &outputDesc->mFormat,
1472 &outputDesc->mChannelMask,
1473 &outputDesc->mLatency,
1474 outputDesc->mFlags);
1478 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1479 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1480 if (mPrimaryOutput == 0 &&
1481 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1482 mPrimaryOutput = output;
1484 addOutput(output, outputDesc);
1485 setOutputDevice(output,
1486 (audio_devices_t)(mDefaultOutputDevice &
1487 outProfile->mSupportedDevices),
1494 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1495 "Not output found for attached devices %08x",
1496 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1498 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1500 updateDevicesAndOutputs();
1502 #ifdef AUDIO_POLICY_TEST
1503 if (mPrimaryOutput != 0) {
1504 AudioParameter outputCmd = AudioParameter();
1505 outputCmd.addInt(String8("set_id"), 0);
1506 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1508 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1509 mTestSamplingRate = 44100;
1510 mTestFormat = AudioSystem::PCM_16_BIT;
1511 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1514 mDirectOutput = false;
1515 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1516 mTestOutputs[i] = 0;
1519 const size_t SIZE = 256;
1521 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1522 run(buffer, ANDROID_PRIORITY_AUDIO);
1524 #endif //AUDIO_POLICY_TEST
1527 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1529 #ifdef AUDIO_POLICY_TEST
1531 #endif //AUDIO_POLICY_TEST
1532 for (size_t i = 0; i < mOutputs.size(); i++) {
1533 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1534 delete mOutputs.valueAt(i);
1536 for (size_t i = 0; i < mInputs.size(); i++) {
1537 mpClientInterface->closeInput(mInputs.keyAt(i));
1538 delete mInputs.valueAt(i);
1540 for (size_t i = 0; i < mHwModules.size(); i++) {
1541 delete mHwModules[i];
1545 status_t AudioPolicyManagerBase::initCheck()
1547 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1550 #ifdef AUDIO_POLICY_TEST
1551 bool AudioPolicyManagerBase::threadLoop()
1553 ALOGV("entering threadLoop()");
1554 while (!exitPending())
1560 Mutex::Autolock _l(mLock);
1561 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1563 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1564 AudioParameter param = AudioParameter(command);
1566 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1568 ALOGV("Test command %s received", command.string());
1570 if (param.get(String8("target"), target) != NO_ERROR) {
1573 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1574 param.remove(String8("test_cmd_policy_output"));
1575 mCurOutput = valueInt;
1577 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1578 param.remove(String8("test_cmd_policy_direct"));
1579 if (value == "false") {
1580 mDirectOutput = false;
1581 } else if (value == "true") {
1582 mDirectOutput = true;
1585 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1586 param.remove(String8("test_cmd_policy_input"));
1587 mTestInput = valueInt;
1590 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1591 param.remove(String8("test_cmd_policy_format"));
1592 int format = AudioSystem::INVALID_FORMAT;
1593 if (value == "PCM 16 bits") {
1594 format = AudioSystem::PCM_16_BIT;
1595 } else if (value == "PCM 8 bits") {
1596 format = AudioSystem::PCM_8_BIT;
1597 } else if (value == "Compressed MP3") {
1598 format = AudioSystem::MP3;
1600 if (format != AudioSystem::INVALID_FORMAT) {
1601 if (target == "Manager") {
1602 mTestFormat = format;
1603 } else if (mTestOutputs[mCurOutput] != 0) {
1604 AudioParameter outputParam = AudioParameter();
1605 outputParam.addInt(String8("format"), format);
1606 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1610 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1611 param.remove(String8("test_cmd_policy_channels"));
1614 if (value == "Channels Stereo") {
1615 channels = AudioSystem::CHANNEL_OUT_STEREO;
1616 } else if (value == "Channels Mono") {
1617 channels = AudioSystem::CHANNEL_OUT_MONO;
1619 if (channels != 0) {
1620 if (target == "Manager") {
1621 mTestChannels = channels;
1622 } else if (mTestOutputs[mCurOutput] != 0) {
1623 AudioParameter outputParam = AudioParameter();
1624 outputParam.addInt(String8("channels"), channels);
1625 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1629 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1630 param.remove(String8("test_cmd_policy_sampleRate"));
1631 if (valueInt >= 0 && valueInt <= 96000) {
1632 int samplingRate = valueInt;
1633 if (target == "Manager") {
1634 mTestSamplingRate = samplingRate;
1635 } else if (mTestOutputs[mCurOutput] != 0) {
1636 AudioParameter outputParam = AudioParameter();
1637 outputParam.addInt(String8("sampling_rate"), samplingRate);
1638 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1643 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1644 param.remove(String8("test_cmd_policy_reopen"));
1646 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1647 mpClientInterface->closeOutput(mPrimaryOutput);
1649 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1651 delete mOutputs.valueFor(mPrimaryOutput);
1652 mOutputs.removeItem(mPrimaryOutput);
1654 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1655 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1656 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1657 &outputDesc->mDevice,
1658 &outputDesc->mSamplingRate,
1659 &outputDesc->mFormat,
1660 &outputDesc->mChannelMask,
1661 &outputDesc->mLatency,
1662 outputDesc->mFlags);
1663 if (mPrimaryOutput == 0) {
1664 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1665 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1667 AudioParameter outputCmd = AudioParameter();
1668 outputCmd.addInt(String8("set_id"), 0);
1669 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1670 addOutput(mPrimaryOutput, outputDesc);
1675 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1681 void AudioPolicyManagerBase::exit()
1684 AutoMutex _l(mLock);
1686 mWaitWorkCV.signal();
1688 requestExitAndWait();
1691 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1693 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1694 if (output == mTestOutputs[i]) return i;
1698 #endif //AUDIO_POLICY_TEST
1702 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1704 outputDesc->mId = id;
1705 mOutputs.add(id, outputDesc);
1709 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1710 AudioSystem::device_connection_state state,
1711 SortedVector<audio_io_handle_t>& outputs)
1713 AudioOutputDescriptor *desc;
1715 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1716 // first list already open outputs that can be routed to this device
1717 for (size_t i = 0; i < mOutputs.size(); i++) {
1718 desc = mOutputs.valueAt(i);
1719 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1720 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1721 outputs.add(mOutputs.keyAt(i));
1724 // then look for output profiles that can be routed to this device
1725 SortedVector<IOProfile *> profiles;
1726 for (size_t i = 0; i < mHwModules.size(); i++)
1728 if (mHwModules[i]->mHandle == 0) {
1731 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1733 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1734 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1735 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1740 if (profiles.isEmpty() && outputs.isEmpty()) {
1741 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1745 // open outputs for matching profiles if needed. Direct outputs are also opened to
1746 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1747 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1748 IOProfile *profile = profiles[profile_index];
1750 // nothing to do if one output is already opened for this profile
1752 for (j = 0; j < mOutputs.size(); j++) {
1753 desc = mOutputs.valueAt(j);
1754 if (!desc->isDuplicated() && desc->mProfile == profile) {
1758 if (j != mOutputs.size()) {
1762 ALOGV("opening output for device %08x", device);
1763 desc = new AudioOutputDescriptor(profile);
1764 desc->mDevice = device;
1765 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1767 &desc->mSamplingRate,
1769 &desc->mChannelMask,
1773 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1776 if (profile->mSamplingRates[0] == 0) {
1777 reply = mpClientInterface->getParameters(output,
1778 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1779 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1781 value = strpbrk((char *)reply.string(), "=");
1782 if (value != NULL) {
1783 loadSamplingRates(value + 1, profile);
1786 if (profile->mFormats[0] == 0) {
1787 reply = mpClientInterface->getParameters(output,
1788 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1789 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1791 value = strpbrk((char *)reply.string(), "=");
1792 if (value != NULL) {
1793 loadFormats(value + 1, profile);
1796 if (profile->mChannelMasks[0] == 0) {
1797 reply = mpClientInterface->getParameters(output,
1798 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1799 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1801 value = strpbrk((char *)reply.string(), "=");
1802 if (value != NULL) {
1803 loadOutChannels(value + 1, profile);
1806 if (((profile->mSamplingRates[0] == 0) &&
1807 (profile->mSamplingRates.size() < 2)) ||
1808 ((profile->mFormats[0] == 0) &&
1809 (profile->mFormats.size() < 2)) ||
1810 ((profile->mFormats[0] == 0) &&
1811 (profile->mChannelMasks.size() < 2))) {
1812 ALOGW("checkOutputsForDevice() direct output missing param");
1813 mpClientInterface->closeOutput(output);
1816 addOutput(output, desc);
1819 audio_io_handle_t duplicatedOutput = 0;
1820 // add output descriptor
1821 addOutput(output, desc);
1822 // set initial stream volume for device
1823 applyStreamVolumes(output, device, 0, true);
1825 //TODO: configure audio effect output stage here
1827 // open a duplicating output thread for the new output and the primary output
1828 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1830 if (duplicatedOutput != 0) {
1831 // add duplicated output descriptor
1832 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1833 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1834 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1835 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1836 dupOutputDesc->mFormat = desc->mFormat;
1837 dupOutputDesc->mChannelMask = desc->mChannelMask;
1838 dupOutputDesc->mLatency = desc->mLatency;
1839 addOutput(duplicatedOutput, dupOutputDesc);
1840 applyStreamVolumes(duplicatedOutput, device, 0, true);
1842 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1843 mPrimaryOutput, output);
1844 mpClientInterface->closeOutput(output);
1845 mOutputs.removeItem(output);
1851 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1853 profiles.removeAt(profile_index);
1856 outputs.add(output);
1857 ALOGV("checkOutputsForDevice(): adding output %d", output);
1861 if (profiles.isEmpty()) {
1862 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1866 // check if one opened output is not needed any more after disconnecting one device
1867 for (size_t i = 0; i < mOutputs.size(); i++) {
1868 desc = mOutputs.valueAt(i);
1869 if (!desc->isDuplicated() &&
1870 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1871 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1872 outputs.add(mOutputs.keyAt(i));
1875 for (size_t i = 0; i < mHwModules.size(); i++)
1877 if (mHwModules[i]->mHandle == 0) {
1880 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1882 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1883 if ((profile->mSupportedDevices & device) &&
1884 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1885 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1887 if (profile->mSamplingRates[0] == 0) {
1888 profile->mSamplingRates.clear();
1889 profile->mSamplingRates.add(0);
1891 if (profile->mFormats[0] == 0) {
1892 profile->mFormats.clear();
1893 profile->mFormats.add((audio_format_t)0);
1895 if (profile->mChannelMasks[0] == 0) {
1896 profile->mChannelMasks.clear();
1897 profile->mChannelMasks.add((audio_channel_mask_t)0);
1906 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1908 ALOGV("closeOutput(%d)", output);
1910 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1911 if (outputDesc == NULL) {
1912 ALOGW("closeOutput() unknown output %d", output);
1916 // look for duplicated outputs connected to the output being removed.
1917 for (size_t i = 0; i < mOutputs.size(); i++) {
1918 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1919 if (dupOutputDesc->isDuplicated() &&
1920 (dupOutputDesc->mOutput1 == outputDesc ||
1921 dupOutputDesc->mOutput2 == outputDesc)) {
1922 AudioOutputDescriptor *outputDesc2;
1923 if (dupOutputDesc->mOutput1 == outputDesc) {
1924 outputDesc2 = dupOutputDesc->mOutput2;
1926 outputDesc2 = dupOutputDesc->mOutput1;
1928 // As all active tracks on duplicated output will be deleted,
1929 // and as they were also referenced on the other output, the reference
1930 // count for their stream type must be adjusted accordingly on
1931 // the other output.
1932 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1933 int refCount = dupOutputDesc->mRefCount[j];
1934 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1936 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1937 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1939 mpClientInterface->closeOutput(duplicatedOutput);
1940 delete mOutputs.valueFor(duplicatedOutput);
1941 mOutputs.removeItem(duplicatedOutput);
1945 AudioParameter param;
1946 param.add(String8("closing"), String8("true"));
1947 mpClientInterface->setParameters(output, param.toString());
1949 mpClientInterface->closeOutput(output);
1951 mOutputs.removeItem(output);
1952 mPreviousOutputs = mOutputs;
1955 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
1956 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
1958 SortedVector<audio_io_handle_t> outputs;
1960 ALOGVV("getOutputsForDevice() device %04x", device);
1961 for (size_t i = 0; i < openOutputs.size(); i++) {
1962 ALOGVV("output %d isDuplicated=%d device=%04x",
1963 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
1964 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
1965 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
1966 outputs.add(openOutputs.keyAt(i));
1972 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1973 SortedVector<audio_io_handle_t>& outputs2)
1975 if (outputs1.size() != outputs2.size()) {
1978 for (size_t i = 0; i < outputs1.size(); i++) {
1979 if (outputs1[i] != outputs2[i]) {
1986 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1988 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
1989 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
1990 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
1991 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
1993 if (!vectorsEqual(srcOutputs,dstOutputs)) {
1994 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1995 strategy, srcOutputs[0], dstOutputs[0]);
1996 // mute strategy while moving tracks from one output to another
1997 for (size_t i = 0; i < srcOutputs.size(); i++) {
1998 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
1999 if (desc->isStrategyActive(strategy)) {
2000 setStrategyMute(strategy, true, srcOutputs[i]);
2001 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2005 // Move effects associated to this strategy from previous output to new output
2006 if (strategy == STRATEGY_MEDIA) {
2008 for (size_t i = 0; i < dstOutputs.size(); i++) {
2009 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
2010 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
2014 SortedVector<audio_io_handle_t> moved;
2015 for (size_t i = 0; i < mEffects.size(); i++) {
2016 EffectDescriptor *desc = mEffects.valueAt(i);
2017 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2018 desc->mIo != dstOutputs[outIdx]) {
2019 if (moved.indexOf(desc->mIo) < 0) {
2020 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2021 mEffects.keyAt(i), dstOutputs[outIdx]);
2022 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2023 dstOutputs[outIdx]);
2024 moved.add(desc->mIo);
2026 desc->mIo = dstOutputs[outIdx];
2030 // Move tracks associated to this strategy from previous output to new output
2031 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2032 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2033 //FIXME see fixme on name change
2034 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
2035 dstOutputs[0] /* ignored */);
2041 void AudioPolicyManagerBase::checkOutputForAllStrategies()
2043 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2044 checkOutputForStrategy(STRATEGY_PHONE);
2045 checkOutputForStrategy(STRATEGY_SONIFICATION);
2046 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2047 checkOutputForStrategy(STRATEGY_MEDIA);
2048 checkOutputForStrategy(STRATEGY_DTMF);
2051 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2057 for (size_t i = 0; i < mOutputs.size(); i++) {
2058 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2059 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2060 return mOutputs.keyAt(i);
2067 void AudioPolicyManagerBase::checkA2dpSuspend()
2072 audio_io_handle_t a2dpOutput = getA2dpOutput();
2073 if (a2dpOutput == 0) {
2077 // suspend A2DP output if:
2078 // (NOT already suspended) &&
2079 // ((SCO device is connected &&
2080 // (forced usage for communication || for record is SCO))) ||
2081 // (phone state is ringing || in call)
2083 // restore A2DP output if:
2084 // (Already suspended) &&
2085 // ((SCO device is NOT connected ||
2086 // (forced usage NOT for communication && NOT for record is SCO))) &&
2087 // (phone state is NOT ringing && NOT in call)
2089 if (mA2dpSuspended) {
2090 if (((mScoDeviceAddress == "") ||
2091 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2092 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2093 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2094 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2096 mpClientInterface->restoreOutput(a2dpOutput);
2097 mA2dpSuspended = false;
2100 if (((mScoDeviceAddress != "") &&
2101 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2102 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2103 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2104 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2106 mpClientInterface->suspendOutput(a2dpOutput);
2107 mA2dpSuspended = true;
2112 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2114 audio_devices_t device = AUDIO_DEVICE_NONE;
2116 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2117 // check the following by order of priority to request a routing change if necessary:
2118 // 1: the strategy enforced audible is active on the output:
2119 // use device for strategy enforced audible
2120 // 2: we are in call or the strategy phone is active on the output:
2121 // use device for strategy phone
2122 // 3: the strategy sonification is active on the output:
2123 // use device for strategy sonification
2124 // 4: the strategy "respectful" sonification is active on the output:
2125 // use device for strategy "respectful" sonification
2126 // 5: the strategy media is active on the output:
2127 // use device for strategy media
2128 // 6: the strategy DTMF is active on the output:
2129 // use device for strategy DTMF
2130 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2131 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2132 } else if (isInCall() ||
2133 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2134 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2135 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2136 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2137 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2138 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2139 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2140 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2141 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2142 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2145 ALOGV("getNewDevice() selected device %x", device);
2149 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2150 return (uint32_t)getStrategy(stream);
2153 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2154 audio_devices_t devices;
2155 // By checking the range of stream before calling getStrategy, we avoid
2156 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2157 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2158 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2159 devices = AUDIO_DEVICE_NONE;
2161 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2162 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2167 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2168 AudioSystem::stream_type stream) {
2169 // stream to strategy mapping
2171 case AudioSystem::VOICE_CALL:
2172 case AudioSystem::BLUETOOTH_SCO:
2173 return STRATEGY_PHONE;
2174 case AudioSystem::RING:
2175 case AudioSystem::ALARM:
2176 return STRATEGY_SONIFICATION;
2177 case AudioSystem::NOTIFICATION:
2178 return STRATEGY_SONIFICATION_RESPECTFUL;
2179 case AudioSystem::DTMF:
2180 return STRATEGY_DTMF;
2182 ALOGE("unknown stream type");
2183 case AudioSystem::SYSTEM:
2184 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2185 // while key clicks are played produces a poor result
2186 case AudioSystem::TTS:
2187 case AudioSystem::MUSIC:
2188 return STRATEGY_MEDIA;
2189 case AudioSystem::ENFORCED_AUDIBLE:
2190 return STRATEGY_ENFORCED_AUDIBLE;
2194 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2196 case AudioSystem::MUSIC:
2197 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2198 updateDevicesAndOutputs();
2205 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2208 uint32_t device = AUDIO_DEVICE_NONE;
2211 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2212 strategy, mDeviceForStrategy[strategy]);
2213 return mDeviceForStrategy[strategy];
2218 case STRATEGY_SONIFICATION_RESPECTFUL:
2220 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2221 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2222 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2223 // while media is playing on a remote device, use the the sonification behavior.
2224 // Note that we test this usecase before testing if media is playing because
2225 // the isStreamActive() method only informs about the activity of a stream, not
2226 // if it's for local playback. Note also that we use the same delay between both tests
2227 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2228 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2229 // while media is playing (or has recently played), use the same device
2230 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2232 // when media is not playing anymore, fall back on the sonification behavior
2233 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2240 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2241 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2244 // when in call, DTMF and PHONE strategies follow the same rules
2247 case STRATEGY_PHONE:
2248 // for phone strategy, we first consider the forced use and then the available devices by order
2250 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2251 case AudioSystem::FORCE_BT_SCO:
2252 if (!isInCall() || strategy != STRATEGY_DTMF) {
2253 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2256 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2258 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2260 // if SCO device is requested but no SCO device is available, fall back to default case
2263 default: // FORCE_NONE
2264 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2265 if (mHasA2dp && !isInCall() &&
2266 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2267 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2268 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2270 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2273 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2275 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2277 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2278 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2280 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2282 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2284 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2286 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2289 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2291 device = mDefaultOutputDevice;
2292 if (device == AUDIO_DEVICE_NONE) {
2293 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2297 case AudioSystem::FORCE_SPEAKER:
2298 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2299 // A2DP speaker when forcing to speaker output
2300 if (mHasA2dp && !isInCall() &&
2301 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2302 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2303 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2306 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2307 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2309 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2311 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2313 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2315 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2318 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2320 device = mDefaultOutputDevice;
2321 if (device == AUDIO_DEVICE_NONE) {
2322 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2328 case STRATEGY_SONIFICATION:
2330 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2331 // handleIncallSonification().
2333 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2338 case STRATEGY_ENFORCED_AUDIBLE:
2339 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2341 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2342 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2344 if ((strategy == STRATEGY_SONIFICATION) ||
2345 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2346 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2347 if (device == AUDIO_DEVICE_NONE) {
2348 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2351 // The second device used for sonification is the same as the device used by media strategy
2354 case STRATEGY_MEDIA: {
2355 uint32_t device2 = AUDIO_DEVICE_NONE;
2356 if (strategy != STRATEGY_SONIFICATION) {
2357 // no sonification on remote submix (e.g. WFD)
2358 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2360 if ((device2 == AUDIO_DEVICE_NONE) &&
2361 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2362 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2363 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2364 if (device2 == AUDIO_DEVICE_NONE) {
2365 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2367 if (device2 == AUDIO_DEVICE_NONE) {
2368 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2371 if (device2 == AUDIO_DEVICE_NONE) {
2372 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2374 if (device2 == AUDIO_DEVICE_NONE) {
2375 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2377 if (device2 == AUDIO_DEVICE_NONE) {
2378 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2380 if (device2 == AUDIO_DEVICE_NONE) {
2381 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2383 if (device2 == AUDIO_DEVICE_NONE) {
2384 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2386 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2387 // no sonification on aux digital (e.g. HDMI)
2388 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2390 if ((device2 == AUDIO_DEVICE_NONE) &&
2391 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2392 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2394 if (device2 == AUDIO_DEVICE_NONE) {
2395 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2398 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2399 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2402 device = mDefaultOutputDevice;
2403 if (device == AUDIO_DEVICE_NONE) {
2404 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2409 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2413 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2417 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2419 for (int i = 0; i < NUM_STRATEGIES; i++) {
2420 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2422 mPreviousOutputs = mOutputs;
2425 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2426 audio_devices_t prevDevice,
2429 // mute/unmute strategies using an incompatible device combination
2430 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2431 // if unmuting, unmute only after the specified delay
2432 if (outputDesc->isDuplicated()) {
2436 uint32_t muteWaitMs = 0;
2437 audio_devices_t device = outputDesc->device();
2438 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2439 // temporary mute output if device selection changes to avoid volume bursts due to
2440 // different per device volumes
2441 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2443 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2444 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2445 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2446 bool doMute = false;
2448 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2450 outputDesc->mStrategyMutedByDevice[i] = true;
2451 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2453 outputDesc->mStrategyMutedByDevice[i] = false;
2455 if (doMute || tempMute) {
2456 for (size_t j = 0; j < mOutputs.size(); j++) {
2457 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2458 // skip output if it does not share any device with current output
2459 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2460 == AUDIO_DEVICE_NONE) {
2463 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2464 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2465 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2466 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2467 if (desc->isStrategyActive((routing_strategy)i)) {
2468 // do tempMute only for current output
2469 if (tempMute && (desc == outputDesc)) {
2470 setStrategyMute((routing_strategy)i, true, curOutput);
2471 setStrategyMute((routing_strategy)i, false, curOutput,
2472 desc->latency() * 2, device);
2474 if ((tempMute && (desc == outputDesc)) || mute) {
2475 if (muteWaitMs < desc->latency()) {
2476 muteWaitMs = desc->latency();
2484 // FIXME: should not need to double latency if volume could be applied immediately by the
2485 // audioflinger mixer. We must account for the delay between now and the next time
2486 // the audioflinger thread for this output will process a buffer (which corresponds to
2487 // one buffer size, usually 1/2 or 1/4 of the latency).
2489 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2490 if (muteWaitMs > delayMs) {
2491 muteWaitMs -= delayMs;
2492 usleep(muteWaitMs * 1000);
2498 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2499 audio_devices_t device,
2503 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2504 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2505 AudioParameter param;
2506 uint32_t muteWaitMs;
2508 if (outputDesc->isDuplicated()) {
2509 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2510 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2513 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2515 if ((device != AUDIO_DEVICE_NONE) &&
2516 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2520 // filter devices according to output selected
2521 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2523 audio_devices_t prevDevice = outputDesc->mDevice;
2525 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2527 if (device != AUDIO_DEVICE_NONE) {
2528 outputDesc->mDevice = device;
2530 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2532 // Do not change the routing if:
2533 // - the requested device is AUDIO_DEVICE_NONE
2534 // - the requested device is the same as current device and force is not specified.
2535 // Doing this check here allows the caller to call setOutputDevice() without conditions
2536 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2537 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2541 ALOGV("setOutputDevice() changing device");
2543 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2544 mpClientInterface->setParameters(output, param.toString(), delayMs);
2546 // update stream volumes according to new device
2547 applyStreamVolumes(output, device, delayMs);
2552 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2553 uint32_t samplingRate,
2555 uint32_t channelMask)
2557 // Choose an input profile based on the requested capture parameters: select the first available
2558 // profile supporting all requested parameters.
2560 for (size_t i = 0; i < mHwModules.size(); i++)
2562 if (mHwModules[i]->mHandle == 0) {
2565 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2567 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2568 if (profile->isCompatibleProfile(device, samplingRate, format,
2569 channelMask,(audio_output_flags_t)0)) {
2577 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2579 uint32_t device = AUDIO_DEVICE_NONE;
2581 switch (inputSource) {
2582 case AUDIO_SOURCE_VOICE_UPLINK:
2583 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2584 device = AUDIO_DEVICE_IN_VOICE_CALL;
2589 case AUDIO_SOURCE_DEFAULT:
2590 case AUDIO_SOURCE_MIC:
2591 case AUDIO_SOURCE_VOICE_RECOGNITION:
2592 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2593 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2594 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2595 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2596 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2597 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2598 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2599 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2602 case AUDIO_SOURCE_CAMCORDER:
2603 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2604 device = AUDIO_DEVICE_IN_BACK_MIC;
2605 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2606 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2609 case AUDIO_SOURCE_VOICE_DOWNLINK:
2610 case AUDIO_SOURCE_VOICE_CALL:
2611 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2612 device = AUDIO_DEVICE_IN_VOICE_CALL;
2615 case AUDIO_SOURCE_REMOTE_SUBMIX:
2616 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2617 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2621 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2624 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2628 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2630 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2631 device &= ~AUDIO_DEVICE_BIT_IN;
2632 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2638 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2640 for (size_t i = 0; i < mInputs.size(); i++) {
2641 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2642 if ((input_descriptor->mRefCount > 0)
2643 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2644 return mInputs.keyAt(i);
2651 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2653 if (device == AUDIO_DEVICE_NONE) {
2654 // this happens when forcing a route update and no track is active on an output.
2655 // In this case the returned category is not important.
2656 device = AUDIO_DEVICE_OUT_SPEAKER;
2657 } else if (AudioSystem::popCount(device) > 1) {
2658 // Multiple device selection is either:
2659 // - speaker + one other device: give priority to speaker in this case.
2660 // - one A2DP device + another device: happens with duplicated output. In this case
2661 // retain the device on the A2DP output as the other must not correspond to an active
2662 // selection if not the speaker.
2663 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2664 device = AUDIO_DEVICE_OUT_SPEAKER;
2666 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2670 ALOGW_IF(AudioSystem::popCount(device) != 1,
2671 "getDeviceForVolume() invalid device combination: %08x",
2677 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2679 switch(getDeviceForVolume(device)) {
2680 case AUDIO_DEVICE_OUT_EARPIECE:
2681 return DEVICE_CATEGORY_EARPIECE;
2682 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2683 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2684 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2685 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2686 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2687 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2688 return DEVICE_CATEGORY_HEADSET;
2689 case AUDIO_DEVICE_OUT_SPEAKER:
2690 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2691 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2692 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2693 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2694 case AUDIO_DEVICE_OUT_USB_DEVICE:
2695 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
2697 return DEVICE_CATEGORY_SPEAKER;
2701 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2704 device_category deviceCategory = getDeviceCategory(device);
2705 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2707 // the volume index in the UI is relative to the min and max volume indices for this stream type
2708 int nbSteps = 1 + curve[VOLMAX].mIndex -
2709 curve[VOLMIN].mIndex;
2710 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2711 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2713 // find what part of the curve this index volume belongs to, or if it's out of bounds
2715 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2717 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2719 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2721 } else if (volIdx <= curve[VOLMAX].mIndex) {
2723 } else { // out of bounds
2727 // linear interpolation in the attenuation table in dB
2728 float decibels = curve[segment].mDBAttenuation +
2729 ((float)(volIdx - curve[segment].mIndex)) *
2730 ( (curve[segment+1].mDBAttenuation -
2731 curve[segment].mDBAttenuation) /
2732 ((float)(curve[segment+1].mIndex -
2733 curve[segment].mIndex)) );
2735 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2737 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2738 curve[segment].mIndex, volIdx,
2739 curve[segment+1].mIndex,
2740 curve[segment].mDBAttenuation,
2742 curve[segment+1].mDBAttenuation,
2745 return amplification;
2748 const AudioPolicyManagerBase::VolumeCurvePoint
2749 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2750 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2753 const AudioPolicyManagerBase::VolumeCurvePoint
2754 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2755 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2758 const AudioPolicyManagerBase::VolumeCurvePoint
2759 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2760 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2763 const AudioPolicyManagerBase::VolumeCurvePoint
2764 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2765 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2768 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2769 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2770 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2771 const AudioPolicyManagerBase::VolumeCurvePoint
2772 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2773 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2776 const AudioPolicyManagerBase::VolumeCurvePoint
2777 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2778 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2781 const AudioPolicyManagerBase::VolumeCurvePoint
2782 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2783 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
2786 const AudioPolicyManagerBase::VolumeCurvePoint
2787 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2788 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
2791 const AudioPolicyManagerBase::VolumeCurvePoint
2792 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2793 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2794 { // AUDIO_STREAM_VOICE_CALL
2795 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2796 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2797 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2799 { // AUDIO_STREAM_SYSTEM
2800 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2801 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2802 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2804 { // AUDIO_STREAM_RING
2805 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2806 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2807 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2809 { // AUDIO_STREAM_MUSIC
2810 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2811 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2812 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2814 { // AUDIO_STREAM_ALARM
2815 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2816 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2817 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2819 { // AUDIO_STREAM_NOTIFICATION
2820 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2821 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2822 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2824 { // AUDIO_STREAM_BLUETOOTH_SCO
2825 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2826 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2827 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2829 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2830 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2831 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2832 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2834 { // AUDIO_STREAM_DTMF
2835 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2836 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2837 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2839 { // AUDIO_STREAM_TTS
2840 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2841 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2842 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2846 void AudioPolicyManagerBase::initializeVolumeCurves()
2848 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2849 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2850 mStreams[i].mVolumeCurve[j] =
2851 sVolumeProfiles[i][j];
2856 float AudioPolicyManagerBase::computeVolume(int stream,
2858 audio_io_handle_t output,
2859 audio_devices_t device)
2862 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2863 StreamDescriptor &streamDesc = mStreams[stream];
2865 if (device == AUDIO_DEVICE_NONE) {
2866 device = outputDesc->device();
2869 // if volume is not 0 (not muted), force media volume to max on digital output
2870 if (stream == AudioSystem::MUSIC &&
2871 index != mStreams[stream].mIndexMin &&
2872 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2873 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2874 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2875 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2879 volume = volIndexToAmpl(device, streamDesc, index);
2881 // if a headset is connected, apply the following rules to ring tones and notifications
2882 // to avoid sound level bursts in user's ears:
2883 // - always attenuate ring tones and notifications volume by 6dB
2884 // - if music is playing, always limit the volume to current music volume,
2885 // with a minimum threshold at -36dB so that notification is always perceived.
2886 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2887 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
2888 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2889 AUDIO_DEVICE_OUT_WIRED_HEADSET |
2890 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
2891 ((stream_strategy == STRATEGY_SONIFICATION)
2892 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2893 || (stream == AudioSystem::SYSTEM)
2894 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
2895 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
2896 streamDesc.mCanBeMuted) {
2897 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2898 // when the phone is ringing we must consider that music could have been paused just before
2899 // by the music application and behave as if music was active if the last music track was
2901 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2902 mLimitRingtoneVolume) {
2903 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
2904 float musicVol = computeVolume(AudioSystem::MUSIC,
2905 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
2908 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2909 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2910 if (volume > minVol) {
2912 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2920 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2922 audio_io_handle_t output,
2923 audio_devices_t device,
2928 // do not change actual stream volume if the stream is muted
2929 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2930 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2931 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2935 // do not change in call volume if bluetooth is connected and vice versa
2936 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2937 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2938 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2939 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2940 return INVALID_OPERATION;
2943 float volume = computeVolume(stream, index, output, device);
2944 // We actually change the volume if:
2945 // - the float value returned by computeVolume() changed
2946 // - the force flag is set
2947 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2949 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2950 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2951 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2953 if (stream == AudioSystem::BLUETOOTH_SCO) {
2954 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2956 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2959 if (stream == AudioSystem::VOICE_CALL ||
2960 stream == AudioSystem::BLUETOOTH_SCO) {
2962 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2963 if (stream == AudioSystem::VOICE_CALL) {
2964 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2969 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2970 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2971 mLastVoiceVolume = voiceVolume;
2978 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2979 audio_devices_t device,
2983 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2985 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2986 checkAndSetVolume(stream,
2987 mStreams[stream].getVolumeIndex(device),
2995 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2997 audio_io_handle_t output,
2999 audio_devices_t device)
3001 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3002 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3003 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3004 setStreamMute(stream, on, output, delayMs, device);
3009 void AudioPolicyManagerBase::setStreamMute(int stream,
3011 audio_io_handle_t output,
3013 audio_devices_t device)
3015 StreamDescriptor &streamDesc = mStreams[stream];
3016 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3017 if (device == AUDIO_DEVICE_NONE) {
3018 device = outputDesc->device();
3021 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3022 stream, on, output, outputDesc->mMuteCount[stream], device);
3025 if (outputDesc->mMuteCount[stream] == 0) {
3026 if (streamDesc.mCanBeMuted &&
3027 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3028 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3029 checkAndSetVolume(stream, 0, output, device, delayMs);
3032 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3033 outputDesc->mMuteCount[stream]++;
3035 if (outputDesc->mMuteCount[stream] == 0) {
3036 ALOGV("setStreamMute() unmuting non muted stream!");
3039 if (--outputDesc->mMuteCount[stream] == 0) {
3040 checkAndSetVolume(stream,
3041 streamDesc.getVolumeIndex(device),
3049 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3051 // if the stream pertains to sonification strategy and we are in call we must
3052 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3053 // in the device used for phone strategy and play the tone if the selected device does not
3054 // interfere with the device used for phone strategy
3055 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3056 // many times as there are active tracks on the output
3057 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3058 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3059 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3060 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3061 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3062 stream, starting, outputDesc->mDevice, stateChange);
3063 if (outputDesc->mRefCount[stream]) {
3066 muteCount = outputDesc->mRefCount[stream];
3068 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3069 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3070 for (int i = 0; i < muteCount; i++) {
3071 setStreamMute(stream, starting, mPrimaryOutput);
3074 ALOGV("handleIncallSonification() high visibility");
3075 if (outputDesc->device() &
3076 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3077 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3078 for (int i = 0; i < muteCount; i++) {
3079 setStreamMute(stream, starting, mPrimaryOutput);
3083 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3085 mpClientInterface->stopTone();
3092 bool AudioPolicyManagerBase::isInCall()
3094 return isStateInCall(mPhoneState);
3097 bool AudioPolicyManagerBase::isStateInCall(int state) {
3098 return ((state == AudioSystem::MODE_IN_CALL) ||
3099 (state == AudioSystem::MODE_IN_COMMUNICATION));
3102 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3104 return MAX_EFFECTS_CPU_LOAD;
3107 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3109 return MAX_EFFECTS_MEMORY;
3112 // --- AudioOutputDescriptor class implementation
3114 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3115 const IOProfile *profile)
3116 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
3117 mChannelMask((audio_channel_mask_t)0), mLatency(0),
3118 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3119 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3121 // clear usage count for all stream types
3122 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3124 mCurVolume[i] = -1.0;
3128 for (int i = 0; i < NUM_STRATEGIES; i++) {
3129 mStrategyMutedByDevice[i] = false;
3131 if (profile != NULL) {
3132 mSamplingRate = profile->mSamplingRates[0];
3133 mFormat = profile->mFormats[0];
3134 mChannelMask = profile->mChannelMasks[0];
3135 mFlags = profile->mFlags;
3139 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3141 if (isDuplicated()) {
3142 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3148 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3150 if (isDuplicated()) {
3151 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3157 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3158 const AudioOutputDescriptor *outputDesc)
3160 if (isDuplicated()) {
3161 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3162 } else if (outputDesc->isDuplicated()){
3163 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3165 return (mProfile->mModule == outputDesc->mProfile->mModule);
3169 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3171 // forward usage count change to attached outputs
3172 if (isDuplicated()) {
3173 mOutput1->changeRefCount(stream, delta);
3174 mOutput2->changeRefCount(stream, delta);
3176 if ((delta + (int)mRefCount[stream]) < 0) {
3177 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3178 mRefCount[stream] = 0;
3181 mRefCount[stream] += delta;
3182 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3185 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3187 if (isDuplicated()) {
3188 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3190 return mProfile->mSupportedDevices ;
3194 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3196 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3199 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3201 nsecs_t sysTime) const
3203 if ((sysTime == 0) && (inPastMs != 0)) {
3204 sysTime = systemTime();
3206 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3207 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3208 (NUM_STRATEGIES == strategy)) &&
3209 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3216 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3218 nsecs_t sysTime) const
3220 if (mRefCount[stream] != 0) {
3223 if (inPastMs == 0) {
3227 sysTime = systemTime();
3229 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3236 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3238 const size_t SIZE = 256;
3242 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3243 result.append(buffer);
3244 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3245 result.append(buffer);
3246 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3247 result.append(buffer);
3248 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3249 result.append(buffer);
3250 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3251 result.append(buffer);
3252 snprintf(buffer, SIZE, " Devices %08x\n", device());
3253 result.append(buffer);
3254 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3255 result.append(buffer);
3256 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3257 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3258 result.append(buffer);
3260 write(fd, result.string(), result.size());
3265 // --- AudioInputDescriptor class implementation
3267 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3268 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3269 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3270 mInputSource(0), mProfile(profile)
3274 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3276 const size_t SIZE = 256;
3280 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3281 result.append(buffer);
3282 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3283 result.append(buffer);
3284 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3285 result.append(buffer);
3286 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3287 result.append(buffer);
3288 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3289 result.append(buffer);
3290 write(fd, result.string(), result.size());
3295 // --- StreamDescriptor class implementation
3297 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3298 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3300 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3303 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3305 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3306 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3307 if (mIndexCur.indexOfKey(device) < 0) {
3308 device = AUDIO_DEVICE_OUT_DEFAULT;
3310 return mIndexCur.valueFor(device);
3313 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3315 const size_t SIZE = 256;
3319 snprintf(buffer, SIZE, "%s %02d %02d ",
3320 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3321 result.append(buffer);
3322 for (size_t i = 0; i < mIndexCur.size(); i++) {
3323 snprintf(buffer, SIZE, "%04x : %02d, ",
3325 mIndexCur.valueAt(i));
3326 result.append(buffer);
3328 result.append("\n");
3330 write(fd, result.string(), result.size());
3333 // --- EffectDescriptor class implementation
3335 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3337 const size_t SIZE = 256;
3341 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3342 result.append(buffer);
3343 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3344 result.append(buffer);
3345 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3346 result.append(buffer);
3347 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3348 result.append(buffer);
3349 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3350 result.append(buffer);
3351 write(fd, result.string(), result.size());
3356 // --- IOProfile class implementation
3358 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3359 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3363 AudioPolicyManagerBase::HwModule::~HwModule()
3365 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3366 delete mOutputProfiles[i];
3368 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3369 delete mInputProfiles[i];
3371 free((void *)mName);
3374 void AudioPolicyManagerBase::HwModule::dump(int fd)
3376 const size_t SIZE = 256;
3380 snprintf(buffer, SIZE, " - name: %s\n", mName);
3381 result.append(buffer);
3382 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3383 result.append(buffer);
3384 write(fd, result.string(), result.size());
3385 if (mOutputProfiles.size()) {
3386 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3387 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3388 snprintf(buffer, SIZE, " output %d:\n", i);
3389 write(fd, buffer, strlen(buffer));
3390 mOutputProfiles[i]->dump(fd);
3393 if (mInputProfiles.size()) {
3394 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3395 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3396 snprintf(buffer, SIZE, " input %d:\n", i);
3397 write(fd, buffer, strlen(buffer));
3398 mInputProfiles[i]->dump(fd);
3403 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3404 : mFlags((audio_output_flags_t)0), mModule(module)
3408 AudioPolicyManagerBase::IOProfile::~IOProfile()
3412 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3413 // means a parameter is don't care
3414 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3415 uint32_t samplingRate,
3417 uint32_t channelMask,
3418 audio_output_flags_t flags) const
3420 if ((mSupportedDevices & device) != device) {
3423 if ((mFlags & flags) != flags) {
3426 if (samplingRate != 0) {
3428 for (i = 0; i < mSamplingRates.size(); i++)
3430 if (mSamplingRates[i] == samplingRate) {
3434 if (i == mSamplingRates.size()) {
3440 for (i = 0; i < mFormats.size(); i++)
3442 if (mFormats[i] == format) {
3446 if (i == mFormats.size()) {
3450 if (channelMask != 0) {
3452 for (i = 0; i < mChannelMasks.size(); i++)
3454 if (mChannelMasks[i] == channelMask) {
3458 if (i == mChannelMasks.size()) {
3465 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3467 const size_t SIZE = 256;
3471 snprintf(buffer, SIZE, " - sampling rates: ");
3472 result.append(buffer);
3473 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3474 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3475 result.append(buffer);
3476 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3479 snprintf(buffer, SIZE, " - channel masks: ");
3480 result.append(buffer);
3481 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3482 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3483 result.append(buffer);
3484 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3487 snprintf(buffer, SIZE, " - formats: ");
3488 result.append(buffer);
3489 for (size_t i = 0; i < mFormats.size(); i++) {
3490 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3491 result.append(buffer);
3492 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3495 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
3496 result.append(buffer);
3497 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3498 result.append(buffer);
3500 write(fd, result.string(), result.size());
3503 // --- audio_policy.conf file parsing
3505 struct StringToEnum {
3510 #define STRING_TO_ENUM(string) { #string, string }
3511 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3513 const struct StringToEnum sDeviceNameToEnumTable[] = {
3514 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3515 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3516 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3517 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3518 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3519 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3520 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3521 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3522 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3523 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3524 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3525 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3526 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3527 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3528 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3529 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3530 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3531 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3532 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3533 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3534 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3535 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3536 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3539 const struct StringToEnum sFlagNameToEnumTable[] = {
3540 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3541 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3542 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3543 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3544 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3545 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3548 const struct StringToEnum sFormatNameToEnumTable[] = {
3549 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3550 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3551 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3552 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3553 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3556 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3557 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3558 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3559 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3560 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3563 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3564 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3565 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3566 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3570 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3574 for (size_t i = 0; i < size; i++) {
3575 if (strcmp(table[i].name, name) == 0) {
3576 ALOGV("stringToEnum() found %s", table[i].name);
3577 return table[i].value;
3583 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3587 // it is OK to cast name to non const here as we are not going to use it after
3588 // strtok() modifies it
3589 char *flagName = strtok(name, "|");
3590 while (flagName != NULL) {
3591 if (strlen(flagName) != 0) {
3592 flag |= stringToEnum(sFlagNameToEnumTable,
3593 ARRAY_SIZE(sFlagNameToEnumTable),
3596 flagName = strtok(NULL, "|");
3598 //force direct flag if offload flag is set: offloading implies a direct output stream
3599 // and all common behaviors are driven by checking only the direct flag
3600 // this should normally be set appropriately in the policy configuration file
3601 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3602 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
3605 return (audio_output_flags_t)flag;
3608 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3610 uint32_t device = 0;
3612 char *devName = strtok(name, "|");
3613 while (devName != NULL) {
3614 if (strlen(devName) != 0) {
3615 device |= stringToEnum(sDeviceNameToEnumTable,
3616 ARRAY_SIZE(sDeviceNameToEnumTable),
3619 devName = strtok(NULL, "|");
3624 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3626 char *str = strtok(name, "|");
3628 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3629 // rates should be read from the output stream after it is opened for the first time
3630 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3631 profile->mSamplingRates.add(0);
3635 while (str != NULL) {
3636 uint32_t rate = atoi(str);
3638 ALOGV("loadSamplingRates() adding rate %d", rate);
3639 profile->mSamplingRates.add(rate);
3641 str = strtok(NULL, "|");
3646 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3648 char *str = strtok(name, "|");
3650 // by convention, "0' in the first entry in mFormats indicates the supported formats
3651 // should be read from the output stream after it is opened for the first time
3652 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3653 profile->mFormats.add((audio_format_t)0);
3657 while (str != NULL) {
3658 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3659 ARRAY_SIZE(sFormatNameToEnumTable),
3662 profile->mFormats.add(format);
3664 str = strtok(NULL, "|");
3669 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3671 const char *str = strtok(name, "|");
3673 ALOGV("loadInChannels() %s", name);
3675 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3676 profile->mChannelMasks.add((audio_channel_mask_t)0);
3680 while (str != NULL) {
3681 audio_channel_mask_t channelMask =
3682 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3683 ARRAY_SIZE(sInChannelsNameToEnumTable),
3685 if (channelMask != 0) {
3686 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3687 profile->mChannelMasks.add(channelMask);
3689 str = strtok(NULL, "|");
3694 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3696 const char *str = strtok(name, "|");
3698 ALOGV("loadOutChannels() %s", name);
3700 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3701 // masks should be read from the output stream after it is opened for the first time
3702 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3703 profile->mChannelMasks.add((audio_channel_mask_t)0);
3707 while (str != NULL) {
3708 audio_channel_mask_t channelMask =
3709 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3710 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3712 if (channelMask != 0) {
3713 profile->mChannelMasks.add(channelMask);
3715 str = strtok(NULL, "|");
3720 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3722 cnode *node = root->first_child;
3724 IOProfile *profile = new IOProfile(module);
3727 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3728 loadSamplingRates((char *)node->value, profile);
3729 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3730 loadFormats((char *)node->value, profile);
3731 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3732 loadInChannels((char *)node->value, profile);
3733 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3734 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3738 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3739 "loadInput() invalid supported devices");
3740 ALOGW_IF(profile->mChannelMasks.size() == 0,
3741 "loadInput() invalid supported channel masks");
3742 ALOGW_IF(profile->mSamplingRates.size() == 0,
3743 "loadInput() invalid supported sampling rates");
3744 ALOGW_IF(profile->mFormats.size() == 0,
3745 "loadInput() invalid supported formats");
3746 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3747 (profile->mChannelMasks.size() != 0) &&
3748 (profile->mSamplingRates.size() != 0) &&
3749 (profile->mFormats.size() != 0)) {
3751 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3753 module->mInputProfiles.add(profile);
3761 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3763 cnode *node = root->first_child;
3765 IOProfile *profile = new IOProfile(module);
3768 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3769 loadSamplingRates((char *)node->value, profile);
3770 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3771 loadFormats((char *)node->value, profile);
3772 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3773 loadOutChannels((char *)node->value, profile);
3774 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3775 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3776 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3777 profile->mFlags = parseFlagNames((char *)node->value);
3781 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3782 "loadOutput() invalid supported devices");
3783 ALOGW_IF(profile->mChannelMasks.size() == 0,
3784 "loadOutput() invalid supported channel masks");
3785 ALOGW_IF(profile->mSamplingRates.size() == 0,
3786 "loadOutput() invalid supported sampling rates");
3787 ALOGW_IF(profile->mFormats.size() == 0,
3788 "loadOutput() invalid supported formats");
3789 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3790 (profile->mChannelMasks.size() != 0) &&
3791 (profile->mSamplingRates.size() != 0) &&
3792 (profile->mFormats.size() != 0)) {
3794 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3795 profile->mSupportedDevices, profile->mFlags);
3797 module->mOutputProfiles.add(profile);
3805 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3807 cnode *node = config_find(root, OUTPUTS_TAG);
3808 status_t status = NAME_NOT_FOUND;
3810 HwModule *module = new HwModule(root->name);
3813 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3815 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3817 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
3818 mHasRemoteSubmix = true;
3821 node = node->first_child;
3823 ALOGV("loadHwModule() loading output %s", node->name);
3824 status_t tmpStatus = loadOutput(node, module);
3825 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3831 node = config_find(root, INPUTS_TAG);
3833 node = node->first_child;
3835 ALOGV("loadHwModule() loading input %s", node->name);
3836 status_t tmpStatus = loadInput(node, module);
3837 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3843 if (status == NO_ERROR) {
3844 mHwModules.add(module);
3850 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3852 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3857 node = node->first_child;
3859 ALOGV("loadHwModules() loading module %s", node->name);
3865 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3867 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3871 node = node->first_child;
3873 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3874 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3875 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
3876 "loadGlobalConfig() no attached output devices");
3877 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3878 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3879 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3880 ARRAY_SIZE(sDeviceNameToEnumTable),
3881 (char *)node->value);
3882 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
3883 "loadGlobalConfig() default device not specified");
3884 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3885 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3886 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
3887 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3893 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3898 data = (char *)load_file(path, NULL);
3902 root = config_node("", "");
3903 config_load(root, data);
3905 loadGlobalConfig(root);
3906 loadHwModules(root);
3912 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3917 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3922 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3923 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3924 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
3926 module = new HwModule("primary");
3928 profile = new IOProfile(module);
3929 profile->mSamplingRates.add(44100);
3930 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3931 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3932 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3933 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3934 module->mOutputProfiles.add(profile);
3936 profile = new IOProfile(module);
3937 profile->mSamplingRates.add(8000);
3938 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3939 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3940 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3941 module->mInputProfiles.add(profile);
3943 mHwModules.add(module);
3946 }; // namespace android