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>
41 namespace android_audio_legacy {
43 // ----------------------------------------------------------------------------
44 // AudioPolicyInterface implementation
45 // ----------------------------------------------------------------------------
48 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
49 AudioSystem::device_connection_state state,
50 const char *device_address)
52 SortedVector <audio_io_handle_t> outputs;
54 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
56 // connect/disconnect only 1 device at a time
57 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
59 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
60 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
64 // handle output devices
65 if (audio_is_output_device(device)) {
67 if (!mHasA2dp && audio_is_a2dp_device(device)) {
68 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
71 if (!mHasUsb && audio_is_usb_device(device)) {
72 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
75 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
76 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
80 // save a copy of the opened output descriptors before any output is opened or closed
81 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
82 mPreviousOutputs = mOutputs;
85 // handle output device connection
86 case AudioSystem::DEVICE_STATE_AVAILABLE:
87 if (mAvailableOutputDevices & device) {
88 ALOGW("setDeviceConnectionState() device already connected: %x", device);
89 return INVALID_OPERATION;
91 ALOGV("setDeviceConnectionState() connecting device %x", device);
93 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
94 return INVALID_OPERATION;
96 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
98 // register new device as available
99 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
101 if (!outputs.isEmpty()) {
103 if (mHasA2dp && audio_is_a2dp_device(device)) {
104 // handle A2DP device connection
105 AudioParameter param;
106 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
107 paramStr = param.toString();
108 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
109 mA2dpSuspended = false;
110 } else if (audio_is_bluetooth_sco_device(device)) {
111 // handle SCO device connection
112 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
113 } else if (mHasUsb && audio_is_usb_device(device)) {
114 // handle USB device connection
115 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
116 paramStr = mUsbCardAndDevice;
118 // not currently handling multiple simultaneous submixes: ignoring remote submix
120 if (!paramStr.isEmpty()) {
121 for (size_t i = 0; i < outputs.size(); i++) {
122 mpClientInterface->setParameters(outputs[i], paramStr);
127 // handle output device disconnection
128 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
129 if (!(mAvailableOutputDevices & device)) {
130 ALOGW("setDeviceConnectionState() device not connected: %x", device);
131 return INVALID_OPERATION;
134 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
135 // remove device from available output devices
136 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
138 checkOutputsForDevice(device, state, outputs);
139 if (mHasA2dp && audio_is_a2dp_device(device)) {
140 // handle A2DP device disconnection
141 mA2dpDeviceAddress = "";
142 mA2dpSuspended = false;
143 } else if (audio_is_bluetooth_sco_device(device)) {
144 // handle SCO device disconnection
145 mScoDeviceAddress = "";
146 } else if (mHasUsb && audio_is_usb_device(device)) {
147 // handle USB device disconnection
148 mUsbCardAndDevice = "";
150 // not currently handling multiple simultaneous submixes: ignoring remote submix
155 ALOGE("setDeviceConnectionState() invalid state: %x", state);
160 checkOutputForAllStrategies();
161 // outputs must be closed after checkOutputForAllStrategies() is executed
162 if (!outputs.isEmpty()) {
163 for (size_t i = 0; i < outputs.size(); i++) {
164 // close unused outputs after device disconnection or direct outputs that have been
165 // opened by checkOutputsForDevice() to query dynamic parameters
166 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
167 (mOutputs.valueFor(outputs[i])->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
168 closeOutput(outputs[i]);
173 updateDevicesAndOutputs();
174 for (size_t i = 0; i < mOutputs.size(); i++) {
175 // do not force device change on duplicated output because if device is 0, it will
176 // also force a device 0 for the two outputs it is duplicated to which may override
177 // a valid device selection on those outputs.
178 setOutputDevice(mOutputs.keyAt(i),
179 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
180 !mOutputs.valueAt(i)->isDuplicated(),
184 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
185 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
186 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
187 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
188 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
189 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
194 // handle input devices
195 if (audio_is_input_device(device)) {
199 // handle input device connection
200 case AudioSystem::DEVICE_STATE_AVAILABLE: {
201 if (mAvailableInputDevices & device) {
202 ALOGW("setDeviceConnectionState() device already connected: %d", device);
203 return INVALID_OPERATION;
205 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
209 // handle input device disconnection
210 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
211 if (!(mAvailableInputDevices & device)) {
212 ALOGW("setDeviceConnectionState() device not connected: %d", device);
213 return INVALID_OPERATION;
215 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
219 ALOGE("setDeviceConnectionState() invalid state: %x", state);
223 audio_io_handle_t activeInput = getActiveInput();
224 if (activeInput != 0) {
225 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
226 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
227 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
228 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
229 inputDesc->mDevice, newDevice, activeInput);
230 inputDesc->mDevice = newDevice;
231 AudioParameter param = AudioParameter();
232 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
233 mpClientInterface->setParameters(activeInput, param.toString());
240 ALOGW("setDeviceConnectionState() invalid device: %x", device);
244 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
245 const char *device_address)
247 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
248 String8 address = String8(device_address);
249 if (audio_is_output_device(device)) {
250 if (device & mAvailableOutputDevices) {
251 if (audio_is_a2dp_device(device) &&
252 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
255 if (audio_is_bluetooth_sco_device(device) &&
256 address != "" && mScoDeviceAddress != address) {
259 if (audio_is_usb_device(device) &&
260 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
261 ALOGE("getDeviceConnectionState() invalid device: %x", device);
264 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
267 state = AudioSystem::DEVICE_STATE_AVAILABLE;
269 } else if (audio_is_input_device(device)) {
270 if (device & mAvailableInputDevices) {
271 state = AudioSystem::DEVICE_STATE_AVAILABLE;
278 void AudioPolicyManagerBase::setPhoneState(int state)
280 ALOGV("setPhoneState() state %d", state);
281 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
282 if (state < 0 || state >= AudioSystem::NUM_MODES) {
283 ALOGW("setPhoneState() invalid state %d", state);
287 if (state == mPhoneState ) {
288 ALOGW("setPhoneState() setting same state %d", state);
292 // if leaving call state, handle special case of active streams
293 // pertaining to sonification strategy see handleIncallSonification()
295 ALOGV("setPhoneState() in call state management: new state is %d", state);
296 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
297 handleIncallSonification(stream, false, true);
301 // store previous phone state for management of sonification strategy below
302 int oldState = mPhoneState;
306 // are we entering or starting a call
307 if (!isStateInCall(oldState) && isStateInCall(state)) {
308 ALOGV(" Entering call in setPhoneState()");
309 // force routing command to audio hardware when starting a call
310 // even if no device change is needed
312 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
313 ALOGV(" Exiting call in setPhoneState()");
314 // force routing command to audio hardware when exiting a call
315 // even if no device change is needed
317 } else if (isStateInCall(state) && (state != oldState)) {
318 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
319 // force routing command to audio hardware when switching between telephony and VoIP
320 // even if no device change is needed
324 // check for device and output changes triggered by new phone state
325 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
327 checkOutputForAllStrategies();
328 updateDevicesAndOutputs();
330 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
332 // force routing command to audio hardware when ending call
333 // even if no device change is needed
334 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
335 newDevice = hwOutputDesc->device();
338 // when changing from ring tone to in call mode, mute the ringing tone
339 // immediately and delay the route change to avoid sending the ring tone
340 // tail into the earpiece or headset.
342 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
343 // delay the device change command by twice the output latency to have some margin
344 // and be sure that audio buffers not yet affected by the mute are out when
345 // we actually apply the route change
346 delayMs = hwOutputDesc->mLatency*2;
347 setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
350 if (isStateInCall(state)) {
351 for (size_t i = 0; i < mOutputs.size(); i++) {
352 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
353 //take the biggest latency for all outputs
354 if (delayMs < (int)desc->mLatency*2) {
355 delayMs = desc->mLatency*2;
357 //mute STRATEGY_MEDIA on all outputs
358 if (desc->strategyRefCount(STRATEGY_MEDIA) != 0) {
359 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
360 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
361 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
366 // change routing is necessary
367 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
369 // if entering in call state, handle special case of active streams
370 // pertaining to sonification strategy see handleIncallSonification()
371 if (isStateInCall(state)) {
372 ALOGV("setPhoneState() in call state management: new state is %d", state);
373 // unmute the ringing tone after a sufficient delay if it was muted before
374 // setting output device above
375 if (oldState == AudioSystem::MODE_RINGTONE) {
376 setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
378 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
379 handleIncallSonification(stream, true, true);
383 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
384 if (state == AudioSystem::MODE_RINGTONE &&
385 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
386 mLimitRingtoneVolume = true;
388 mLimitRingtoneVolume = false;
392 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
394 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
396 bool forceVolumeReeval = false;
398 case AudioSystem::FOR_COMMUNICATION:
399 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
400 config != AudioSystem::FORCE_NONE) {
401 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
404 forceVolumeReeval = true;
405 mForceUse[usage] = config;
407 case AudioSystem::FOR_MEDIA:
408 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
409 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
410 config != AudioSystem::FORCE_ANALOG_DOCK &&
411 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
412 config != AudioSystem::FORCE_NO_BT_A2DP) {
413 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
416 mForceUse[usage] = config;
418 case AudioSystem::FOR_RECORD:
419 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
420 config != AudioSystem::FORCE_NONE) {
421 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
424 mForceUse[usage] = config;
426 case AudioSystem::FOR_DOCK:
427 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
428 config != AudioSystem::FORCE_BT_DESK_DOCK &&
429 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
430 config != AudioSystem::FORCE_ANALOG_DOCK &&
431 config != AudioSystem::FORCE_DIGITAL_DOCK) {
432 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
434 forceVolumeReeval = true;
435 mForceUse[usage] = config;
437 case AudioSystem::FOR_SYSTEM:
438 if (config != AudioSystem::FORCE_NONE &&
439 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
440 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
442 forceVolumeReeval = true;
443 mForceUse[usage] = config;
446 ALOGW("setForceUse() invalid usage %d", usage);
450 // check for device and output changes triggered by new force usage
452 checkOutputForAllStrategies();
453 updateDevicesAndOutputs();
454 for (size_t i = 0; i < mOutputs.size(); i++) {
455 audio_io_handle_t output = mOutputs.keyAt(i);
456 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
457 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
458 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
459 applyStreamVolumes(output, newDevice, 0, true);
463 audio_io_handle_t activeInput = getActiveInput();
464 if (activeInput != 0) {
465 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
466 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
467 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
468 ALOGV("setForceUse() changing device from %x to %x for input %d",
469 inputDesc->mDevice, newDevice, activeInput);
470 inputDesc->mDevice = newDevice;
471 AudioParameter param = AudioParameter();
472 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
473 mpClientInterface->setParameters(activeInput, param.toString());
479 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
481 return mForceUse[usage];
484 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
486 ALOGV("setSystemProperty() property %s, value %s", property, value);
489 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
490 audio_devices_t device,
491 uint32_t samplingRate,
493 uint32_t channelMask,
494 audio_output_flags_t flags)
496 for (size_t i = 0; i < mHwModules.size(); i++) {
497 if (mHwModules[i]->mHandle == 0) {
500 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
501 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
502 if (profile->isCompatibleProfile(device, samplingRate, format,
504 AUDIO_OUTPUT_FLAG_DIRECT)) {
505 if (mAvailableOutputDevices & profile->mSupportedDevices) {
506 return mHwModules[i]->mOutputProfiles[j];
514 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
515 uint32_t samplingRate,
517 uint32_t channelMask,
518 AudioSystem::output_flags flags)
520 audio_io_handle_t output = 0;
521 uint32_t latency = 0;
522 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
523 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
524 ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
525 stream, samplingRate, format, channelMask, flags);
527 #ifdef AUDIO_POLICY_TEST
528 if (mCurOutput != 0) {
529 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
530 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
532 if (mTestOutputs[mCurOutput] == 0) {
533 ALOGV("getOutput() opening test output");
534 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
535 outputDesc->mDevice = mTestDevice;
536 outputDesc->mSamplingRate = mTestSamplingRate;
537 outputDesc->mFormat = mTestFormat;
538 outputDesc->mChannelMask = mTestChannels;
539 outputDesc->mLatency = mTestLatencyMs;
540 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
541 outputDesc->mRefCount[stream] = 0;
542 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
543 &outputDesc->mSamplingRate,
544 &outputDesc->mFormat,
545 &outputDesc->mChannelMask,
546 &outputDesc->mLatency,
548 if (mTestOutputs[mCurOutput]) {
549 AudioParameter outputCmd = AudioParameter();
550 outputCmd.addInt(String8("set_id"),mCurOutput);
551 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
552 addOutput(mTestOutputs[mCurOutput], outputDesc);
555 return mTestOutputs[mCurOutput];
557 #endif //AUDIO_POLICY_TEST
559 // open a direct output if required by specified parameters
560 IOProfile *profile = getProfileForDirectOutput(device,
564 (audio_output_flags_t)flags);
565 if (profile != NULL) {
567 ALOGV("getOutput() opening direct output device %x", device);
569 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(profile);
570 outputDesc->mDevice = device;
571 outputDesc->mSamplingRate = samplingRate;
572 outputDesc->mFormat = (audio_format_t)format;
573 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
574 outputDesc->mLatency = 0;
575 outputDesc->mFlags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);;
576 outputDesc->mRefCount[stream] = 0;
577 outputDesc->mStopTime[stream] = 0;
578 output = mpClientInterface->openOutput(profile->mModule->mHandle,
579 &outputDesc->mDevice,
580 &outputDesc->mSamplingRate,
581 &outputDesc->mFormat,
582 &outputDesc->mChannelMask,
583 &outputDesc->mLatency,
586 // only accept an output with the requested parameters
588 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
589 (format != 0 && format != outputDesc->mFormat) ||
590 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
591 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
592 "format %d %d, channelMask %04x %04x", output, samplingRate,
593 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
594 outputDesc->mChannelMask);
596 mpClientInterface->closeOutput(output);
601 addOutput(output, outputDesc);
602 ALOGV("getOutput() returns direct output %d", output);
606 // ignoring channel mask due to downmix capability in mixer
608 // open a non direct output
610 // get which output is suitable for the specified stream. The actual routing change will happen
611 // when startOutput() will be called
612 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
614 output = selectOutput(outputs, flags);
616 ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
617 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
619 ALOGV("getOutput() returns output %d", output);
624 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
625 AudioSystem::output_flags flags)
627 // select one output among several that provide a path to a particular device or set of
628 // devices (the list was previously build by getOutputsForDevice()).
629 // The priority is as follows:
630 // 1: the output with the highest number of requested policy flags
631 // 2: the primary output
632 // 3: the first output in the list
634 if (outputs.size() == 0) {
637 if (outputs.size() == 1) {
641 int maxCommonFlags = 0;
642 audio_io_handle_t outputFlags = 0;
643 audio_io_handle_t outputPrimary = 0;
645 for (size_t i = 0; i < outputs.size(); i++) {
646 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
647 if (!outputDesc->isDuplicated()) {
648 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
649 if (commonFlags > maxCommonFlags) {
650 outputFlags = outputs[i];
651 maxCommonFlags = commonFlags;
652 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
654 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
655 outputPrimary = outputs[i];
660 if (outputFlags != 0) {
663 if (outputPrimary != 0) {
664 return outputPrimary;
670 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
671 AudioSystem::stream_type stream,
674 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
675 ssize_t index = mOutputs.indexOfKey(output);
677 ALOGW("startOutput() unknow output %d", output);
681 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
683 // increment usage count for this stream on the requested output:
684 // NOTE that the usage count is the same for duplicated output and hardware output which is
685 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
686 outputDesc->changeRefCount(stream, 1);
688 if (outputDesc->mRefCount[stream] == 1) {
689 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
690 routing_strategy strategy = getStrategy(stream);
691 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
692 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
695 for (size_t i = 0; i < mOutputs.size(); i++) {
696 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
697 if (desc != outputDesc) {
698 // force a device change if any other output is managed by the same hw
699 // module and has a current device selection that differs from selected device.
700 // In this case, the audio HAL must receive the new device selection so that it can
701 // change the device currently selected by the other active output.
702 if (outputDesc->sharesHwModuleWith(desc) &&
703 desc->device() != newDevice) {
706 // wait for audio on other active outputs to be presented when starting
707 // a notification so that audio focus effect can propagate.
708 uint32_t latency = desc->latency();
709 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
714 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
716 // handle special case for sonification while in call
718 handleIncallSonification(stream, true, false);
721 // apply volume rules for current stream and device if necessary
722 checkAndSetVolume(stream,
723 mStreams[stream].getVolumeIndex(newDevice),
727 // update the outputs if starting an output with a stream that can affect notification
729 handleNotificationRoutingForStream(stream);
730 if (waitMs > muteWaitMs) {
731 usleep((waitMs - muteWaitMs) * 2 * 1000);
738 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
739 AudioSystem::stream_type stream,
742 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
743 ssize_t index = mOutputs.indexOfKey(output);
745 ALOGW("stopOutput() unknow output %d", output);
749 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
751 // handle special case for sonification while in call
753 handleIncallSonification(stream, false, false);
756 if (outputDesc->mRefCount[stream] > 0) {
757 // decrement usage count of this stream on the output
758 outputDesc->changeRefCount(stream, -1);
759 // store time at which the stream was stopped - see isStreamActive()
760 if (outputDesc->mRefCount[stream] == 0) {
761 outputDesc->mStopTime[stream] = systemTime();
762 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
763 // delay the device switch by twice the latency because stopOutput() is executed when
764 // the track stop() command is received and at that time the audio track buffer can
765 // still contain data that needs to be drained. The latency only covers the audio HAL
766 // and kernel buffers. Also the latency does not always include additional delay in the
767 // audio path (audio DSP, CODEC ...)
768 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
770 // force restoring the device selection on other active outputs if it differs from the
771 // one being selected for this output
772 for (size_t i = 0; i < mOutputs.size(); i++) {
773 audio_io_handle_t curOutput = mOutputs.keyAt(i);
774 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
775 if (curOutput != output &&
776 desc->refCount() != 0 &&
777 outputDesc->sharesHwModuleWith(desc) &&
778 newDevice != desc->device()) {
779 setOutputDevice(curOutput,
780 getNewDevice(curOutput, false /*fromCache*/),
782 outputDesc->mLatency*2);
785 // update the outputs if stopping one with a stream that can affect notification routing
786 handleNotificationRoutingForStream(stream);
790 ALOGW("stopOutput() refcount is already 0 for output %d", output);
791 return INVALID_OPERATION;
795 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
797 ALOGV("releaseOutput() %d", output);
798 ssize_t index = mOutputs.indexOfKey(output);
800 ALOGW("releaseOutput() releasing unknown output %d", output);
804 #ifdef AUDIO_POLICY_TEST
805 int testIndex = testOutputIndex(output);
806 if (testIndex != 0) {
807 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
808 if (outputDesc->refCount() == 0) {
809 mpClientInterface->closeOutput(output);
810 delete mOutputs.valueAt(index);
811 mOutputs.removeItem(output);
812 mTestOutputs[testIndex] = 0;
816 #endif //AUDIO_POLICY_TEST
818 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
819 mpClientInterface->closeOutput(output);
820 delete mOutputs.valueAt(index);
821 mOutputs.removeItem(output);
822 mPreviousOutputs = mOutputs;
827 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
828 uint32_t samplingRate,
830 uint32_t channelMask,
831 AudioSystem::audio_in_acoustics acoustics)
833 audio_io_handle_t input = 0;
834 audio_devices_t device = getDeviceForInputSource(inputSource);
836 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
837 inputSource, samplingRate, format, channelMask, acoustics);
839 if (device == AUDIO_DEVICE_NONE) {
840 ALOGW("getInput() could not find device for inputSource %d", inputSource);
844 // adapt channel selection to input source
845 switch(inputSource) {
846 case AUDIO_SOURCE_VOICE_UPLINK:
847 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
849 case AUDIO_SOURCE_VOICE_DOWNLINK:
850 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
852 case AUDIO_SOURCE_VOICE_CALL:
853 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
859 IOProfile *profile = getInputProfile(device,
863 if (profile == NULL) {
864 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
866 device, samplingRate, format, channelMask);
870 if (profile->mModule->mHandle == 0) {
871 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
875 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
877 inputDesc->mInputSource = inputSource;
878 inputDesc->mDevice = device;
879 inputDesc->mSamplingRate = samplingRate;
880 inputDesc->mFormat = (audio_format_t)format;
881 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
882 inputDesc->mRefCount = 0;
883 input = mpClientInterface->openInput(profile->mModule->mHandle,
885 &inputDesc->mSamplingRate,
887 &inputDesc->mChannelMask);
889 // only accept input with the exact requested set of parameters
891 (samplingRate != inputDesc->mSamplingRate) ||
892 (format != inputDesc->mFormat) ||
893 (channelMask != inputDesc->mChannelMask)) {
894 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
895 samplingRate, format, channelMask);
897 mpClientInterface->closeInput(input);
902 mInputs.add(input, inputDesc);
906 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
908 ALOGV("startInput() input %d", input);
909 ssize_t index = mInputs.indexOfKey(input);
911 ALOGW("startInput() unknow input %d", input);
914 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
916 #ifdef AUDIO_POLICY_TEST
918 #endif //AUDIO_POLICY_TEST
920 // refuse 2 active AudioRecord clients at the same time
921 if (getActiveInput() != 0) {
922 ALOGW("startInput() input %d failed: other input already started", input);
923 return INVALID_OPERATION;
927 AudioParameter param = AudioParameter();
928 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
930 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
931 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
933 mpClientInterface->setParameters(input, param.toString());
935 inputDesc->mRefCount = 1;
939 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
941 ALOGV("stopInput() input %d", input);
942 ssize_t index = mInputs.indexOfKey(input);
944 ALOGW("stopInput() unknow input %d", input);
947 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
949 if (inputDesc->mRefCount == 0) {
950 ALOGW("stopInput() input %d already stopped", input);
951 return INVALID_OPERATION;
953 AudioParameter param = AudioParameter();
954 param.addInt(String8(AudioParameter::keyRouting), 0);
955 mpClientInterface->setParameters(input, param.toString());
956 inputDesc->mRefCount = 0;
961 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
963 ALOGV("releaseInput() %d", input);
964 ssize_t index = mInputs.indexOfKey(input);
966 ALOGW("releaseInput() releasing unknown input %d", input);
969 mpClientInterface->closeInput(input);
970 delete mInputs.valueAt(index);
971 mInputs.removeItem(input);
972 ALOGV("releaseInput() exit");
975 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
979 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
980 if (indexMin < 0 || indexMin >= indexMax) {
981 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
984 mStreams[stream].mIndexMin = indexMin;
985 mStreams[stream].mIndexMax = indexMax;
988 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
990 audio_devices_t device)
993 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
996 if (!audio_is_output_device(device)) {
1000 // Force max volume if stream cannot be muted
1001 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1003 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1004 stream, device, index);
1006 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1007 // clear all device specific values
1008 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1009 mStreams[stream].mIndexCur.clear();
1011 mStreams[stream].mIndexCur.add(device, index);
1013 // compute and apply stream volume on all outputs according to connected device
1014 status_t status = NO_ERROR;
1015 for (size_t i = 0; i < mOutputs.size(); i++) {
1016 audio_devices_t curDevice =
1017 getDeviceForVolume(mOutputs.valueAt(i)->device());
1018 if (device == curDevice) {
1019 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1020 if (volStatus != NO_ERROR) {
1028 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1030 audio_devices_t device)
1032 if (index == NULL) {
1035 if (!audio_is_output_device(device)) {
1038 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1039 // the strategy the stream belongs to.
1040 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1041 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1043 device = getDeviceForVolume(device);
1045 *index = mStreams[stream].getVolumeIndex(device);
1046 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1050 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1052 ALOGV("getOutputForEffect()");
1053 // apply simple rule where global effects are attached to the same output as MUSIC streams
1055 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1056 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1057 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1059 for (size_t i = 0; i < dstOutputs.size(); i++) {
1060 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1061 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1065 return dstOutputs[outIdx];
1068 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1069 audio_io_handle_t io,
1074 ssize_t index = mOutputs.indexOfKey(io);
1076 index = mInputs.indexOfKey(io);
1078 ALOGW("registerEffect() unknown io %d", io);
1079 return INVALID_OPERATION;
1083 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1084 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1085 desc->name, desc->memoryUsage);
1086 return INVALID_OPERATION;
1088 mTotalEffectsMemory += desc->memoryUsage;
1089 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1090 desc->name, io, strategy, session, id);
1091 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1093 EffectDescriptor *pDesc = new EffectDescriptor();
1094 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1096 pDesc->mStrategy = (routing_strategy)strategy;
1097 pDesc->mSession = session;
1098 pDesc->mEnabled = false;
1100 mEffects.add(id, pDesc);
1105 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1107 ssize_t index = mEffects.indexOfKey(id);
1109 ALOGW("unregisterEffect() unknown effect ID %d", id);
1110 return INVALID_OPERATION;
1113 EffectDescriptor *pDesc = mEffects.valueAt(index);
1115 setEffectEnabled(pDesc, false);
1117 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1118 ALOGW("unregisterEffect() memory %d too big for total %d",
1119 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1120 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1122 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1123 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1124 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1126 mEffects.removeItem(id);
1132 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1134 ssize_t index = mEffects.indexOfKey(id);
1136 ALOGW("unregisterEffect() unknown effect ID %d", id);
1137 return INVALID_OPERATION;
1140 return setEffectEnabled(mEffects.valueAt(index), enabled);
1143 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1145 if (enabled == pDesc->mEnabled) {
1146 ALOGV("setEffectEnabled(%s) effect already %s",
1147 enabled?"true":"false", enabled?"enabled":"disabled");
1148 return INVALID_OPERATION;
1152 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1153 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1154 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1155 return INVALID_OPERATION;
1157 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1158 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1160 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1161 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1162 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1163 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1165 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1166 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1168 pDesc->mEnabled = enabled;
1172 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1174 nsecs_t sysTime = systemTime();
1175 for (size_t i = 0; i < mOutputs.size(); i++) {
1176 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
1177 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
1184 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1186 nsecs_t sysTime = systemTime();
1187 for (size_t i = 0; i < mOutputs.size(); i++) {
1188 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1189 if ((outputDesc->mRefCount[stream] != 0 ||
1190 ns2ms(sysTime - outputDesc->mStopTime[stream]) < inPastMs)
1191 && ((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) ) {
1198 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1200 for (size_t i = 0; i < mInputs.size(); i++) {
1201 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1202 if ((inputDescriptor->mInputSource == (int) source)
1203 && (inputDescriptor->mRefCount > 0)) {
1212 status_t AudioPolicyManagerBase::dump(int fd)
1214 const size_t SIZE = 256;
1218 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1219 result.append(buffer);
1221 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1222 result.append(buffer);
1223 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1224 result.append(buffer);
1225 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1226 result.append(buffer);
1227 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1228 result.append(buffer);
1229 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1230 result.append(buffer);
1231 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1232 result.append(buffer);
1233 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1234 result.append(buffer);
1235 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1236 result.append(buffer);
1237 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1238 result.append(buffer);
1239 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1240 result.append(buffer);
1241 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1242 result.append(buffer);
1243 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1244 result.append(buffer);
1245 write(fd, result.string(), result.size());
1248 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1249 write(fd, buffer, strlen(buffer));
1250 for (size_t i = 0; i < mHwModules.size(); i++) {
1251 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1252 write(fd, buffer, strlen(buffer));
1253 mHwModules[i]->dump(fd);
1256 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1257 write(fd, buffer, strlen(buffer));
1258 for (size_t i = 0; i < mOutputs.size(); i++) {
1259 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1260 write(fd, buffer, strlen(buffer));
1261 mOutputs.valueAt(i)->dump(fd);
1264 snprintf(buffer, SIZE, "\nInputs dump:\n");
1265 write(fd, buffer, strlen(buffer));
1266 for (size_t i = 0; i < mInputs.size(); i++) {
1267 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1268 write(fd, buffer, strlen(buffer));
1269 mInputs.valueAt(i)->dump(fd);
1272 snprintf(buffer, SIZE, "\nStreams dump:\n");
1273 write(fd, buffer, strlen(buffer));
1274 snprintf(buffer, SIZE,
1275 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1276 write(fd, buffer, strlen(buffer));
1277 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1278 snprintf(buffer, SIZE, " %02d ", i);
1279 write(fd, buffer, strlen(buffer));
1280 mStreams[i].dump(fd);
1283 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1284 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1285 write(fd, buffer, strlen(buffer));
1287 snprintf(buffer, SIZE, "Registered effects:\n");
1288 write(fd, buffer, strlen(buffer));
1289 for (size_t i = 0; i < mEffects.size(); i++) {
1290 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1291 write(fd, buffer, strlen(buffer));
1292 mEffects.valueAt(i)->dump(fd);
1299 // ----------------------------------------------------------------------------
1300 // AudioPolicyManagerBase
1301 // ----------------------------------------------------------------------------
1303 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1305 #ifdef AUDIO_POLICY_TEST
1307 #endif //AUDIO_POLICY_TEST
1308 mPrimaryOutput((audio_io_handle_t)0),
1309 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1310 mPhoneState(AudioSystem::MODE_NORMAL),
1311 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1312 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1313 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false)
1315 mpClientInterface = clientInterface;
1317 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1318 mForceUse[i] = AudioSystem::FORCE_NONE;
1321 initializeVolumeCurves();
1323 mA2dpDeviceAddress = String8("");
1324 mScoDeviceAddress = String8("");
1325 mUsbCardAndDevice = String8("");
1327 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1328 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1329 ALOGE("could not load audio policy configuration file, setting defaults");
1330 defaultAudioPolicyConfig();
1334 // open all output streams needed to access attached devices
1335 for (size_t i = 0; i < mHwModules.size(); i++) {
1336 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1337 if (mHwModules[i]->mHandle == 0) {
1338 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1341 // open all output streams needed to access attached devices
1342 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1344 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1346 if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1347 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1348 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1349 outProfile->mSupportedDevices);
1350 audio_io_handle_t output = mpClientInterface->openOutput(
1351 outProfile->mModule->mHandle,
1352 &outputDesc->mDevice,
1353 &outputDesc->mSamplingRate,
1354 &outputDesc->mFormat,
1355 &outputDesc->mChannelMask,
1356 &outputDesc->mLatency,
1357 outputDesc->mFlags);
1361 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1362 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1363 if (mPrimaryOutput == 0 &&
1364 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1365 mPrimaryOutput = output;
1367 addOutput(output, outputDesc);
1368 setOutputDevice(output,
1369 (audio_devices_t)(mDefaultOutputDevice &
1370 outProfile->mSupportedDevices),
1377 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1378 "Not output found for attached devices %08x",
1379 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1381 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1383 updateDevicesAndOutputs();
1385 #ifdef AUDIO_POLICY_TEST
1386 if (mPrimaryOutput != 0) {
1387 AudioParameter outputCmd = AudioParameter();
1388 outputCmd.addInt(String8("set_id"), 0);
1389 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1391 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1392 mTestSamplingRate = 44100;
1393 mTestFormat = AudioSystem::PCM_16_BIT;
1394 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1397 mDirectOutput = false;
1398 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1399 mTestOutputs[i] = 0;
1402 const size_t SIZE = 256;
1404 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1405 run(buffer, ANDROID_PRIORITY_AUDIO);
1407 #endif //AUDIO_POLICY_TEST
1410 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1412 #ifdef AUDIO_POLICY_TEST
1414 #endif //AUDIO_POLICY_TEST
1415 for (size_t i = 0; i < mOutputs.size(); i++) {
1416 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1417 delete mOutputs.valueAt(i);
1419 for (size_t i = 0; i < mInputs.size(); i++) {
1420 mpClientInterface->closeInput(mInputs.keyAt(i));
1421 delete mInputs.valueAt(i);
1423 for (size_t i = 0; i < mHwModules.size(); i++) {
1424 delete mHwModules[i];
1428 status_t AudioPolicyManagerBase::initCheck()
1430 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1433 #ifdef AUDIO_POLICY_TEST
1434 bool AudioPolicyManagerBase::threadLoop()
1436 ALOGV("entering threadLoop()");
1437 while (!exitPending())
1443 Mutex::Autolock _l(mLock);
1444 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1446 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1447 AudioParameter param = AudioParameter(command);
1449 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1451 ALOGV("Test command %s received", command.string());
1453 if (param.get(String8("target"), target) != NO_ERROR) {
1456 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1457 param.remove(String8("test_cmd_policy_output"));
1458 mCurOutput = valueInt;
1460 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1461 param.remove(String8("test_cmd_policy_direct"));
1462 if (value == "false") {
1463 mDirectOutput = false;
1464 } else if (value == "true") {
1465 mDirectOutput = true;
1468 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1469 param.remove(String8("test_cmd_policy_input"));
1470 mTestInput = valueInt;
1473 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1474 param.remove(String8("test_cmd_policy_format"));
1475 int format = AudioSystem::INVALID_FORMAT;
1476 if (value == "PCM 16 bits") {
1477 format = AudioSystem::PCM_16_BIT;
1478 } else if (value == "PCM 8 bits") {
1479 format = AudioSystem::PCM_8_BIT;
1480 } else if (value == "Compressed MP3") {
1481 format = AudioSystem::MP3;
1483 if (format != AudioSystem::INVALID_FORMAT) {
1484 if (target == "Manager") {
1485 mTestFormat = format;
1486 } else if (mTestOutputs[mCurOutput] != 0) {
1487 AudioParameter outputParam = AudioParameter();
1488 outputParam.addInt(String8("format"), format);
1489 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1493 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1494 param.remove(String8("test_cmd_policy_channels"));
1497 if (value == "Channels Stereo") {
1498 channels = AudioSystem::CHANNEL_OUT_STEREO;
1499 } else if (value == "Channels Mono") {
1500 channels = AudioSystem::CHANNEL_OUT_MONO;
1502 if (channels != 0) {
1503 if (target == "Manager") {
1504 mTestChannels = channels;
1505 } else if (mTestOutputs[mCurOutput] != 0) {
1506 AudioParameter outputParam = AudioParameter();
1507 outputParam.addInt(String8("channels"), channels);
1508 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1512 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1513 param.remove(String8("test_cmd_policy_sampleRate"));
1514 if (valueInt >= 0 && valueInt <= 96000) {
1515 int samplingRate = valueInt;
1516 if (target == "Manager") {
1517 mTestSamplingRate = samplingRate;
1518 } else if (mTestOutputs[mCurOutput] != 0) {
1519 AudioParameter outputParam = AudioParameter();
1520 outputParam.addInt(String8("sampling_rate"), samplingRate);
1521 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1526 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1527 param.remove(String8("test_cmd_policy_reopen"));
1529 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1530 mpClientInterface->closeOutput(mPrimaryOutput);
1532 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1534 delete mOutputs.valueFor(mPrimaryOutput);
1535 mOutputs.removeItem(mPrimaryOutput);
1537 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1538 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1539 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1540 &outputDesc->mDevice,
1541 &outputDesc->mSamplingRate,
1542 &outputDesc->mFormat,
1543 &outputDesc->mChannelMask,
1544 &outputDesc->mLatency,
1545 outputDesc->mFlags);
1546 if (mPrimaryOutput == 0) {
1547 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1548 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1550 AudioParameter outputCmd = AudioParameter();
1551 outputCmd.addInt(String8("set_id"), 0);
1552 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1553 addOutput(mPrimaryOutput, outputDesc);
1558 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1564 void AudioPolicyManagerBase::exit()
1567 AutoMutex _l(mLock);
1569 mWaitWorkCV.signal();
1571 requestExitAndWait();
1574 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1576 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1577 if (output == mTestOutputs[i]) return i;
1581 #endif //AUDIO_POLICY_TEST
1585 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1587 outputDesc->mId = id;
1588 mOutputs.add(id, outputDesc);
1592 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1593 AudioSystem::device_connection_state state,
1594 SortedVector<audio_io_handle_t>& outputs)
1596 AudioOutputDescriptor *desc;
1598 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1599 // first list already open outputs that can be routed to this device
1600 for (size_t i = 0; i < mOutputs.size(); i++) {
1601 desc = mOutputs.valueAt(i);
1602 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1603 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1604 outputs.add(mOutputs.keyAt(i));
1607 // then look for output profiles that can be routed to this device
1608 SortedVector<IOProfile *> profiles;
1609 for (size_t i = 0; i < mHwModules.size(); i++)
1611 if (mHwModules[i]->mHandle == 0) {
1614 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1616 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1617 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1618 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1623 if (profiles.isEmpty() && outputs.isEmpty()) {
1624 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1628 // open outputs for matching profiles if needed. Direct outputs are also opened to
1629 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1630 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1631 IOProfile *profile = profiles[profile_index];
1633 // nothing to do if one output is already opened for this profile
1635 for (j = 0; j < mOutputs.size(); j++) {
1636 desc = mOutputs.valueAt(j);
1637 if (!desc->isDuplicated() && desc->mProfile == profile) {
1641 if (j != mOutputs.size()) {
1645 ALOGV("opening output for device %08x", device);
1646 desc = new AudioOutputDescriptor(profile);
1647 desc->mDevice = device;
1648 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1650 &desc->mSamplingRate,
1652 &desc->mChannelMask,
1656 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1659 if (profile->mSamplingRates[0] == 0) {
1660 reply = mpClientInterface->getParameters(output,
1661 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1662 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1664 value = strpbrk((char *)reply.string(), "=");
1665 if (value != NULL) {
1666 loadSamplingRates(value + 1, profile);
1669 if (profile->mFormats[0] == 0) {
1670 reply = mpClientInterface->getParameters(output,
1671 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1672 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1674 value = strpbrk((char *)reply.string(), "=");
1675 if (value != NULL) {
1676 loadFormats(value + 1, profile);
1679 if (profile->mChannelMasks[0] == 0) {
1680 reply = mpClientInterface->getParameters(output,
1681 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1682 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1684 value = strpbrk((char *)reply.string(), "=");
1685 if (value != NULL) {
1686 loadOutChannels(value + 1, profile);
1689 if (((profile->mSamplingRates[0] == 0) &&
1690 (profile->mSamplingRates.size() < 2)) ||
1691 ((profile->mFormats[0] == 0) &&
1692 (profile->mFormats.size() < 2)) ||
1693 ((profile->mFormats[0] == 0) &&
1694 (profile->mChannelMasks.size() < 2))) {
1695 ALOGW("checkOutputsForDevice() direct output missing param");
1696 mpClientInterface->closeOutput(output);
1699 addOutput(output, desc);
1702 audio_io_handle_t duplicatedOutput = 0;
1703 // add output descriptor
1704 addOutput(output, desc);
1705 // set initial stream volume for device
1706 applyStreamVolumes(output, device, 0, true);
1708 //TODO: configure audio effect output stage here
1710 // open a duplicating output thread for the new output and the primary output
1711 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1713 if (duplicatedOutput != 0) {
1714 // add duplicated output descriptor
1715 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1716 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1717 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1718 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1719 dupOutputDesc->mFormat = desc->mFormat;
1720 dupOutputDesc->mChannelMask = desc->mChannelMask;
1721 dupOutputDesc->mLatency = desc->mLatency;
1722 addOutput(duplicatedOutput, dupOutputDesc);
1723 applyStreamVolumes(duplicatedOutput, device, 0, true);
1725 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1726 mPrimaryOutput, output);
1727 mpClientInterface->closeOutput(output);
1728 mOutputs.removeItem(output);
1734 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1736 profiles.removeAt(profile_index);
1739 outputs.add(output);
1740 ALOGV("checkOutputsForDevice(): adding output %d", output);
1744 if (profiles.isEmpty()) {
1745 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1749 // check if one opened output is not needed any more after disconnecting one device
1750 for (size_t i = 0; i < mOutputs.size(); i++) {
1751 desc = mOutputs.valueAt(i);
1752 if (!desc->isDuplicated() &&
1753 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1754 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1755 outputs.add(mOutputs.keyAt(i));
1758 for (size_t i = 0; i < mHwModules.size(); i++)
1760 if (mHwModules[i]->mHandle == 0) {
1763 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1765 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1766 if ((profile->mSupportedDevices & device) &&
1767 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1768 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1770 if (profile->mSamplingRates[0] == 0) {
1771 profile->mSamplingRates.clear();
1772 profile->mSamplingRates.add(0);
1774 if (profile->mFormats[0] == 0) {
1775 profile->mFormats.clear();
1776 profile->mFormats.add((audio_format_t)0);
1778 if (profile->mChannelMasks[0] == 0) {
1779 profile->mChannelMasks.clear();
1780 profile->mChannelMasks.add((audio_channel_mask_t)0);
1789 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1791 ALOGV("closeOutput(%d)", output);
1793 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1794 if (outputDesc == NULL) {
1795 ALOGW("closeOutput() unknown output %d", output);
1799 // look for duplicated outputs connected to the output being removed.
1800 for (size_t i = 0; i < mOutputs.size(); i++) {
1801 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1802 if (dupOutputDesc->isDuplicated() &&
1803 (dupOutputDesc->mOutput1 == outputDesc ||
1804 dupOutputDesc->mOutput2 == outputDesc)) {
1805 AudioOutputDescriptor *outputDesc2;
1806 if (dupOutputDesc->mOutput1 == outputDesc) {
1807 outputDesc2 = dupOutputDesc->mOutput2;
1809 outputDesc2 = dupOutputDesc->mOutput1;
1811 // As all active tracks on duplicated output will be deleted,
1812 // and as they were also referenced on the other output, the reference
1813 // count for their stream type must be adjusted accordingly on
1814 // the other output.
1815 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1816 int refCount = dupOutputDesc->mRefCount[j];
1817 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1819 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1820 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1822 mpClientInterface->closeOutput(duplicatedOutput);
1823 delete mOutputs.valueFor(duplicatedOutput);
1824 mOutputs.removeItem(duplicatedOutput);
1828 AudioParameter param;
1829 param.add(String8("closing"), String8("true"));
1830 mpClientInterface->setParameters(output, param.toString());
1832 mpClientInterface->closeOutput(output);
1833 delete mOutputs.valueFor(output);
1834 mOutputs.removeItem(output);
1837 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
1838 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
1840 SortedVector<audio_io_handle_t> outputs;
1842 ALOGVV("getOutputsForDevice() device %04x", device);
1843 for (size_t i = 0; i < openOutputs.size(); i++) {
1844 ALOGVV("output %d isDuplicated=%d device=%04x",
1845 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
1846 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
1847 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
1848 outputs.add(openOutputs.keyAt(i));
1854 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1855 SortedVector<audio_io_handle_t>& outputs2)
1857 if (outputs1.size() != outputs2.size()) {
1860 for (size_t i = 0; i < outputs1.size(); i++) {
1861 if (outputs1[i] != outputs2[i]) {
1868 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1870 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
1871 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
1872 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
1873 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
1875 if (!vectorsEqual(srcOutputs,dstOutputs)) {
1876 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1877 strategy, srcOutputs[0], dstOutputs[0]);
1878 // mute strategy while moving tracks from one output to another
1879 for (size_t i = 0; i < srcOutputs.size(); i++) {
1880 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
1881 if (desc->strategyRefCount(strategy) != 0) {
1882 setStrategyMute(strategy, true, srcOutputs[i]);
1883 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
1887 // Move effects associated to this strategy from previous output to new output
1888 if (strategy == STRATEGY_MEDIA) {
1890 for (size_t i = 0; i < dstOutputs.size(); i++) {
1891 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1892 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1896 SortedVector<audio_io_handle_t> moved;
1897 for (size_t i = 0; i < mEffects.size(); i++) {
1898 EffectDescriptor *desc = mEffects.valueAt(i);
1899 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
1900 desc->mIo != dstOutputs[outIdx]) {
1901 if (moved.indexOf(desc->mIo) < 0) {
1902 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1903 mEffects.keyAt(i), dstOutputs[outIdx]);
1904 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
1905 dstOutputs[outIdx]);
1906 moved.add(desc->mIo);
1908 desc->mIo = dstOutputs[outIdx];
1912 // Move tracks associated to this strategy from previous output to new output
1913 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1914 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1915 //FIXME see fixme on name change
1916 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
1917 dstOutputs[0] /* ignored */);
1923 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1925 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1926 checkOutputForStrategy(STRATEGY_PHONE);
1927 checkOutputForStrategy(STRATEGY_SONIFICATION);
1928 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1929 checkOutputForStrategy(STRATEGY_MEDIA);
1930 checkOutputForStrategy(STRATEGY_DTMF);
1933 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1939 for (size_t i = 0; i < mOutputs.size(); i++) {
1940 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1941 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1942 return mOutputs.keyAt(i);
1949 void AudioPolicyManagerBase::checkA2dpSuspend()
1954 audio_io_handle_t a2dpOutput = getA2dpOutput();
1955 if (a2dpOutput == 0) {
1959 // suspend A2DP output if:
1960 // (NOT already suspended) &&
1961 // ((SCO device is connected &&
1962 // (forced usage for communication || for record is SCO))) ||
1963 // (phone state is ringing || in call)
1965 // restore A2DP output if:
1966 // (Already suspended) &&
1967 // ((SCO device is NOT connected ||
1968 // (forced usage NOT for communication && NOT for record is SCO))) &&
1969 // (phone state is NOT ringing && NOT in call)
1971 if (mA2dpSuspended) {
1972 if (((mScoDeviceAddress == "") ||
1973 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1974 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1975 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1976 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1978 mpClientInterface->restoreOutput(a2dpOutput);
1979 mA2dpSuspended = false;
1982 if (((mScoDeviceAddress != "") &&
1983 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1984 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1985 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1986 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1988 mpClientInterface->suspendOutput(a2dpOutput);
1989 mA2dpSuspended = true;
1994 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1996 audio_devices_t device = AUDIO_DEVICE_NONE;
1998 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1999 // check the following by order of priority to request a routing change if necessary:
2000 // 1: the strategy enforced audible is active on the output:
2001 // use device for strategy enforced audible
2002 // 2: we are in call or the strategy phone is active on the output:
2003 // use device for strategy phone
2004 // 3: the strategy sonification is active on the output:
2005 // use device for strategy sonification
2006 // 4: the strategy "respectful" sonification is active on the output:
2007 // use device for strategy "respectful" sonification
2008 // 5: the strategy media is active on the output:
2009 // use device for strategy media
2010 // 6: the strategy DTMF is active on the output:
2011 // use device for strategy DTMF
2012 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
2013 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2014 } else if (isInCall() ||
2015 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
2016 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2017 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
2018 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2019 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
2020 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2021 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
2022 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2023 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
2024 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2027 ALOGV("getNewDevice() selected device %x", device);
2031 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2032 return (uint32_t)getStrategy(stream);
2035 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2036 audio_devices_t devices;
2037 // By checking the range of stream before calling getStrategy, we avoid
2038 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2039 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2040 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2041 devices = AUDIO_DEVICE_NONE;
2043 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2044 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2049 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2050 AudioSystem::stream_type stream) {
2051 // stream to strategy mapping
2053 case AudioSystem::VOICE_CALL:
2054 case AudioSystem::BLUETOOTH_SCO:
2055 return STRATEGY_PHONE;
2056 case AudioSystem::RING:
2057 case AudioSystem::ALARM:
2058 return STRATEGY_SONIFICATION;
2059 case AudioSystem::NOTIFICATION:
2060 return STRATEGY_SONIFICATION_RESPECTFUL;
2061 case AudioSystem::DTMF:
2062 return STRATEGY_DTMF;
2064 ALOGE("unknown stream type");
2065 case AudioSystem::SYSTEM:
2066 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2067 // while key clicks are played produces a poor result
2068 case AudioSystem::TTS:
2069 case AudioSystem::MUSIC:
2070 return STRATEGY_MEDIA;
2071 case AudioSystem::ENFORCED_AUDIBLE:
2072 return STRATEGY_ENFORCED_AUDIBLE;
2076 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2078 case AudioSystem::MUSIC:
2079 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2080 updateDevicesAndOutputs();
2087 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2090 uint32_t device = AUDIO_DEVICE_NONE;
2093 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2094 strategy, mDeviceForStrategy[strategy]);
2095 return mDeviceForStrategy[strategy];
2100 case STRATEGY_SONIFICATION_RESPECTFUL:
2102 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2103 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2104 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2105 // while media is playing on a remote device, use the the sonification behavior.
2106 // Note that we test this usecase before testing if media is playing because
2107 // the isStreamActive() method only informs about the activity of a stream, not
2108 // if it's for local playback. Note also that we use the same delay between both tests
2109 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2110 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2111 // while media is playing (or has recently played), use the same device
2112 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2114 // when media is not playing anymore, fall back on the sonification behavior
2115 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2122 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2123 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2126 // when in call, DTMF and PHONE strategies follow the same rules
2129 case STRATEGY_PHONE:
2130 // for phone strategy, we first consider the forced use and then the available devices by order
2132 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2133 case AudioSystem::FORCE_BT_SCO:
2134 if (!isInCall() || strategy != STRATEGY_DTMF) {
2135 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2138 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2140 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2142 // if SCO device is requested but no SCO device is available, fall back to default case
2145 default: // FORCE_NONE
2146 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2147 if (mHasA2dp && !isInCall() &&
2148 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2149 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2150 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2152 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2155 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2157 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2159 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2160 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2162 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2164 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2166 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2168 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2171 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2173 device = mDefaultOutputDevice;
2174 if (device == AUDIO_DEVICE_NONE) {
2175 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2179 case AudioSystem::FORCE_SPEAKER:
2180 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2181 // A2DP speaker when forcing to speaker output
2182 if (mHasA2dp && !isInCall() &&
2183 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2184 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2185 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2188 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2189 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2191 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2193 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2195 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2197 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2200 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2202 device = mDefaultOutputDevice;
2203 if (device == AUDIO_DEVICE_NONE) {
2204 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2210 case STRATEGY_SONIFICATION:
2212 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2213 // handleIncallSonification().
2215 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2220 case STRATEGY_ENFORCED_AUDIBLE:
2221 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2223 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2224 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2226 if ((strategy == STRATEGY_SONIFICATION) ||
2227 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2228 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2229 if (device == AUDIO_DEVICE_NONE) {
2230 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2233 // The second device used for sonification is the same as the device used by media strategy
2236 case STRATEGY_MEDIA: {
2237 uint32_t device2 = AUDIO_DEVICE_NONE;
2238 if (strategy != STRATEGY_SONIFICATION) {
2239 // no sonification on remote submix (e.g. WFD)
2240 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2242 if ((device2 == AUDIO_DEVICE_NONE) &&
2243 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2244 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2245 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2246 if (device2 == AUDIO_DEVICE_NONE) {
2247 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2249 if (device2 == AUDIO_DEVICE_NONE) {
2250 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2253 if (device2 == AUDIO_DEVICE_NONE) {
2254 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2256 if (device2 == AUDIO_DEVICE_NONE) {
2257 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2259 if (device2 == AUDIO_DEVICE_NONE) {
2260 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2262 if (device2 == AUDIO_DEVICE_NONE) {
2263 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2265 if (device2 == AUDIO_DEVICE_NONE) {
2266 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2268 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2269 // no sonification on aux digital (e.g. HDMI)
2270 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2272 if ((device2 == AUDIO_DEVICE_NONE) &&
2273 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2274 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2276 if (device2 == AUDIO_DEVICE_NONE) {
2277 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2280 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2281 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2284 device = mDefaultOutputDevice;
2285 if (device == AUDIO_DEVICE_NONE) {
2286 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2291 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2295 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2299 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2301 for (int i = 0; i < NUM_STRATEGIES; i++) {
2302 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2304 mPreviousOutputs = mOutputs;
2307 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2308 audio_devices_t prevDevice,
2311 // mute/unmute strategies using an incompatible device combination
2312 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2313 // if unmuting, unmute only after the specified delay
2314 if (outputDesc->isDuplicated()) {
2318 uint32_t muteWaitMs = 0;
2319 audio_devices_t device = outputDesc->device();
2320 bool shouldMute = (outputDesc->refCount() != 0) &&
2321 (AudioSystem::popCount(device) >= 2);
2322 // temporary mute output if device selection changes to avoid volume bursts due to
2323 // different per device volumes
2324 bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
2326 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2327 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2328 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2329 bool doMute = false;
2331 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2333 outputDesc->mStrategyMutedByDevice[i] = true;
2334 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2336 outputDesc->mStrategyMutedByDevice[i] = false;
2338 if (doMute || tempMute) {
2339 for (size_t j = 0; j < mOutputs.size(); j++) {
2340 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2341 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2342 == AUDIO_DEVICE_NONE) {
2345 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2346 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2347 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2348 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2349 if (desc->strategyRefCount((routing_strategy)i) != 0) {
2351 setStrategyMute((routing_strategy)i, true, curOutput);
2352 setStrategyMute((routing_strategy)i, false, curOutput,
2353 desc->latency() * 2, device);
2355 if (tempMute || mute) {
2356 if (muteWaitMs < desc->latency()) {
2357 muteWaitMs = desc->latency();
2365 // FIXME: should not need to double latency if volume could be applied immediately by the
2366 // audioflinger mixer. We must account for the delay between now and the next time
2367 // the audioflinger thread for this output will process a buffer (which corresponds to
2368 // one buffer size, usually 1/2 or 1/4 of the latency).
2370 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2371 if (muteWaitMs > delayMs) {
2372 muteWaitMs -= delayMs;
2373 usleep(muteWaitMs * 1000);
2379 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2380 audio_devices_t device,
2384 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2385 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2386 AudioParameter param;
2387 uint32_t muteWaitMs = 0;
2389 if (outputDesc->isDuplicated()) {
2390 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2391 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2394 // filter devices according to output selected
2395 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2397 audio_devices_t prevDevice = outputDesc->mDevice;
2399 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2401 if (device != AUDIO_DEVICE_NONE) {
2402 outputDesc->mDevice = device;
2404 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2406 // Do not change the routing if:
2407 // - the requested device is AUDIO_DEVICE_NONE
2408 // - the requested device is the same as current device and force is not specified.
2409 // Doing this check here allows the caller to call setOutputDevice() without conditions
2410 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2411 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2415 ALOGV("setOutputDevice() changing device");
2417 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2418 mpClientInterface->setParameters(output, param.toString(), delayMs);
2420 // update stream volumes according to new device
2421 applyStreamVolumes(output, device, delayMs);
2426 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2427 uint32_t samplingRate,
2429 uint32_t channelMask)
2431 // Choose an input profile based on the requested capture parameters: select the first available
2432 // profile supporting all requested parameters.
2434 for (size_t i = 0; i < mHwModules.size(); i++)
2436 if (mHwModules[i]->mHandle == 0) {
2439 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2441 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2442 if (profile->isCompatibleProfile(device, samplingRate, format,
2443 channelMask,(audio_output_flags_t)0)) {
2451 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2453 uint32_t device = AUDIO_DEVICE_NONE;
2455 switch(inputSource) {
2456 case AUDIO_SOURCE_DEFAULT:
2457 case AUDIO_SOURCE_MIC:
2458 case AUDIO_SOURCE_VOICE_RECOGNITION:
2459 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2460 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2461 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2462 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2463 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2464 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2465 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2466 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2469 case AUDIO_SOURCE_CAMCORDER:
2470 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2471 device = AUDIO_DEVICE_IN_BACK_MIC;
2472 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2473 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2476 case AUDIO_SOURCE_VOICE_UPLINK:
2477 case AUDIO_SOURCE_VOICE_DOWNLINK:
2478 case AUDIO_SOURCE_VOICE_CALL:
2479 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2480 device = AUDIO_DEVICE_IN_VOICE_CALL;
2483 case AUDIO_SOURCE_REMOTE_SUBMIX:
2484 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2485 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2489 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2492 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2496 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2498 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2499 device &= ~AUDIO_DEVICE_BIT_IN;
2500 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2506 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2508 for (size_t i = 0; i < mInputs.size(); i++) {
2509 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2510 if ((input_descriptor->mRefCount > 0)
2511 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2512 return mInputs.keyAt(i);
2519 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2521 if (device == AUDIO_DEVICE_NONE) {
2522 // this happens when forcing a route update and no track is active on an output.
2523 // In this case the returned category is not important.
2524 device = AUDIO_DEVICE_OUT_SPEAKER;
2525 } else if (AudioSystem::popCount(device) > 1) {
2526 // Multiple device selection is either:
2527 // - speaker + one other device: give priority to speaker in this case.
2528 // - one A2DP device + another device: happens with duplicated output. In this case
2529 // retain the device on the A2DP output as the other must not correspond to an active
2530 // selection if not the speaker.
2531 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2532 device = AUDIO_DEVICE_OUT_SPEAKER;
2534 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2538 ALOGW_IF(AudioSystem::popCount(device) != 1,
2539 "getDeviceForVolume() invalid device combination: %08x",
2545 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2547 switch(getDeviceForVolume(device)) {
2548 case AUDIO_DEVICE_OUT_EARPIECE:
2549 return DEVICE_CATEGORY_EARPIECE;
2550 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2551 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2552 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2553 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2554 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2555 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2556 return DEVICE_CATEGORY_HEADSET;
2557 case AUDIO_DEVICE_OUT_SPEAKER:
2558 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2559 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2560 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2561 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2562 case AUDIO_DEVICE_OUT_USB_DEVICE:
2563 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
2565 return DEVICE_CATEGORY_SPEAKER;
2569 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2572 device_category deviceCategory = getDeviceCategory(device);
2573 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2575 // the volume index in the UI is relative to the min and max volume indices for this stream type
2576 int nbSteps = 1 + curve[VOLMAX].mIndex -
2577 curve[VOLMIN].mIndex;
2578 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2579 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2581 // find what part of the curve this index volume belongs to, or if it's out of bounds
2583 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2585 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2587 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2589 } else if (volIdx <= curve[VOLMAX].mIndex) {
2591 } else { // out of bounds
2595 // linear interpolation in the attenuation table in dB
2596 float decibels = curve[segment].mDBAttenuation +
2597 ((float)(volIdx - curve[segment].mIndex)) *
2598 ( (curve[segment+1].mDBAttenuation -
2599 curve[segment].mDBAttenuation) /
2600 ((float)(curve[segment+1].mIndex -
2601 curve[segment].mIndex)) );
2603 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2605 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2606 curve[segment].mIndex, volIdx,
2607 curve[segment+1].mIndex,
2608 curve[segment].mDBAttenuation,
2610 curve[segment+1].mDBAttenuation,
2613 return amplification;
2616 const AudioPolicyManagerBase::VolumeCurvePoint
2617 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2618 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2621 const AudioPolicyManagerBase::VolumeCurvePoint
2622 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2623 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2626 const AudioPolicyManagerBase::VolumeCurvePoint
2627 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2628 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2631 const AudioPolicyManagerBase::VolumeCurvePoint
2632 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2633 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2636 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2637 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2638 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2639 const AudioPolicyManagerBase::VolumeCurvePoint
2640 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2641 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2644 const AudioPolicyManagerBase::VolumeCurvePoint
2645 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2646 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2649 const AudioPolicyManagerBase::VolumeCurvePoint
2650 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2651 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
2654 const AudioPolicyManagerBase::VolumeCurvePoint
2655 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2656 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
2659 const AudioPolicyManagerBase::VolumeCurvePoint
2660 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2661 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2662 { // AUDIO_STREAM_VOICE_CALL
2663 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2664 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2665 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2667 { // AUDIO_STREAM_SYSTEM
2668 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2669 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2670 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2672 { // AUDIO_STREAM_RING
2673 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2674 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2675 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2677 { // AUDIO_STREAM_MUSIC
2678 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2679 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2680 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2682 { // AUDIO_STREAM_ALARM
2683 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2684 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2685 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2687 { // AUDIO_STREAM_NOTIFICATION
2688 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2689 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2690 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2692 { // AUDIO_STREAM_BLUETOOTH_SCO
2693 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2694 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2695 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2697 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2698 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2699 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2700 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2702 { // AUDIO_STREAM_DTMF
2703 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2704 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2705 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2707 { // AUDIO_STREAM_TTS
2708 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2709 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2710 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2714 void AudioPolicyManagerBase::initializeVolumeCurves()
2716 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2717 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2718 mStreams[i].mVolumeCurve[j] =
2719 sVolumeProfiles[i][j];
2724 float AudioPolicyManagerBase::computeVolume(int stream,
2726 audio_io_handle_t output,
2727 audio_devices_t device)
2730 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2731 StreamDescriptor &streamDesc = mStreams[stream];
2733 if (device == AUDIO_DEVICE_NONE) {
2734 device = outputDesc->device();
2737 // if volume is not 0 (not muted), force media volume to max on digital output
2738 if (stream == AudioSystem::MUSIC &&
2739 index != mStreams[stream].mIndexMin &&
2740 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2741 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2742 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2743 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2747 volume = volIndexToAmpl(device, streamDesc, index);
2749 // if a headset is connected, apply the following rules to ring tones and notifications
2750 // to avoid sound level bursts in user's ears:
2751 // - always attenuate ring tones and notifications volume by 6dB
2752 // - if music is playing, always limit the volume to current music volume,
2753 // with a minimum threshold at -36dB so that notification is always perceived.
2754 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2755 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
2756 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2757 AUDIO_DEVICE_OUT_WIRED_HEADSET |
2758 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
2759 ((stream_strategy == STRATEGY_SONIFICATION)
2760 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2761 || (stream == AudioSystem::SYSTEM)
2762 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
2763 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
2764 streamDesc.mCanBeMuted) {
2765 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2766 // when the phone is ringing we must consider that music could have been paused just before
2767 // by the music application and behave as if music was active if the last music track was
2769 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2770 mLimitRingtoneVolume) {
2771 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
2772 float musicVol = computeVolume(AudioSystem::MUSIC,
2773 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
2776 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2777 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2778 if (volume > minVol) {
2780 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2788 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2790 audio_io_handle_t output,
2791 audio_devices_t device,
2796 // do not change actual stream volume if the stream is muted
2797 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2798 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2799 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2803 // do not change in call volume if bluetooth is connected and vice versa
2804 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2805 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2806 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2807 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2808 return INVALID_OPERATION;
2811 float volume = computeVolume(stream, index, output, device);
2812 // We actually change the volume if:
2813 // - the float value returned by computeVolume() changed
2814 // - the force flag is set
2815 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2817 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2818 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2819 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2821 if (stream == AudioSystem::BLUETOOTH_SCO) {
2822 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2824 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2827 if (stream == AudioSystem::VOICE_CALL ||
2828 stream == AudioSystem::BLUETOOTH_SCO) {
2830 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2831 if (stream == AudioSystem::VOICE_CALL) {
2832 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2837 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2838 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2839 mLastVoiceVolume = voiceVolume;
2846 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2847 audio_devices_t device,
2851 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2853 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2854 checkAndSetVolume(stream,
2855 mStreams[stream].getVolumeIndex(device),
2863 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2865 audio_io_handle_t output,
2867 audio_devices_t device)
2869 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2870 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2871 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2872 setStreamMute(stream, on, output, delayMs, device);
2877 void AudioPolicyManagerBase::setStreamMute(int stream,
2879 audio_io_handle_t output,
2881 audio_devices_t device)
2883 StreamDescriptor &streamDesc = mStreams[stream];
2884 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2885 if (device == AUDIO_DEVICE_NONE) {
2886 device = outputDesc->device();
2889 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
2890 stream, on, output, outputDesc->mMuteCount[stream], device);
2893 if (outputDesc->mMuteCount[stream] == 0) {
2894 if (streamDesc.mCanBeMuted &&
2895 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
2896 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
2897 checkAndSetVolume(stream, 0, output, device, delayMs);
2900 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2901 outputDesc->mMuteCount[stream]++;
2903 if (outputDesc->mMuteCount[stream] == 0) {
2904 ALOGV("setStreamMute() unmuting non muted stream!");
2907 if (--outputDesc->mMuteCount[stream] == 0) {
2908 checkAndSetVolume(stream,
2909 streamDesc.getVolumeIndex(device),
2917 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2919 // if the stream pertains to sonification strategy and we are in call we must
2920 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2921 // in the device used for phone strategy and play the tone if the selected device does not
2922 // interfere with the device used for phone strategy
2923 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2924 // many times as there are active tracks on the output
2925 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2926 if ((stream_strategy == STRATEGY_SONIFICATION) ||
2927 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2928 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2929 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2930 stream, starting, outputDesc->mDevice, stateChange);
2931 if (outputDesc->mRefCount[stream]) {
2934 muteCount = outputDesc->mRefCount[stream];
2936 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2937 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2938 for (int i = 0; i < muteCount; i++) {
2939 setStreamMute(stream, starting, mPrimaryOutput);
2942 ALOGV("handleIncallSonification() high visibility");
2943 if (outputDesc->device() &
2944 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2945 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2946 for (int i = 0; i < muteCount; i++) {
2947 setStreamMute(stream, starting, mPrimaryOutput);
2951 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2953 mpClientInterface->stopTone();
2960 bool AudioPolicyManagerBase::isInCall()
2962 return isStateInCall(mPhoneState);
2965 bool AudioPolicyManagerBase::isStateInCall(int state) {
2966 return ((state == AudioSystem::MODE_IN_CALL) ||
2967 (state == AudioSystem::MODE_IN_COMMUNICATION));
2970 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
2971 uint32_t samplingRate,
2972 audio_format_t format,
2973 audio_channel_mask_t channelMask,
2974 audio_output_flags_t flags,
2975 audio_devices_t device)
2977 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2978 (format != 0 && !AudioSystem::isLinearPCM(format)));
2981 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2983 return MAX_EFFECTS_CPU_LOAD;
2986 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2988 return MAX_EFFECTS_MEMORY;
2991 // --- AudioOutputDescriptor class implementation
2993 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2994 const IOProfile *profile)
2995 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
2996 mChannelMask((audio_channel_mask_t)0), mLatency(0),
2997 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
2998 mOutput1(0), mOutput2(0), mProfile(profile)
3000 // clear usage count for all stream types
3001 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3003 mCurVolume[i] = -1.0;
3007 for (int i = 0; i < NUM_STRATEGIES; i++) {
3008 mStrategyMutedByDevice[i] = false;
3010 if (profile != NULL) {
3011 mSamplingRate = profile->mSamplingRates[0];
3012 mFormat = profile->mFormats[0];
3013 mChannelMask = profile->mChannelMasks[0];
3014 mFlags = profile->mFlags;
3018 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3020 if (isDuplicated()) {
3021 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3027 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3029 if (isDuplicated()) {
3030 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3036 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3037 const AudioOutputDescriptor *outputDesc)
3039 if (isDuplicated()) {
3040 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3041 } else if (outputDesc->isDuplicated()){
3042 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3044 return (mProfile->mModule == outputDesc->mProfile->mModule);
3048 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3050 // forward usage count change to attached outputs
3051 if (isDuplicated()) {
3052 mOutput1->changeRefCount(stream, delta);
3053 mOutput2->changeRefCount(stream, delta);
3055 if ((delta + (int)mRefCount[stream]) < 0) {
3056 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3057 mRefCount[stream] = 0;
3060 mRefCount[stream] += delta;
3061 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3064 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
3066 uint32_t refcount = 0;
3067 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
3068 refcount += mRefCount[i];
3073 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
3075 uint32_t refCount = 0;
3076 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
3077 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
3078 refCount += mRefCount[i];
3084 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3086 if (isDuplicated()) {
3087 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3089 return mProfile->mSupportedDevices ;
3093 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3095 nsecs_t sysTime = systemTime();
3096 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3097 if (mRefCount[i] != 0 ||
3098 ns2ms(sysTime - mStopTime[i]) < inPastMs) {
3105 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3107 const size_t SIZE = 256;
3111 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3112 result.append(buffer);
3113 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3114 result.append(buffer);
3115 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3116 result.append(buffer);
3117 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3118 result.append(buffer);
3119 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3120 result.append(buffer);
3121 snprintf(buffer, SIZE, " Devices %08x\n", device());
3122 result.append(buffer);
3123 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3124 result.append(buffer);
3125 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3126 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3127 result.append(buffer);
3129 write(fd, result.string(), result.size());
3134 // --- AudioInputDescriptor class implementation
3136 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3137 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3138 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3139 mInputSource(0), mProfile(profile)
3143 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3145 const size_t SIZE = 256;
3149 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3150 result.append(buffer);
3151 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3152 result.append(buffer);
3153 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3154 result.append(buffer);
3155 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3156 result.append(buffer);
3157 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3158 result.append(buffer);
3159 write(fd, result.string(), result.size());
3164 // --- StreamDescriptor class implementation
3166 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3167 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3169 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3172 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3174 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3175 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3176 if (mIndexCur.indexOfKey(device) < 0) {
3177 device = AUDIO_DEVICE_OUT_DEFAULT;
3179 return mIndexCur.valueFor(device);
3182 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3184 const size_t SIZE = 256;
3188 snprintf(buffer, SIZE, "%s %02d %02d ",
3189 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3190 result.append(buffer);
3191 for (size_t i = 0; i < mIndexCur.size(); i++) {
3192 snprintf(buffer, SIZE, "%04x : %02d, ",
3194 mIndexCur.valueAt(i));
3195 result.append(buffer);
3197 result.append("\n");
3199 write(fd, result.string(), result.size());
3202 // --- EffectDescriptor class implementation
3204 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3206 const size_t SIZE = 256;
3210 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3211 result.append(buffer);
3212 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3213 result.append(buffer);
3214 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3215 result.append(buffer);
3216 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3217 result.append(buffer);
3218 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3219 result.append(buffer);
3220 write(fd, result.string(), result.size());
3225 // --- IOProfile class implementation
3227 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3228 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3232 AudioPolicyManagerBase::HwModule::~HwModule()
3234 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3235 delete mOutputProfiles[i];
3237 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3238 delete mInputProfiles[i];
3240 free((void *)mName);
3243 void AudioPolicyManagerBase::HwModule::dump(int fd)
3245 const size_t SIZE = 256;
3249 snprintf(buffer, SIZE, " - name: %s\n", mName);
3250 result.append(buffer);
3251 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3252 result.append(buffer);
3253 write(fd, result.string(), result.size());
3254 if (mOutputProfiles.size()) {
3255 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3256 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3257 snprintf(buffer, SIZE, " output %d:\n", i);
3258 write(fd, buffer, strlen(buffer));
3259 mOutputProfiles[i]->dump(fd);
3262 if (mInputProfiles.size()) {
3263 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3264 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3265 snprintf(buffer, SIZE, " input %d:\n", i);
3266 write(fd, buffer, strlen(buffer));
3267 mInputProfiles[i]->dump(fd);
3272 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3273 : mFlags((audio_output_flags_t)0), mModule(module)
3277 AudioPolicyManagerBase::IOProfile::~IOProfile()
3281 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3282 // means a parameter is don't care
3283 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3284 uint32_t samplingRate,
3286 uint32_t channelMask,
3287 audio_output_flags_t flags) const
3289 if ((mSupportedDevices & device) != device) {
3292 if ((mFlags & flags) != flags) {
3295 if (samplingRate != 0) {
3297 for (i = 0; i < mSamplingRates.size(); i++)
3299 if (mSamplingRates[i] == samplingRate) {
3303 if (i == mSamplingRates.size()) {
3309 for (i = 0; i < mFormats.size(); i++)
3311 if (mFormats[i] == format) {
3315 if (i == mFormats.size()) {
3319 if (channelMask != 0) {
3321 for (i = 0; i < mChannelMasks.size(); i++)
3323 if (mChannelMasks[i] == channelMask) {
3327 if (i == mChannelMasks.size()) {
3334 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3336 const size_t SIZE = 256;
3340 snprintf(buffer, SIZE, " - sampling rates: ");
3341 result.append(buffer);
3342 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3343 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3344 result.append(buffer);
3345 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3348 snprintf(buffer, SIZE, " - channel masks: ");
3349 result.append(buffer);
3350 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3351 snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3352 result.append(buffer);
3353 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3356 snprintf(buffer, SIZE, " - formats: ");
3357 result.append(buffer);
3358 for (size_t i = 0; i < mFormats.size(); i++) {
3359 snprintf(buffer, SIZE, "%d", mFormats[i]);
3360 result.append(buffer);
3361 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3364 snprintf(buffer, SIZE, " - devices: %04x\n", mSupportedDevices);
3365 result.append(buffer);
3366 snprintf(buffer, SIZE, " - flags: %04x\n", mFlags);
3367 result.append(buffer);
3369 write(fd, result.string(), result.size());
3372 // --- audio_policy.conf file parsing
3374 struct StringToEnum {
3379 #define STRING_TO_ENUM(string) { #string, string }
3380 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3382 const struct StringToEnum sDeviceNameToEnumTable[] = {
3383 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3384 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3385 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3386 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3387 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3388 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3389 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3390 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3391 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3392 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3393 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3394 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3395 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3396 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3397 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3398 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3399 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3400 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3401 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3402 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3403 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3404 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3405 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3408 const struct StringToEnum sFlagNameToEnumTable[] = {
3409 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3410 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3411 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3412 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3415 const struct StringToEnum sFormatNameToEnumTable[] = {
3416 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3417 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3418 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3419 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3420 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3423 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3424 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3425 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3426 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3427 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3430 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3431 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3432 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3433 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3437 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3441 for (size_t i = 0; i < size; i++) {
3442 if (strcmp(table[i].name, name) == 0) {
3443 ALOGV("stringToEnum() found %s", table[i].name);
3444 return table[i].value;
3450 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3454 // it is OK to cast name to non const here as we are not going to use it after
3455 // strtok() modifies it
3456 char *flagName = strtok(name, "|");
3457 while (flagName != NULL) {
3458 if (strlen(flagName) != 0) {
3459 flag |= stringToEnum(sFlagNameToEnumTable,
3460 ARRAY_SIZE(sFlagNameToEnumTable),
3463 flagName = strtok(NULL, "|");
3465 return (audio_output_flags_t)flag;
3468 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3470 uint32_t device = 0;
3472 char *devName = strtok(name, "|");
3473 while (devName != NULL) {
3474 if (strlen(devName) != 0) {
3475 device |= stringToEnum(sDeviceNameToEnumTable,
3476 ARRAY_SIZE(sDeviceNameToEnumTable),
3479 devName = strtok(NULL, "|");
3484 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3486 char *str = strtok(name, "|");
3488 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3489 // rates should be read from the output stream after it is opened for the first time
3490 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3491 profile->mSamplingRates.add(0);
3495 while (str != NULL) {
3496 uint32_t rate = atoi(str);
3498 ALOGV("loadSamplingRates() adding rate %d", rate);
3499 profile->mSamplingRates.add(rate);
3501 str = strtok(NULL, "|");
3506 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3508 char *str = strtok(name, "|");
3510 // by convention, "0' in the first entry in mFormats indicates the supported formats
3511 // should be read from the output stream after it is opened for the first time
3512 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3513 profile->mFormats.add((audio_format_t)0);
3517 while (str != NULL) {
3518 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3519 ARRAY_SIZE(sFormatNameToEnumTable),
3522 profile->mFormats.add(format);
3524 str = strtok(NULL, "|");
3529 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3531 const char *str = strtok(name, "|");
3533 ALOGV("loadInChannels() %s", name);
3535 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3536 profile->mChannelMasks.add((audio_channel_mask_t)0);
3540 while (str != NULL) {
3541 audio_channel_mask_t channelMask =
3542 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3543 ARRAY_SIZE(sInChannelsNameToEnumTable),
3545 if (channelMask != 0) {
3546 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3547 profile->mChannelMasks.add(channelMask);
3549 str = strtok(NULL, "|");
3554 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3556 const char *str = strtok(name, "|");
3558 ALOGV("loadOutChannels() %s", name);
3560 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3561 // masks should be read from the output stream after it is opened for the first time
3562 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3563 profile->mChannelMasks.add((audio_channel_mask_t)0);
3567 while (str != NULL) {
3568 audio_channel_mask_t channelMask =
3569 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3570 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3572 if (channelMask != 0) {
3573 profile->mChannelMasks.add(channelMask);
3575 str = strtok(NULL, "|");
3580 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3582 cnode *node = root->first_child;
3584 IOProfile *profile = new IOProfile(module);
3587 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3588 loadSamplingRates((char *)node->value, profile);
3589 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3590 loadFormats((char *)node->value, profile);
3591 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3592 loadInChannels((char *)node->value, profile);
3593 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3594 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3598 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3599 "loadInput() invalid supported devices");
3600 ALOGW_IF(profile->mChannelMasks.size() == 0,
3601 "loadInput() invalid supported channel masks");
3602 ALOGW_IF(profile->mSamplingRates.size() == 0,
3603 "loadInput() invalid supported sampling rates");
3604 ALOGW_IF(profile->mFormats.size() == 0,
3605 "loadInput() invalid supported formats");
3606 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3607 (profile->mChannelMasks.size() != 0) &&
3608 (profile->mSamplingRates.size() != 0) &&
3609 (profile->mFormats.size() != 0)) {
3611 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3613 module->mInputProfiles.add(profile);
3621 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3623 cnode *node = root->first_child;
3625 IOProfile *profile = new IOProfile(module);
3628 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3629 loadSamplingRates((char *)node->value, profile);
3630 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3631 loadFormats((char *)node->value, profile);
3632 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3633 loadOutChannels((char *)node->value, profile);
3634 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3635 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3636 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3637 profile->mFlags = parseFlagNames((char *)node->value);
3641 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3642 "loadOutput() invalid supported devices");
3643 ALOGW_IF(profile->mChannelMasks.size() == 0,
3644 "loadOutput() invalid supported channel masks");
3645 ALOGW_IF(profile->mSamplingRates.size() == 0,
3646 "loadOutput() invalid supported sampling rates");
3647 ALOGW_IF(profile->mFormats.size() == 0,
3648 "loadOutput() invalid supported formats");
3649 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3650 (profile->mChannelMasks.size() != 0) &&
3651 (profile->mSamplingRates.size() != 0) &&
3652 (profile->mFormats.size() != 0)) {
3654 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3655 profile->mSupportedDevices, profile->mFlags);
3657 module->mOutputProfiles.add(profile);
3665 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3667 cnode *node = config_find(root, OUTPUTS_TAG);
3668 status_t status = NAME_NOT_FOUND;
3670 HwModule *module = new HwModule(root->name);
3673 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3675 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3677 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
3678 mHasRemoteSubmix = true;
3681 node = node->first_child;
3683 ALOGV("loadHwModule() loading output %s", node->name);
3684 status_t tmpStatus = loadOutput(node, module);
3685 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3691 node = config_find(root, INPUTS_TAG);
3693 node = node->first_child;
3695 ALOGV("loadHwModule() loading input %s", node->name);
3696 status_t tmpStatus = loadInput(node, module);
3697 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3703 if (status == NO_ERROR) {
3704 mHwModules.add(module);
3710 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3712 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3717 node = node->first_child;
3719 ALOGV("loadHwModules() loading module %s", node->name);
3725 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3727 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3731 node = node->first_child;
3733 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3734 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3735 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
3736 "loadGlobalConfig() no attached output devices");
3737 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3738 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3739 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3740 ARRAY_SIZE(sDeviceNameToEnumTable),
3741 (char *)node->value);
3742 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
3743 "loadGlobalConfig() default device not specified");
3744 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3745 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3746 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
3747 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3753 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3758 data = (char *)load_file(path, NULL);
3762 root = config_node("", "");
3763 config_load(root, data);
3765 loadGlobalConfig(root);
3766 loadHwModules(root);
3772 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3777 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3782 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3783 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3784 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
3786 module = new HwModule("primary");
3788 profile = new IOProfile(module);
3789 profile->mSamplingRates.add(44100);
3790 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3791 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3792 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3793 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3794 module->mOutputProfiles.add(profile);
3796 profile = new IOProfile(module);
3797 profile->mSamplingRates.add(8000);
3798 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3799 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3800 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3801 module->mInputProfiles.add(profile);
3803 mHwModules.add(module);
3806 }; // namespace android