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
31 #include <utils/Log.h>
32 #include <hardware_legacy/AudioPolicyManagerBase.h>
33 #include <hardware/audio_effect.h>
34 #include <hardware/audio.h>
36 #include <hardware_legacy/audio_policy_conf.h>
38 namespace android_audio_legacy {
40 // ----------------------------------------------------------------------------
41 // AudioPolicyInterface implementation
42 // ----------------------------------------------------------------------------
45 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
46 AudioSystem::device_connection_state state,
47 const char *device_address)
49 SortedVector <audio_io_handle_t> outputs;
51 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
53 // connect/disconnect only 1 device at a time
54 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
56 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
57 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
61 // handle output devices
62 if (audio_is_output_device(device)) {
64 if (!mHasA2dp && audio_is_a2dp_device(device)) {
65 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
68 if (!mHasUsb && audio_is_usb_device(device)) {
69 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
72 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
73 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
77 // save a copy of the opened output descriptors before any output is opened or closed
78 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
79 mPreviousOutputs = mOutputs;
82 // handle output device connection
83 case AudioSystem::DEVICE_STATE_AVAILABLE:
84 if (mAvailableOutputDevices & device) {
85 ALOGW("setDeviceConnectionState() device already connected: %x", device);
86 return INVALID_OPERATION;
88 ALOGV("setDeviceConnectionState() connecting device %x", device);
90 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
91 return INVALID_OPERATION;
93 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
95 // register new device as available
96 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
98 if (!outputs.isEmpty()) {
100 if (mHasA2dp && audio_is_a2dp_device(device)) {
101 // handle A2DP device connection
102 AudioParameter param;
103 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
104 paramStr = param.toString();
105 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
106 mA2dpSuspended = false;
107 } else if (audio_is_bluetooth_sco_device(device)) {
108 // handle SCO device connection
109 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
110 } else if (mHasUsb && audio_is_usb_device(device)) {
111 // handle USB device connection
112 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
113 paramStr = mUsbCardAndDevice;
115 // not currently handling multiple simultaneous submixes: ignoring remote submix
117 if (!paramStr.isEmpty()) {
118 for (size_t i = 0; i < outputs.size(); i++) {
119 mpClientInterface->setParameters(outputs[i], paramStr);
124 // handle output device disconnection
125 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
126 if (!(mAvailableOutputDevices & device)) {
127 ALOGW("setDeviceConnectionState() device not connected: %x", device);
128 return INVALID_OPERATION;
131 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
132 // remove device from available output devices
133 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
135 checkOutputsForDevice(device, state, outputs);
136 if (mHasA2dp && audio_is_a2dp_device(device)) {
137 // handle A2DP device disconnection
138 mA2dpDeviceAddress = "";
139 mA2dpSuspended = false;
140 } else if (audio_is_bluetooth_sco_device(device)) {
141 // handle SCO device disconnection
142 mScoDeviceAddress = "";
143 } else if (mHasUsb && audio_is_usb_device(device)) {
144 // handle USB device disconnection
145 mUsbCardAndDevice = "";
147 // not currently handling multiple simultaneous submixes: ignoring remote submix
152 ALOGE("setDeviceConnectionState() invalid state: %x", state);
157 checkOutputForAllStrategies();
158 // outputs must be closed after checkOutputForAllStrategies() is executed
159 if (!outputs.isEmpty()) {
160 for (size_t i = 0; i < outputs.size(); i++) {
161 // close unused outputs after device disconnection or direct outputs that have been
162 // opened by checkOutputsForDevice() to query dynamic parameters
163 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
164 (mOutputs.valueFor(outputs[i])->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
165 closeOutput(outputs[i]);
170 updateDevicesAndOutputs();
171 for (size_t i = 0; i < mOutputs.size(); i++) {
172 // do not force device change on duplicated output because if device is 0, it will
173 // also force a device 0 for the two outputs it is duplicated to which may override
174 // a valid device selection on those outputs.
175 setOutputDevice(mOutputs.keyAt(i),
176 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
177 !mOutputs.valueAt(i)->isDuplicated(),
181 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
182 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
183 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
184 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
185 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
186 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
191 // handle input devices
192 if (audio_is_input_device(device)) {
196 // handle input device connection
197 case AudioSystem::DEVICE_STATE_AVAILABLE: {
198 if (mAvailableInputDevices & device) {
199 ALOGW("setDeviceConnectionState() device already connected: %d", device);
200 return INVALID_OPERATION;
202 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
206 // handle input device disconnection
207 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
208 if (!(mAvailableInputDevices & device)) {
209 ALOGW("setDeviceConnectionState() device not connected: %d", device);
210 return INVALID_OPERATION;
212 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
216 ALOGE("setDeviceConnectionState() invalid state: %x", state);
220 audio_io_handle_t activeInput = getActiveInput();
221 if (activeInput != 0) {
222 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
223 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
224 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
225 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
226 inputDesc->mDevice, newDevice, activeInput);
227 inputDesc->mDevice = newDevice;
228 AudioParameter param = AudioParameter();
229 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
230 mpClientInterface->setParameters(activeInput, param.toString());
237 ALOGW("setDeviceConnectionState() invalid device: %x", device);
241 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
242 const char *device_address)
244 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
245 String8 address = String8(device_address);
246 if (audio_is_output_device(device)) {
247 if (device & mAvailableOutputDevices) {
248 if (audio_is_a2dp_device(device) &&
249 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
252 if (audio_is_bluetooth_sco_device(device) &&
253 address != "" && mScoDeviceAddress != address) {
256 if (audio_is_usb_device(device) &&
257 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
258 ALOGE("getDeviceConnectionState() invalid device: %x", device);
261 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
264 state = AudioSystem::DEVICE_STATE_AVAILABLE;
266 } else if (audio_is_input_device(device)) {
267 if (device & mAvailableInputDevices) {
268 state = AudioSystem::DEVICE_STATE_AVAILABLE;
275 void AudioPolicyManagerBase::setPhoneState(int state)
277 ALOGV("setPhoneState() state %d", state);
278 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
279 if (state < 0 || state >= AudioSystem::NUM_MODES) {
280 ALOGW("setPhoneState() invalid state %d", state);
284 if (state == mPhoneState ) {
285 ALOGW("setPhoneState() setting same state %d", state);
289 // if leaving call state, handle special case of active streams
290 // pertaining to sonification strategy see handleIncallSonification()
292 ALOGV("setPhoneState() in call state management: new state is %d", state);
293 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
294 handleIncallSonification(stream, false, true);
298 // store previous phone state for management of sonification strategy below
299 int oldState = mPhoneState;
303 // are we entering or starting a call
304 if (!isStateInCall(oldState) && isStateInCall(state)) {
305 ALOGV(" Entering call in setPhoneState()");
306 // force routing command to audio hardware when starting a call
307 // even if no device change is needed
309 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
310 ALOGV(" Exiting call in setPhoneState()");
311 // force routing command to audio hardware when exiting a call
312 // even if no device change is needed
314 } else if (isStateInCall(state) && (state != oldState)) {
315 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
316 // force routing command to audio hardware when switching between telephony and VoIP
317 // even if no device change is needed
321 // check for device and output changes triggered by new phone state
322 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
324 checkOutputForAllStrategies();
325 updateDevicesAndOutputs();
327 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
329 // force routing command to audio hardware when ending call
330 // even if no device change is needed
331 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
332 newDevice = hwOutputDesc->device();
335 // when changing from ring tone to in call mode, mute the ringing tone
336 // immediately and delay the route change to avoid sending the ring tone
337 // tail into the earpiece or headset.
339 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
340 // delay the device change command by twice the output latency to have some margin
341 // and be sure that audio buffers not yet affected by the mute are out when
342 // we actually apply the route change
343 delayMs = hwOutputDesc->mLatency*2;
344 setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
347 if (isStateInCall(state)) {
348 for (size_t i = 0; i < mOutputs.size(); i++) {
349 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
350 //take the biggest latency for all outputs
351 if (delayMs < (int)desc->mLatency*2) {
352 delayMs = desc->mLatency*2;
354 //mute STRATEGY_MEDIA on all outputs
355 if (desc->strategyRefCount(STRATEGY_MEDIA) != 0) {
356 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
357 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
358 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
363 // change routing is necessary
364 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
366 // if entering in call state, handle special case of active streams
367 // pertaining to sonification strategy see handleIncallSonification()
368 if (isStateInCall(state)) {
369 ALOGV("setPhoneState() in call state management: new state is %d", state);
370 // unmute the ringing tone after a sufficient delay if it was muted before
371 // setting output device above
372 if (oldState == AudioSystem::MODE_RINGTONE) {
373 setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
375 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
376 handleIncallSonification(stream, true, true);
380 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
381 if (state == AudioSystem::MODE_RINGTONE &&
382 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
383 mLimitRingtoneVolume = true;
385 mLimitRingtoneVolume = false;
389 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
391 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
393 bool forceVolumeReeval = false;
395 case AudioSystem::FOR_COMMUNICATION:
396 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
397 config != AudioSystem::FORCE_NONE) {
398 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
401 forceVolumeReeval = true;
402 mForceUse[usage] = config;
404 case AudioSystem::FOR_MEDIA:
405 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
406 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
407 config != AudioSystem::FORCE_ANALOG_DOCK &&
408 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
409 config != AudioSystem::FORCE_NO_BT_A2DP) {
410 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
413 mForceUse[usage] = config;
415 case AudioSystem::FOR_RECORD:
416 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
417 config != AudioSystem::FORCE_NONE) {
418 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
421 mForceUse[usage] = config;
423 case AudioSystem::FOR_DOCK:
424 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
425 config != AudioSystem::FORCE_BT_DESK_DOCK &&
426 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
427 config != AudioSystem::FORCE_ANALOG_DOCK &&
428 config != AudioSystem::FORCE_DIGITAL_DOCK) {
429 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
431 forceVolumeReeval = true;
432 mForceUse[usage] = config;
434 case AudioSystem::FOR_SYSTEM:
435 if (config != AudioSystem::FORCE_NONE &&
436 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
437 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
439 forceVolumeReeval = true;
440 mForceUse[usage] = config;
443 ALOGW("setForceUse() invalid usage %d", usage);
447 // check for device and output changes triggered by new force usage
449 checkOutputForAllStrategies();
450 updateDevicesAndOutputs();
451 for (size_t i = 0; i < mOutputs.size(); i++) {
452 audio_io_handle_t output = mOutputs.keyAt(i);
453 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
454 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
455 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
456 applyStreamVolumes(output, newDevice, 0, true);
460 audio_io_handle_t activeInput = getActiveInput();
461 if (activeInput != 0) {
462 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
463 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
464 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
465 ALOGV("setForceUse() changing device from %x to %x for input %d",
466 inputDesc->mDevice, newDevice, activeInput);
467 inputDesc->mDevice = newDevice;
468 AudioParameter param = AudioParameter();
469 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
470 mpClientInterface->setParameters(activeInput, param.toString());
476 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
478 return mForceUse[usage];
481 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
483 ALOGV("setSystemProperty() property %s, value %s", property, value);
486 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
487 audio_devices_t device,
488 uint32_t samplingRate,
490 uint32_t channelMask,
491 audio_output_flags_t flags)
493 for (size_t i = 0; i < mHwModules.size(); i++) {
494 if (mHwModules[i]->mHandle == 0) {
497 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
498 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
499 if (profile->isCompatibleProfile(device, samplingRate, format,
501 AUDIO_OUTPUT_FLAG_DIRECT)) {
502 if (mAvailableOutputDevices & profile->mSupportedDevices) {
503 return mHwModules[i]->mOutputProfiles[j];
511 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
512 uint32_t samplingRate,
514 uint32_t channelMask,
515 AudioSystem::output_flags flags)
517 audio_io_handle_t output = 0;
518 uint32_t latency = 0;
519 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
520 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
521 ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
522 stream, samplingRate, format, channelMask, flags);
524 #ifdef AUDIO_POLICY_TEST
525 if (mCurOutput != 0) {
526 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
527 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
529 if (mTestOutputs[mCurOutput] == 0) {
530 ALOGV("getOutput() opening test output");
531 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
532 outputDesc->mDevice = mTestDevice;
533 outputDesc->mSamplingRate = mTestSamplingRate;
534 outputDesc->mFormat = mTestFormat;
535 outputDesc->mChannelMask = mTestChannels;
536 outputDesc->mLatency = mTestLatencyMs;
537 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
538 outputDesc->mRefCount[stream] = 0;
539 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
540 &outputDesc->mSamplingRate,
541 &outputDesc->mFormat,
542 &outputDesc->mChannelMask,
543 &outputDesc->mLatency,
545 if (mTestOutputs[mCurOutput]) {
546 AudioParameter outputCmd = AudioParameter();
547 outputCmd.addInt(String8("set_id"),mCurOutput);
548 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
549 addOutput(mTestOutputs[mCurOutput], outputDesc);
552 return mTestOutputs[mCurOutput];
554 #endif //AUDIO_POLICY_TEST
556 // open a direct output if required by specified parameters
557 IOProfile *profile = getProfileForDirectOutput(device,
561 (audio_output_flags_t)flags);
562 if (profile != NULL) {
564 ALOGV("getOutput() opening direct output device %x", device);
566 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(profile);
567 outputDesc->mDevice = device;
568 outputDesc->mSamplingRate = samplingRate;
569 outputDesc->mFormat = (audio_format_t)format;
570 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
571 outputDesc->mLatency = 0;
572 outputDesc->mFlags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);;
573 outputDesc->mRefCount[stream] = 0;
574 outputDesc->mStopTime[stream] = 0;
575 output = mpClientInterface->openOutput(profile->mModule->mHandle,
576 &outputDesc->mDevice,
577 &outputDesc->mSamplingRate,
578 &outputDesc->mFormat,
579 &outputDesc->mChannelMask,
580 &outputDesc->mLatency,
583 // only accept an output with the requested parameters
585 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
586 (format != 0 && format != outputDesc->mFormat) ||
587 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
588 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
589 "format %d %d, channelMask %04x %04x", output, samplingRate,
590 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
591 outputDesc->mChannelMask);
593 mpClientInterface->closeOutput(output);
598 addOutput(output, outputDesc);
599 ALOGV("getOutput() returns direct output %d", output);
603 // ignoring channel mask due to downmix capability in mixer
605 // open a non direct output
607 // get which output is suitable for the specified stream. The actual routing change will happen
608 // when startOutput() will be called
609 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
611 output = selectOutput(outputs, flags);
613 ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
614 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
616 ALOGV("getOutput() returns output %d", output);
621 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
622 AudioSystem::output_flags flags)
624 // select one output among several that provide a path to a particular device or set of
625 // devices (the list was previously build by getOutputsForDevice()).
626 // The priority is as follows:
627 // 1: the output with the highest number of requested policy flags
628 // 2: the primary output
629 // 3: the first output in the list
631 if (outputs.size() == 0) {
634 if (outputs.size() == 1) {
638 int maxCommonFlags = 0;
639 audio_io_handle_t outputFlags = 0;
640 audio_io_handle_t outputPrimary = 0;
642 for (size_t i = 0; i < outputs.size(); i++) {
643 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
644 if (!outputDesc->isDuplicated()) {
645 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
646 if (commonFlags > maxCommonFlags) {
647 outputFlags = outputs[i];
648 maxCommonFlags = commonFlags;
649 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
651 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
652 outputPrimary = outputs[i];
657 if (outputFlags != 0) {
660 if (outputPrimary != 0) {
661 return outputPrimary;
667 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
668 AudioSystem::stream_type stream,
671 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
672 ssize_t index = mOutputs.indexOfKey(output);
674 ALOGW("startOutput() unknow output %d", output);
678 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
680 // increment usage count for this stream on the requested output:
681 // NOTE that the usage count is the same for duplicated output and hardware output which is
682 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
683 outputDesc->changeRefCount(stream, 1);
685 if (outputDesc->mRefCount[stream] == 1) {
686 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
687 routing_strategy strategy = getStrategy(stream);
688 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
689 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
692 for (size_t i = 0; i < mOutputs.size(); i++) {
693 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
694 if (desc != outputDesc) {
695 // force a device change if any other output is managed by the same hw
696 // module and has a current device selection that differs from selected device.
697 // In this case, the audio HAL must receive the new device selection so that it can
698 // change the device currently selected by the other active output.
699 if (outputDesc->sharesHwModuleWith(desc) &&
700 desc->device() != newDevice) {
703 // wait for audio on other active outputs to be presented when starting
704 // a notification so that audio focus effect can propagate.
705 uint32_t latency = desc->latency();
706 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
711 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
713 // handle special case for sonification while in call
715 handleIncallSonification(stream, true, false);
718 // apply volume rules for current stream and device if necessary
719 checkAndSetVolume(stream,
720 mStreams[stream].getVolumeIndex(newDevice),
724 // update the outputs if starting an output with a stream that can affect notification
726 handleNotificationRoutingForStream(stream);
727 if (waitMs > muteWaitMs) {
728 usleep((waitMs - muteWaitMs) * 2 * 1000);
735 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
736 AudioSystem::stream_type stream,
739 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
740 ssize_t index = mOutputs.indexOfKey(output);
742 ALOGW("stopOutput() unknow output %d", output);
746 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
748 // handle special case for sonification while in call
750 handleIncallSonification(stream, false, false);
753 if (outputDesc->mRefCount[stream] > 0) {
754 // decrement usage count of this stream on the output
755 outputDesc->changeRefCount(stream, -1);
756 // store time at which the stream was stopped - see isStreamActive()
757 if (outputDesc->mRefCount[stream] == 0) {
758 outputDesc->mStopTime[stream] = systemTime();
759 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
760 // delay the device switch by twice the latency because stopOutput() is executed when
761 // the track stop() command is received and at that time the audio track buffer can
762 // still contain data that needs to be drained. The latency only covers the audio HAL
763 // and kernel buffers. Also the latency does not always include additional delay in the
764 // audio path (audio DSP, CODEC ...)
765 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
767 // force restoring the device selection on other active outputs if it differs from the
768 // one being selected for this output
769 for (size_t i = 0; i < mOutputs.size(); i++) {
770 audio_io_handle_t curOutput = mOutputs.keyAt(i);
771 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
772 if (curOutput != output &&
773 desc->refCount() != 0 &&
774 outputDesc->sharesHwModuleWith(desc) &&
775 newDevice != desc->device()) {
776 setOutputDevice(curOutput,
777 getNewDevice(curOutput, false /*fromCache*/),
779 outputDesc->mLatency*2);
782 // update the outputs if stopping one with a stream that can affect notification routing
783 handleNotificationRoutingForStream(stream);
787 ALOGW("stopOutput() refcount is already 0 for output %d", output);
788 return INVALID_OPERATION;
792 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
794 ALOGV("releaseOutput() %d", output);
795 ssize_t index = mOutputs.indexOfKey(output);
797 ALOGW("releaseOutput() releasing unknown output %d", output);
801 #ifdef AUDIO_POLICY_TEST
802 int testIndex = testOutputIndex(output);
803 if (testIndex != 0) {
804 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
805 if (outputDesc->refCount() == 0) {
806 mpClientInterface->closeOutput(output);
807 delete mOutputs.valueAt(index);
808 mOutputs.removeItem(output);
809 mTestOutputs[testIndex] = 0;
813 #endif //AUDIO_POLICY_TEST
815 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
816 mpClientInterface->closeOutput(output);
817 delete mOutputs.valueAt(index);
818 mOutputs.removeItem(output);
819 mPreviousOutputs = mOutputs;
824 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
825 uint32_t samplingRate,
827 uint32_t channelMask,
828 AudioSystem::audio_in_acoustics acoustics)
830 audio_io_handle_t input = 0;
831 audio_devices_t device = getDeviceForInputSource(inputSource);
833 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
834 inputSource, samplingRate, format, channelMask, acoustics);
836 if (device == AUDIO_DEVICE_NONE) {
837 ALOGW("getInput() could not find device for inputSource %d", inputSource);
841 // adapt channel selection to input source
842 switch(inputSource) {
843 case AUDIO_SOURCE_VOICE_UPLINK:
844 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
846 case AUDIO_SOURCE_VOICE_DOWNLINK:
847 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
849 case AUDIO_SOURCE_VOICE_CALL:
850 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
856 IOProfile *profile = getInputProfile(device,
860 if (profile == NULL) {
861 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
863 device, samplingRate, format, channelMask);
867 if (profile->mModule->mHandle == 0) {
868 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
872 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
874 inputDesc->mInputSource = inputSource;
875 inputDesc->mDevice = device;
876 inputDesc->mSamplingRate = samplingRate;
877 inputDesc->mFormat = (audio_format_t)format;
878 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
879 inputDesc->mRefCount = 0;
880 input = mpClientInterface->openInput(profile->mModule->mHandle,
882 &inputDesc->mSamplingRate,
884 &inputDesc->mChannelMask);
886 // only accept input with the exact requested set of parameters
888 (samplingRate != inputDesc->mSamplingRate) ||
889 (format != inputDesc->mFormat) ||
890 (channelMask != inputDesc->mChannelMask)) {
891 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
892 samplingRate, format, channelMask);
894 mpClientInterface->closeInput(input);
899 mInputs.add(input, inputDesc);
903 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
905 ALOGV("startInput() input %d", input);
906 ssize_t index = mInputs.indexOfKey(input);
908 ALOGW("startInput() unknow input %d", input);
911 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
913 #ifdef AUDIO_POLICY_TEST
915 #endif //AUDIO_POLICY_TEST
917 // refuse 2 active AudioRecord clients at the same time
918 if (getActiveInput() != 0) {
919 ALOGW("startInput() input %d failed: other input already started", input);
920 return INVALID_OPERATION;
924 AudioParameter param = AudioParameter();
925 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
927 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
928 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
930 mpClientInterface->setParameters(input, param.toString());
932 inputDesc->mRefCount = 1;
936 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
938 ALOGV("stopInput() input %d", input);
939 ssize_t index = mInputs.indexOfKey(input);
941 ALOGW("stopInput() unknow input %d", input);
944 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
946 if (inputDesc->mRefCount == 0) {
947 ALOGW("stopInput() input %d already stopped", input);
948 return INVALID_OPERATION;
950 AudioParameter param = AudioParameter();
951 param.addInt(String8(AudioParameter::keyRouting), 0);
952 mpClientInterface->setParameters(input, param.toString());
953 inputDesc->mRefCount = 0;
958 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
960 ALOGV("releaseInput() %d", input);
961 ssize_t index = mInputs.indexOfKey(input);
963 ALOGW("releaseInput() releasing unknown input %d", input);
966 mpClientInterface->closeInput(input);
967 delete mInputs.valueAt(index);
968 mInputs.removeItem(input);
969 ALOGV("releaseInput() exit");
972 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
976 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
977 if (indexMin < 0 || indexMin >= indexMax) {
978 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
981 mStreams[stream].mIndexMin = indexMin;
982 mStreams[stream].mIndexMax = indexMax;
985 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
987 audio_devices_t device)
990 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
993 if (!audio_is_output_device(device)) {
997 // Force max volume if stream cannot be muted
998 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1000 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1001 stream, device, index);
1003 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1004 // clear all device specific values
1005 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1006 mStreams[stream].mIndexCur.clear();
1008 mStreams[stream].mIndexCur.add(device, index);
1010 // compute and apply stream volume on all outputs according to connected device
1011 status_t status = NO_ERROR;
1012 for (size_t i = 0; i < mOutputs.size(); i++) {
1013 audio_devices_t curDevice =
1014 getDeviceForVolume(mOutputs.valueAt(i)->device());
1015 if (device == curDevice) {
1016 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1017 if (volStatus != NO_ERROR) {
1025 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1027 audio_devices_t device)
1029 if (index == NULL) {
1032 if (!audio_is_output_device(device)) {
1035 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1036 // the strategy the stream belongs to.
1037 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1038 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1040 device = getDeviceForVolume(device);
1042 *index = mStreams[stream].getVolumeIndex(device);
1043 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1047 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1049 ALOGV("getOutputForEffect()");
1050 // apply simple rule where global effects are attached to the same output as MUSIC streams
1052 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1053 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1054 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1056 for (size_t i = 0; i < dstOutputs.size(); i++) {
1057 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1058 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1062 return dstOutputs[outIdx];
1065 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1066 audio_io_handle_t io,
1071 ssize_t index = mOutputs.indexOfKey(io);
1073 index = mInputs.indexOfKey(io);
1075 ALOGW("registerEffect() unknown io %d", io);
1076 return INVALID_OPERATION;
1080 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1081 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1082 desc->name, desc->memoryUsage);
1083 return INVALID_OPERATION;
1085 mTotalEffectsMemory += desc->memoryUsage;
1086 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1087 desc->name, io, strategy, session, id);
1088 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1090 EffectDescriptor *pDesc = new EffectDescriptor();
1091 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1093 pDesc->mStrategy = (routing_strategy)strategy;
1094 pDesc->mSession = session;
1095 pDesc->mEnabled = false;
1097 mEffects.add(id, pDesc);
1102 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1104 ssize_t index = mEffects.indexOfKey(id);
1106 ALOGW("unregisterEffect() unknown effect ID %d", id);
1107 return INVALID_OPERATION;
1110 EffectDescriptor *pDesc = mEffects.valueAt(index);
1112 setEffectEnabled(pDesc, false);
1114 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1115 ALOGW("unregisterEffect() memory %d too big for total %d",
1116 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1117 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1119 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1120 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1121 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1123 mEffects.removeItem(id);
1129 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1131 ssize_t index = mEffects.indexOfKey(id);
1133 ALOGW("unregisterEffect() unknown effect ID %d", id);
1134 return INVALID_OPERATION;
1137 return setEffectEnabled(mEffects.valueAt(index), enabled);
1140 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1142 if (enabled == pDesc->mEnabled) {
1143 ALOGV("setEffectEnabled(%s) effect already %s",
1144 enabled?"true":"false", enabled?"enabled":"disabled");
1145 return INVALID_OPERATION;
1149 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1150 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1151 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1152 return INVALID_OPERATION;
1154 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1155 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1157 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1158 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1159 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1160 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1162 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1163 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1165 pDesc->mEnabled = enabled;
1169 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1171 nsecs_t sysTime = systemTime();
1172 for (size_t i = 0; i < mOutputs.size(); i++) {
1173 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
1174 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
1181 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1183 for (size_t i = 0; i < mInputs.size(); i++) {
1184 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1185 if ((inputDescriptor->mInputSource == (int) source)
1186 && (inputDescriptor->mRefCount > 0)) {
1195 status_t AudioPolicyManagerBase::dump(int fd)
1197 const size_t SIZE = 256;
1201 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1202 result.append(buffer);
1204 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1205 result.append(buffer);
1206 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1207 result.append(buffer);
1208 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1209 result.append(buffer);
1210 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1211 result.append(buffer);
1212 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1213 result.append(buffer);
1214 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1215 result.append(buffer);
1216 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1217 result.append(buffer);
1218 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1219 result.append(buffer);
1220 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1221 result.append(buffer);
1222 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1223 result.append(buffer);
1224 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1225 result.append(buffer);
1226 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1227 result.append(buffer);
1228 write(fd, result.string(), result.size());
1231 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1232 write(fd, buffer, strlen(buffer));
1233 for (size_t i = 0; i < mHwModules.size(); i++) {
1234 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1235 write(fd, buffer, strlen(buffer));
1236 mHwModules[i]->dump(fd);
1239 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1240 write(fd, buffer, strlen(buffer));
1241 for (size_t i = 0; i < mOutputs.size(); i++) {
1242 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1243 write(fd, buffer, strlen(buffer));
1244 mOutputs.valueAt(i)->dump(fd);
1247 snprintf(buffer, SIZE, "\nInputs dump:\n");
1248 write(fd, buffer, strlen(buffer));
1249 for (size_t i = 0; i < mInputs.size(); i++) {
1250 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1251 write(fd, buffer, strlen(buffer));
1252 mInputs.valueAt(i)->dump(fd);
1255 snprintf(buffer, SIZE, "\nStreams dump:\n");
1256 write(fd, buffer, strlen(buffer));
1257 snprintf(buffer, SIZE,
1258 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1259 write(fd, buffer, strlen(buffer));
1260 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1261 snprintf(buffer, SIZE, " %02d ", i);
1262 write(fd, buffer, strlen(buffer));
1263 mStreams[i].dump(fd);
1266 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1267 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1268 write(fd, buffer, strlen(buffer));
1270 snprintf(buffer, SIZE, "Registered effects:\n");
1271 write(fd, buffer, strlen(buffer));
1272 for (size_t i = 0; i < mEffects.size(); i++) {
1273 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1274 write(fd, buffer, strlen(buffer));
1275 mEffects.valueAt(i)->dump(fd);
1282 // ----------------------------------------------------------------------------
1283 // AudioPolicyManagerBase
1284 // ----------------------------------------------------------------------------
1286 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1288 #ifdef AUDIO_POLICY_TEST
1290 #endif //AUDIO_POLICY_TEST
1291 mPrimaryOutput((audio_io_handle_t)0),
1292 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1293 mPhoneState(AudioSystem::MODE_NORMAL),
1294 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1295 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1296 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false)
1298 mpClientInterface = clientInterface;
1300 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1301 mForceUse[i] = AudioSystem::FORCE_NONE;
1304 initializeVolumeCurves();
1306 mA2dpDeviceAddress = String8("");
1307 mScoDeviceAddress = String8("");
1308 mUsbCardAndDevice = String8("");
1310 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1311 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1312 ALOGE("could not load audio policy configuration file, setting defaults");
1313 defaultAudioPolicyConfig();
1317 // open all output streams needed to access attached devices
1318 for (size_t i = 0; i < mHwModules.size(); i++) {
1319 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1320 if (mHwModules[i]->mHandle == 0) {
1321 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1324 // open all output streams needed to access attached devices
1325 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1327 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1329 if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1330 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1331 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1332 outProfile->mSupportedDevices);
1333 audio_io_handle_t output = mpClientInterface->openOutput(
1334 outProfile->mModule->mHandle,
1335 &outputDesc->mDevice,
1336 &outputDesc->mSamplingRate,
1337 &outputDesc->mFormat,
1338 &outputDesc->mChannelMask,
1339 &outputDesc->mLatency,
1340 outputDesc->mFlags);
1344 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1345 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1346 if (mPrimaryOutput == 0 &&
1347 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1348 mPrimaryOutput = output;
1350 addOutput(output, outputDesc);
1351 setOutputDevice(output,
1352 (audio_devices_t)(mDefaultOutputDevice &
1353 outProfile->mSupportedDevices),
1360 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1361 "Not output found for attached devices %08x",
1362 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1364 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1366 updateDevicesAndOutputs();
1368 #ifdef AUDIO_POLICY_TEST
1369 if (mPrimaryOutput != 0) {
1370 AudioParameter outputCmd = AudioParameter();
1371 outputCmd.addInt(String8("set_id"), 0);
1372 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1374 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1375 mTestSamplingRate = 44100;
1376 mTestFormat = AudioSystem::PCM_16_BIT;
1377 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1380 mDirectOutput = false;
1381 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1382 mTestOutputs[i] = 0;
1385 const size_t SIZE = 256;
1387 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1388 run(buffer, ANDROID_PRIORITY_AUDIO);
1390 #endif //AUDIO_POLICY_TEST
1393 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1395 #ifdef AUDIO_POLICY_TEST
1397 #endif //AUDIO_POLICY_TEST
1398 for (size_t i = 0; i < mOutputs.size(); i++) {
1399 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1400 delete mOutputs.valueAt(i);
1402 for (size_t i = 0; i < mInputs.size(); i++) {
1403 mpClientInterface->closeInput(mInputs.keyAt(i));
1404 delete mInputs.valueAt(i);
1406 for (size_t i = 0; i < mHwModules.size(); i++) {
1407 delete mHwModules[i];
1411 status_t AudioPolicyManagerBase::initCheck()
1413 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1416 #ifdef AUDIO_POLICY_TEST
1417 bool AudioPolicyManagerBase::threadLoop()
1419 ALOGV("entering threadLoop()");
1420 while (!exitPending())
1426 Mutex::Autolock _l(mLock);
1427 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1429 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1430 AudioParameter param = AudioParameter(command);
1432 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1434 ALOGV("Test command %s received", command.string());
1436 if (param.get(String8("target"), target) != NO_ERROR) {
1439 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1440 param.remove(String8("test_cmd_policy_output"));
1441 mCurOutput = valueInt;
1443 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1444 param.remove(String8("test_cmd_policy_direct"));
1445 if (value == "false") {
1446 mDirectOutput = false;
1447 } else if (value == "true") {
1448 mDirectOutput = true;
1451 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1452 param.remove(String8("test_cmd_policy_input"));
1453 mTestInput = valueInt;
1456 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1457 param.remove(String8("test_cmd_policy_format"));
1458 int format = AudioSystem::INVALID_FORMAT;
1459 if (value == "PCM 16 bits") {
1460 format = AudioSystem::PCM_16_BIT;
1461 } else if (value == "PCM 8 bits") {
1462 format = AudioSystem::PCM_8_BIT;
1463 } else if (value == "Compressed MP3") {
1464 format = AudioSystem::MP3;
1466 if (format != AudioSystem::INVALID_FORMAT) {
1467 if (target == "Manager") {
1468 mTestFormat = format;
1469 } else if (mTestOutputs[mCurOutput] != 0) {
1470 AudioParameter outputParam = AudioParameter();
1471 outputParam.addInt(String8("format"), format);
1472 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1476 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1477 param.remove(String8("test_cmd_policy_channels"));
1480 if (value == "Channels Stereo") {
1481 channels = AudioSystem::CHANNEL_OUT_STEREO;
1482 } else if (value == "Channels Mono") {
1483 channels = AudioSystem::CHANNEL_OUT_MONO;
1485 if (channels != 0) {
1486 if (target == "Manager") {
1487 mTestChannels = channels;
1488 } else if (mTestOutputs[mCurOutput] != 0) {
1489 AudioParameter outputParam = AudioParameter();
1490 outputParam.addInt(String8("channels"), channels);
1491 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1495 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1496 param.remove(String8("test_cmd_policy_sampleRate"));
1497 if (valueInt >= 0 && valueInt <= 96000) {
1498 int samplingRate = valueInt;
1499 if (target == "Manager") {
1500 mTestSamplingRate = samplingRate;
1501 } else if (mTestOutputs[mCurOutput] != 0) {
1502 AudioParameter outputParam = AudioParameter();
1503 outputParam.addInt(String8("sampling_rate"), samplingRate);
1504 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1509 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1510 param.remove(String8("test_cmd_policy_reopen"));
1512 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1513 mpClientInterface->closeOutput(mPrimaryOutput);
1515 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1517 delete mOutputs.valueFor(mPrimaryOutput);
1518 mOutputs.removeItem(mPrimaryOutput);
1520 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1521 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1522 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1523 &outputDesc->mDevice,
1524 &outputDesc->mSamplingRate,
1525 &outputDesc->mFormat,
1526 &outputDesc->mChannelMask,
1527 &outputDesc->mLatency,
1528 outputDesc->mFlags);
1529 if (mPrimaryOutput == 0) {
1530 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1531 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1533 AudioParameter outputCmd = AudioParameter();
1534 outputCmd.addInt(String8("set_id"), 0);
1535 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1536 addOutput(mPrimaryOutput, outputDesc);
1541 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1547 void AudioPolicyManagerBase::exit()
1550 AutoMutex _l(mLock);
1552 mWaitWorkCV.signal();
1554 requestExitAndWait();
1557 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1559 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1560 if (output == mTestOutputs[i]) return i;
1564 #endif //AUDIO_POLICY_TEST
1568 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1570 outputDesc->mId = id;
1571 mOutputs.add(id, outputDesc);
1575 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1576 AudioSystem::device_connection_state state,
1577 SortedVector<audio_io_handle_t>& outputs)
1579 AudioOutputDescriptor *desc;
1581 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1582 // first list already open outputs that can be routed to this device
1583 for (size_t i = 0; i < mOutputs.size(); i++) {
1584 desc = mOutputs.valueAt(i);
1585 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1586 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1587 outputs.add(mOutputs.keyAt(i));
1590 // then look for output profiles that can be routed to this device
1591 SortedVector<IOProfile *> profiles;
1592 for (size_t i = 0; i < mHwModules.size(); i++)
1594 if (mHwModules[i]->mHandle == 0) {
1597 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1599 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1600 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1601 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1606 if (profiles.isEmpty() && outputs.isEmpty()) {
1607 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1611 // open outputs for matching profiles if needed. Direct outputs are also opened to
1612 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1613 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1614 IOProfile *profile = profiles[profile_index];
1616 // nothing to do if one output is already opened for this profile
1618 for (j = 0; j < mOutputs.size(); j++) {
1619 desc = mOutputs.valueAt(j);
1620 if (!desc->isDuplicated() && desc->mProfile == profile) {
1624 if (j != mOutputs.size()) {
1628 ALOGV("opening output for device %08x", device);
1629 desc = new AudioOutputDescriptor(profile);
1630 desc->mDevice = device;
1631 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1633 &desc->mSamplingRate,
1635 &desc->mChannelMask,
1639 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1642 if (profile->mSamplingRates[0] == 0) {
1643 reply = mpClientInterface->getParameters(output,
1644 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1645 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1647 value = strpbrk((char *)reply.string(), "=");
1648 if (value != NULL) {
1649 loadSamplingRates(value + 1, profile);
1652 if (profile->mFormats[0] == 0) {
1653 reply = mpClientInterface->getParameters(output,
1654 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1655 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1657 value = strpbrk((char *)reply.string(), "=");
1658 if (value != NULL) {
1659 loadFormats(value + 1, profile);
1662 if (profile->mChannelMasks[0] == 0) {
1663 reply = mpClientInterface->getParameters(output,
1664 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1665 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1667 value = strpbrk((char *)reply.string(), "=");
1668 if (value != NULL) {
1669 loadOutChannels(value + 1, profile);
1672 if (((profile->mSamplingRates[0] == 0) &&
1673 (profile->mSamplingRates.size() < 2)) ||
1674 ((profile->mFormats[0] == 0) &&
1675 (profile->mFormats.size() < 2)) ||
1676 ((profile->mFormats[0] == 0) &&
1677 (profile->mChannelMasks.size() < 2))) {
1678 ALOGW("checkOutputsForDevice() direct output missing param");
1679 mpClientInterface->closeOutput(output);
1682 addOutput(output, desc);
1685 audio_io_handle_t duplicatedOutput = 0;
1686 // add output descriptor
1687 addOutput(output, desc);
1688 // set initial stream volume for device
1689 applyStreamVolumes(output, device, 0, true);
1691 //TODO: configure audio effect output stage here
1693 // open a duplicating output thread for the new output and the primary output
1694 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1696 if (duplicatedOutput != 0) {
1697 // add duplicated output descriptor
1698 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1699 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1700 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1701 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1702 dupOutputDesc->mFormat = desc->mFormat;
1703 dupOutputDesc->mChannelMask = desc->mChannelMask;
1704 dupOutputDesc->mLatency = desc->mLatency;
1705 addOutput(duplicatedOutput, dupOutputDesc);
1706 applyStreamVolumes(duplicatedOutput, device, 0, true);
1708 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1709 mPrimaryOutput, output);
1710 mpClientInterface->closeOutput(output);
1711 mOutputs.removeItem(output);
1717 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1719 profiles.removeAt(profile_index);
1722 outputs.add(output);
1723 ALOGV("checkOutputsForDevice(): adding output %d", output);
1727 if (profiles.isEmpty()) {
1728 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1732 // check if one opened output is not needed any more after disconnecting one device
1733 for (size_t i = 0; i < mOutputs.size(); i++) {
1734 desc = mOutputs.valueAt(i);
1735 if (!desc->isDuplicated() &&
1736 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1737 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1738 outputs.add(mOutputs.keyAt(i));
1741 for (size_t i = 0; i < mHwModules.size(); i++)
1743 if (mHwModules[i]->mHandle == 0) {
1746 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1748 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1749 if ((profile->mSupportedDevices & device) &&
1750 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1751 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1753 if (profile->mSamplingRates[0] == 0) {
1754 profile->mSamplingRates.clear();
1755 profile->mSamplingRates.add(0);
1757 if (profile->mFormats[0] == 0) {
1758 profile->mFormats.clear();
1759 profile->mFormats.add((audio_format_t)0);
1761 if (profile->mChannelMasks[0] == 0) {
1762 profile->mChannelMasks.clear();
1763 profile->mChannelMasks.add((audio_channel_mask_t)0);
1772 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1774 ALOGV("closeOutput(%d)", output);
1776 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1777 if (outputDesc == NULL) {
1778 ALOGW("closeOutput() unknown output %d", output);
1782 // look for duplicated outputs connected to the output being removed.
1783 for (size_t i = 0; i < mOutputs.size(); i++) {
1784 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1785 if (dupOutputDesc->isDuplicated() &&
1786 (dupOutputDesc->mOutput1 == outputDesc ||
1787 dupOutputDesc->mOutput2 == outputDesc)) {
1788 AudioOutputDescriptor *outputDesc2;
1789 if (dupOutputDesc->mOutput1 == outputDesc) {
1790 outputDesc2 = dupOutputDesc->mOutput2;
1792 outputDesc2 = dupOutputDesc->mOutput1;
1794 // As all active tracks on duplicated output will be deleted,
1795 // and as they were also referenced on the other output, the reference
1796 // count for their stream type must be adjusted accordingly on
1797 // the other output.
1798 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1799 int refCount = dupOutputDesc->mRefCount[j];
1800 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1802 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1803 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1805 mpClientInterface->closeOutput(duplicatedOutput);
1806 delete mOutputs.valueFor(duplicatedOutput);
1807 mOutputs.removeItem(duplicatedOutput);
1811 AudioParameter param;
1812 param.add(String8("closing"), String8("true"));
1813 mpClientInterface->setParameters(output, param.toString());
1815 mpClientInterface->closeOutput(output);
1816 delete mOutputs.valueFor(output);
1817 mOutputs.removeItem(output);
1820 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
1821 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
1823 SortedVector<audio_io_handle_t> outputs;
1825 ALOGVV("getOutputsForDevice() device %04x", device);
1826 for (size_t i = 0; i < openOutputs.size(); i++) {
1827 ALOGVV("output %d isDuplicated=%d device=%04x",
1828 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
1829 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
1830 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
1831 outputs.add(openOutputs.keyAt(i));
1837 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1838 SortedVector<audio_io_handle_t>& outputs2)
1840 if (outputs1.size() != outputs2.size()) {
1843 for (size_t i = 0; i < outputs1.size(); i++) {
1844 if (outputs1[i] != outputs2[i]) {
1851 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1853 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
1854 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
1855 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
1856 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
1858 if (!vectorsEqual(srcOutputs,dstOutputs)) {
1859 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1860 strategy, srcOutputs[0], dstOutputs[0]);
1861 // mute strategy while moving tracks from one output to another
1862 for (size_t i = 0; i < srcOutputs.size(); i++) {
1863 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
1864 if (desc->strategyRefCount(strategy) != 0) {
1865 setStrategyMute(strategy, true, srcOutputs[i]);
1866 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
1870 // Move effects associated to this strategy from previous output to new output
1871 if (strategy == STRATEGY_MEDIA) {
1873 for (size_t i = 0; i < dstOutputs.size(); i++) {
1874 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1875 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1879 SortedVector<audio_io_handle_t> moved;
1880 for (size_t i = 0; i < mEffects.size(); i++) {
1881 EffectDescriptor *desc = mEffects.valueAt(i);
1882 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
1883 desc->mIo != dstOutputs[outIdx]) {
1884 if (moved.indexOf(desc->mIo) < 0) {
1885 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1886 mEffects.keyAt(i), dstOutputs[outIdx]);
1887 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
1888 dstOutputs[outIdx]);
1889 moved.add(desc->mIo);
1891 desc->mIo = dstOutputs[outIdx];
1895 // Move tracks associated to this strategy from previous output to new output
1896 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1897 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1898 //FIXME see fixme on name change
1899 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
1900 dstOutputs[0] /* ignored */);
1906 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1908 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1909 checkOutputForStrategy(STRATEGY_PHONE);
1910 checkOutputForStrategy(STRATEGY_SONIFICATION);
1911 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1912 checkOutputForStrategy(STRATEGY_MEDIA);
1913 checkOutputForStrategy(STRATEGY_DTMF);
1916 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1922 for (size_t i = 0; i < mOutputs.size(); i++) {
1923 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1924 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1925 return mOutputs.keyAt(i);
1932 void AudioPolicyManagerBase::checkA2dpSuspend()
1937 audio_io_handle_t a2dpOutput = getA2dpOutput();
1938 if (a2dpOutput == 0) {
1942 // suspend A2DP output if:
1943 // (NOT already suspended) &&
1944 // ((SCO device is connected &&
1945 // (forced usage for communication || for record is SCO))) ||
1946 // (phone state is ringing || in call)
1948 // restore A2DP output if:
1949 // (Already suspended) &&
1950 // ((SCO device is NOT connected ||
1951 // (forced usage NOT for communication && NOT for record is SCO))) &&
1952 // (phone state is NOT ringing && NOT in call)
1954 if (mA2dpSuspended) {
1955 if (((mScoDeviceAddress == "") ||
1956 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1957 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1958 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1959 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1961 mpClientInterface->restoreOutput(a2dpOutput);
1962 mA2dpSuspended = false;
1965 if (((mScoDeviceAddress != "") &&
1966 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1967 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1968 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1969 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1971 mpClientInterface->suspendOutput(a2dpOutput);
1972 mA2dpSuspended = true;
1977 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1979 audio_devices_t device = AUDIO_DEVICE_NONE;
1981 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1982 // check the following by order of priority to request a routing change if necessary:
1983 // 1: the strategy enforced audible is active on the output:
1984 // use device for strategy enforced audible
1985 // 2: we are in call or the strategy phone is active on the output:
1986 // use device for strategy phone
1987 // 3: the strategy sonification is active on the output:
1988 // use device for strategy sonification
1989 // 4: the strategy "respectful" sonification is active on the output:
1990 // use device for strategy "respectful" sonification
1991 // 5: the strategy media is active on the output:
1992 // use device for strategy media
1993 // 6: the strategy DTMF is active on the output:
1994 // use device for strategy DTMF
1995 if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1996 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1997 } else if (isInCall() ||
1998 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1999 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2000 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
2001 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2002 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
2003 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2004 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
2005 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2006 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
2007 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2010 ALOGV("getNewDevice() selected device %x", device);
2014 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2015 return (uint32_t)getStrategy(stream);
2018 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2019 audio_devices_t devices;
2020 // By checking the range of stream before calling getStrategy, we avoid
2021 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2022 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2023 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2024 devices = AUDIO_DEVICE_NONE;
2026 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2027 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2032 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2033 AudioSystem::stream_type stream) {
2034 // stream to strategy mapping
2036 case AudioSystem::VOICE_CALL:
2037 case AudioSystem::BLUETOOTH_SCO:
2038 return STRATEGY_PHONE;
2039 case AudioSystem::RING:
2040 case AudioSystem::ALARM:
2041 return STRATEGY_SONIFICATION;
2042 case AudioSystem::NOTIFICATION:
2043 return STRATEGY_SONIFICATION_RESPECTFUL;
2044 case AudioSystem::DTMF:
2045 return STRATEGY_DTMF;
2047 ALOGE("unknown stream type");
2048 case AudioSystem::SYSTEM:
2049 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2050 // while key clicks are played produces a poor result
2051 case AudioSystem::TTS:
2052 case AudioSystem::MUSIC:
2053 return STRATEGY_MEDIA;
2054 case AudioSystem::ENFORCED_AUDIBLE:
2055 return STRATEGY_ENFORCED_AUDIBLE;
2059 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2061 case AudioSystem::MUSIC:
2062 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2063 updateDevicesAndOutputs();
2070 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2073 uint32_t device = AUDIO_DEVICE_NONE;
2076 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2077 strategy, mDeviceForStrategy[strategy]);
2078 return mDeviceForStrategy[strategy];
2083 case STRATEGY_SONIFICATION_RESPECTFUL:
2085 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2086 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2087 // while media is playing (or has recently played), use the same device
2088 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2090 // when media is not playing anymore, fall back on the sonification behavior
2091 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2098 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2099 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2102 // when in call, DTMF and PHONE strategies follow the same rules
2105 case STRATEGY_PHONE:
2106 // for phone strategy, we first consider the forced use and then the available devices by order
2108 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2109 case AudioSystem::FORCE_BT_SCO:
2110 if (!isInCall() || strategy != STRATEGY_DTMF) {
2111 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2114 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2116 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2118 // if SCO device is requested but no SCO device is available, fall back to default case
2121 default: // FORCE_NONE
2122 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2123 if (mHasA2dp && !isInCall() &&
2124 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2125 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2126 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2128 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2131 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2133 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2135 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2136 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2138 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2140 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2142 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2144 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2147 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2149 device = mDefaultOutputDevice;
2150 if (device == AUDIO_DEVICE_NONE) {
2151 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2155 case AudioSystem::FORCE_SPEAKER:
2156 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2157 // A2DP speaker when forcing to speaker output
2158 if (mHasA2dp && !isInCall() &&
2159 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2160 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2161 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2164 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2165 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2167 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2169 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2171 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2173 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2176 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2178 device = mDefaultOutputDevice;
2179 if (device == AUDIO_DEVICE_NONE) {
2180 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2186 case STRATEGY_SONIFICATION:
2188 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2189 // handleIncallSonification().
2191 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2196 case STRATEGY_ENFORCED_AUDIBLE:
2197 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2199 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2200 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2202 if ((strategy == STRATEGY_SONIFICATION) ||
2203 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2204 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2205 if (device == AUDIO_DEVICE_NONE) {
2206 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2209 // The second device used for sonification is the same as the device used by media strategy
2212 case STRATEGY_MEDIA: {
2213 uint32_t device2 = AUDIO_DEVICE_NONE;
2214 if (strategy != STRATEGY_SONIFICATION) {
2215 // no sonification on remote submix (e.g. WFD)
2216 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2218 if ((device2 == AUDIO_DEVICE_NONE) &&
2219 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2220 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2221 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2222 if (device2 == AUDIO_DEVICE_NONE) {
2223 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2225 if (device2 == AUDIO_DEVICE_NONE) {
2226 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2229 if (device2 == AUDIO_DEVICE_NONE) {
2230 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2232 if (device2 == AUDIO_DEVICE_NONE) {
2233 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2235 if (device2 == AUDIO_DEVICE_NONE) {
2236 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2238 if (device2 == AUDIO_DEVICE_NONE) {
2239 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2241 if (device2 == AUDIO_DEVICE_NONE) {
2242 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2244 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2245 // no sonification on aux digital (e.g. HDMI)
2246 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2248 if ((device2 == AUDIO_DEVICE_NONE) &&
2249 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2250 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2252 if (device2 == AUDIO_DEVICE_NONE) {
2253 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2256 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2257 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2260 device = mDefaultOutputDevice;
2261 if (device == AUDIO_DEVICE_NONE) {
2262 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2267 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2271 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2275 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2277 for (int i = 0; i < NUM_STRATEGIES; i++) {
2278 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2280 mPreviousOutputs = mOutputs;
2283 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2284 audio_devices_t prevDevice,
2287 // mute/unmute strategies using an incompatible device combination
2288 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2289 // if unmuting, unmute only after the specified delay
2290 if (outputDesc->isDuplicated()) {
2294 uint32_t muteWaitMs = 0;
2295 audio_devices_t device = outputDesc->device();
2296 bool shouldMute = (outputDesc->refCount() != 0) &&
2297 (AudioSystem::popCount(device) >= 2);
2298 // temporary mute output if device selection changes to avoid volume bursts due to
2299 // different per device volumes
2300 bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
2302 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2303 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2304 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2305 bool doMute = false;
2307 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2309 outputDesc->mStrategyMutedByDevice[i] = true;
2310 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2312 outputDesc->mStrategyMutedByDevice[i] = false;
2314 if (doMute || tempMute) {
2315 for (size_t j = 0; j < mOutputs.size(); j++) {
2316 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2317 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2318 == AUDIO_DEVICE_NONE) {
2321 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2322 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2323 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2324 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2325 if (desc->strategyRefCount((routing_strategy)i) != 0) {
2327 setStrategyMute((routing_strategy)i, true, curOutput);
2328 setStrategyMute((routing_strategy)i, false, curOutput,
2329 desc->latency() * 2, device);
2331 if (tempMute || mute) {
2332 if (muteWaitMs < desc->latency()) {
2333 muteWaitMs = desc->latency();
2341 // FIXME: should not need to double latency if volume could be applied immediately by the
2342 // audioflinger mixer. We must account for the delay between now and the next time
2343 // the audioflinger thread for this output will process a buffer (which corresponds to
2344 // one buffer size, usually 1/2 or 1/4 of the latency).
2346 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2347 if (muteWaitMs > delayMs) {
2348 muteWaitMs -= delayMs;
2349 usleep(muteWaitMs * 1000);
2355 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2356 audio_devices_t device,
2360 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2361 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2362 AudioParameter param;
2363 uint32_t muteWaitMs = 0;
2365 if (outputDesc->isDuplicated()) {
2366 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2367 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2370 // filter devices according to output selected
2371 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2373 audio_devices_t prevDevice = outputDesc->mDevice;
2375 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2377 if (device != AUDIO_DEVICE_NONE) {
2378 outputDesc->mDevice = device;
2380 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2382 // Do not change the routing if:
2383 // - the requested device is AUDIO_DEVICE_NONE
2384 // - the requested device is the same as current device and force is not specified.
2385 // Doing this check here allows the caller to call setOutputDevice() without conditions
2386 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2387 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2391 ALOGV("setOutputDevice() changing device");
2393 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2394 mpClientInterface->setParameters(output, param.toString(), delayMs);
2396 // update stream volumes according to new device
2397 applyStreamVolumes(output, device, delayMs);
2402 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2403 uint32_t samplingRate,
2405 uint32_t channelMask)
2407 // Choose an input profile based on the requested capture parameters: select the first available
2408 // profile supporting all requested parameters.
2410 for (size_t i = 0; i < mHwModules.size(); i++)
2412 if (mHwModules[i]->mHandle == 0) {
2415 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2417 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2418 if (profile->isCompatibleProfile(device, samplingRate, format,
2419 channelMask,(audio_output_flags_t)0)) {
2427 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2429 uint32_t device = AUDIO_DEVICE_NONE;
2431 switch(inputSource) {
2432 case AUDIO_SOURCE_DEFAULT:
2433 case AUDIO_SOURCE_MIC:
2434 case AUDIO_SOURCE_VOICE_RECOGNITION:
2435 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2436 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2437 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2438 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2439 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2440 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2441 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2442 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2445 case AUDIO_SOURCE_CAMCORDER:
2446 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2447 device = AUDIO_DEVICE_IN_BACK_MIC;
2448 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2449 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2452 case AUDIO_SOURCE_VOICE_UPLINK:
2453 case AUDIO_SOURCE_VOICE_DOWNLINK:
2454 case AUDIO_SOURCE_VOICE_CALL:
2455 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2456 device = AUDIO_DEVICE_IN_VOICE_CALL;
2459 case AUDIO_SOURCE_REMOTE_SUBMIX:
2460 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2461 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2465 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2468 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2472 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2474 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2475 device &= ~AUDIO_DEVICE_BIT_IN;
2476 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2482 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2484 for (size_t i = 0; i < mInputs.size(); i++) {
2485 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2486 if ((input_descriptor->mRefCount > 0)
2487 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2488 return mInputs.keyAt(i);
2495 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2497 if (device == AUDIO_DEVICE_NONE) {
2498 // this happens when forcing a route update and no track is active on an output.
2499 // In this case the returned category is not important.
2500 device = AUDIO_DEVICE_OUT_SPEAKER;
2501 } else if (AudioSystem::popCount(device) > 1) {
2502 // Multiple device selection is either:
2503 // - speaker + one other device: give priority to speaker in this case.
2504 // - one A2DP device + another device: happens with duplicated output. In this case
2505 // retain the device on the A2DP output as the other must not correspond to an active
2506 // selection if not the speaker.
2507 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2508 device = AUDIO_DEVICE_OUT_SPEAKER;
2510 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2514 ALOGW_IF(AudioSystem::popCount(device) != 1,
2515 "getDeviceForVolume() invalid device combination: %08x",
2521 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2523 switch(getDeviceForVolume(device)) {
2524 case AUDIO_DEVICE_OUT_EARPIECE:
2525 return DEVICE_CATEGORY_EARPIECE;
2526 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2527 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2528 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2529 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2530 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2531 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2532 return DEVICE_CATEGORY_HEADSET;
2533 case AUDIO_DEVICE_OUT_SPEAKER:
2534 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2535 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2536 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2537 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2538 case AUDIO_DEVICE_OUT_USB_DEVICE:
2539 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
2541 return DEVICE_CATEGORY_SPEAKER;
2545 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2548 device_category deviceCategory = getDeviceCategory(device);
2549 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2551 // the volume index in the UI is relative to the min and max volume indices for this stream type
2552 int nbSteps = 1 + curve[VOLMAX].mIndex -
2553 curve[VOLMIN].mIndex;
2554 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2555 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2557 // find what part of the curve this index volume belongs to, or if it's out of bounds
2559 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2561 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2563 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2565 } else if (volIdx <= curve[VOLMAX].mIndex) {
2567 } else { // out of bounds
2571 // linear interpolation in the attenuation table in dB
2572 float decibels = curve[segment].mDBAttenuation +
2573 ((float)(volIdx - curve[segment].mIndex)) *
2574 ( (curve[segment+1].mDBAttenuation -
2575 curve[segment].mDBAttenuation) /
2576 ((float)(curve[segment+1].mIndex -
2577 curve[segment].mIndex)) );
2579 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2581 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2582 curve[segment].mIndex, volIdx,
2583 curve[segment+1].mIndex,
2584 curve[segment].mDBAttenuation,
2586 curve[segment+1].mDBAttenuation,
2589 return amplification;
2592 const AudioPolicyManagerBase::VolumeCurvePoint
2593 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2594 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2597 const AudioPolicyManagerBase::VolumeCurvePoint
2598 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2599 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2602 const AudioPolicyManagerBase::VolumeCurvePoint
2603 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2604 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2607 const AudioPolicyManagerBase::VolumeCurvePoint
2608 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2609 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2612 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2613 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2614 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2615 const AudioPolicyManagerBase::VolumeCurvePoint
2616 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2617 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2620 const AudioPolicyManagerBase::VolumeCurvePoint
2621 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2622 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2625 const AudioPolicyManagerBase::VolumeCurvePoint
2626 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2627 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
2630 const AudioPolicyManagerBase::VolumeCurvePoint
2631 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2632 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
2635 const AudioPolicyManagerBase::VolumeCurvePoint
2636 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2637 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2638 { // AUDIO_STREAM_VOICE_CALL
2639 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2640 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2641 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2643 { // AUDIO_STREAM_SYSTEM
2644 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2645 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2646 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2648 { // AUDIO_STREAM_RING
2649 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2650 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2651 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2653 { // AUDIO_STREAM_MUSIC
2654 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2655 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2656 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2658 { // AUDIO_STREAM_ALARM
2659 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2660 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2661 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2663 { // AUDIO_STREAM_NOTIFICATION
2664 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2665 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2666 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2668 { // AUDIO_STREAM_BLUETOOTH_SCO
2669 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2670 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2671 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2673 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2674 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2675 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2676 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2678 { // AUDIO_STREAM_DTMF
2679 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2680 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2681 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2683 { // AUDIO_STREAM_TTS
2684 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2685 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2686 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2690 void AudioPolicyManagerBase::initializeVolumeCurves()
2692 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2693 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2694 mStreams[i].mVolumeCurve[j] =
2695 sVolumeProfiles[i][j];
2700 float AudioPolicyManagerBase::computeVolume(int stream,
2702 audio_io_handle_t output,
2703 audio_devices_t device)
2706 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2707 StreamDescriptor &streamDesc = mStreams[stream];
2709 if (device == AUDIO_DEVICE_NONE) {
2710 device = outputDesc->device();
2713 // if volume is not 0 (not muted), force media volume to max on digital output
2714 if (stream == AudioSystem::MUSIC &&
2715 index != mStreams[stream].mIndexMin &&
2716 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2717 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2718 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2719 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2723 volume = volIndexToAmpl(device, streamDesc, index);
2725 // if a headset is connected, apply the following rules to ring tones and notifications
2726 // to avoid sound level bursts in user's ears:
2727 // - always attenuate ring tones and notifications volume by 6dB
2728 // - if music is playing, always limit the volume to current music volume,
2729 // with a minimum threshold at -36dB so that notification is always perceived.
2730 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2731 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
2732 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2733 AUDIO_DEVICE_OUT_WIRED_HEADSET |
2734 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
2735 ((stream_strategy == STRATEGY_SONIFICATION)
2736 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2737 || (stream == AudioSystem::SYSTEM)
2738 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
2739 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
2740 streamDesc.mCanBeMuted) {
2741 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2742 // when the phone is ringing we must consider that music could have been paused just before
2743 // by the music application and behave as if music was active if the last music track was
2745 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2746 mLimitRingtoneVolume) {
2747 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
2748 float musicVol = computeVolume(AudioSystem::MUSIC,
2749 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
2752 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2753 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2754 if (volume > minVol) {
2756 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2764 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2766 audio_io_handle_t output,
2767 audio_devices_t device,
2772 // do not change actual stream volume if the stream is muted
2773 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2774 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2775 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2779 // do not change in call volume if bluetooth is connected and vice versa
2780 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2781 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2782 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2783 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2784 return INVALID_OPERATION;
2787 float volume = computeVolume(stream, index, output, device);
2788 // We actually change the volume if:
2789 // - the float value returned by computeVolume() changed
2790 // - the force flag is set
2791 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2793 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2794 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2795 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2797 if (stream == AudioSystem::BLUETOOTH_SCO) {
2798 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2800 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2803 if (stream == AudioSystem::VOICE_CALL ||
2804 stream == AudioSystem::BLUETOOTH_SCO) {
2806 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2807 if (stream == AudioSystem::VOICE_CALL) {
2808 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2813 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2814 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2815 mLastVoiceVolume = voiceVolume;
2822 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2823 audio_devices_t device,
2827 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2829 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2830 checkAndSetVolume(stream,
2831 mStreams[stream].getVolumeIndex(device),
2839 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2841 audio_io_handle_t output,
2843 audio_devices_t device)
2845 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2846 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2847 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2848 setStreamMute(stream, on, output, delayMs, device);
2853 void AudioPolicyManagerBase::setStreamMute(int stream,
2855 audio_io_handle_t output,
2857 audio_devices_t device)
2859 StreamDescriptor &streamDesc = mStreams[stream];
2860 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2861 if (device == AUDIO_DEVICE_NONE) {
2862 device = outputDesc->device();
2865 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
2866 stream, on, output, outputDesc->mMuteCount[stream], device);
2869 if (outputDesc->mMuteCount[stream] == 0) {
2870 if (streamDesc.mCanBeMuted &&
2871 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
2872 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
2873 checkAndSetVolume(stream, 0, output, device, delayMs);
2876 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2877 outputDesc->mMuteCount[stream]++;
2879 if (outputDesc->mMuteCount[stream] == 0) {
2880 ALOGV("setStreamMute() unmuting non muted stream!");
2883 if (--outputDesc->mMuteCount[stream] == 0) {
2884 checkAndSetVolume(stream,
2885 streamDesc.getVolumeIndex(device),
2893 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2895 // if the stream pertains to sonification strategy and we are in call we must
2896 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2897 // in the device used for phone strategy and play the tone if the selected device does not
2898 // interfere with the device used for phone strategy
2899 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2900 // many times as there are active tracks on the output
2901 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2902 if ((stream_strategy == STRATEGY_SONIFICATION) ||
2903 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2904 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2905 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2906 stream, starting, outputDesc->mDevice, stateChange);
2907 if (outputDesc->mRefCount[stream]) {
2910 muteCount = outputDesc->mRefCount[stream];
2912 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2913 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2914 for (int i = 0; i < muteCount; i++) {
2915 setStreamMute(stream, starting, mPrimaryOutput);
2918 ALOGV("handleIncallSonification() high visibility");
2919 if (outputDesc->device() &
2920 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2921 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2922 for (int i = 0; i < muteCount; i++) {
2923 setStreamMute(stream, starting, mPrimaryOutput);
2927 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2929 mpClientInterface->stopTone();
2936 bool AudioPolicyManagerBase::isInCall()
2938 return isStateInCall(mPhoneState);
2941 bool AudioPolicyManagerBase::isStateInCall(int state) {
2942 return ((state == AudioSystem::MODE_IN_CALL) ||
2943 (state == AudioSystem::MODE_IN_COMMUNICATION));
2946 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
2947 uint32_t samplingRate,
2948 audio_format_t format,
2949 audio_channel_mask_t channelMask,
2950 audio_output_flags_t flags,
2951 audio_devices_t device)
2953 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2954 (format != 0 && !AudioSystem::isLinearPCM(format)));
2957 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2959 return MAX_EFFECTS_CPU_LOAD;
2962 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2964 return MAX_EFFECTS_MEMORY;
2967 // --- AudioOutputDescriptor class implementation
2969 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2970 const IOProfile *profile)
2971 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
2972 mChannelMask((audio_channel_mask_t)0), mLatency(0),
2973 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
2974 mOutput1(0), mOutput2(0), mProfile(profile)
2976 // clear usage count for all stream types
2977 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2979 mCurVolume[i] = -1.0;
2983 for (int i = 0; i < NUM_STRATEGIES; i++) {
2984 mStrategyMutedByDevice[i] = false;
2986 if (profile != NULL) {
2987 mSamplingRate = profile->mSamplingRates[0];
2988 mFormat = profile->mFormats[0];
2989 mChannelMask = profile->mChannelMasks[0];
2990 mFlags = profile->mFlags;
2994 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2996 if (isDuplicated()) {
2997 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3003 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3005 if (isDuplicated()) {
3006 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3012 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3013 const AudioOutputDescriptor *outputDesc)
3015 if (isDuplicated()) {
3016 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3017 } else if (outputDesc->isDuplicated()){
3018 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3020 return (mProfile->mModule == outputDesc->mProfile->mModule);
3024 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3026 // forward usage count change to attached outputs
3027 if (isDuplicated()) {
3028 mOutput1->changeRefCount(stream, delta);
3029 mOutput2->changeRefCount(stream, delta);
3031 if ((delta + (int)mRefCount[stream]) < 0) {
3032 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3033 mRefCount[stream] = 0;
3036 mRefCount[stream] += delta;
3037 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3040 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
3042 uint32_t refcount = 0;
3043 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
3044 refcount += mRefCount[i];
3049 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
3051 uint32_t refCount = 0;
3052 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
3053 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
3054 refCount += mRefCount[i];
3060 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3062 if (isDuplicated()) {
3063 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3065 return mProfile->mSupportedDevices ;
3069 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3071 nsecs_t sysTime = systemTime();
3072 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3073 if (mRefCount[i] != 0 ||
3074 ns2ms(sysTime - mStopTime[i]) < inPastMs) {
3081 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3083 const size_t SIZE = 256;
3087 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3088 result.append(buffer);
3089 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3090 result.append(buffer);
3091 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3092 result.append(buffer);
3093 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3094 result.append(buffer);
3095 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3096 result.append(buffer);
3097 snprintf(buffer, SIZE, " Devices %08x\n", device());
3098 result.append(buffer);
3099 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3100 result.append(buffer);
3101 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3102 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3103 result.append(buffer);
3105 write(fd, result.string(), result.size());
3110 // --- AudioInputDescriptor class implementation
3112 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3113 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3114 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3115 mInputSource(0), mProfile(profile)
3119 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3121 const size_t SIZE = 256;
3125 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3126 result.append(buffer);
3127 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3128 result.append(buffer);
3129 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3130 result.append(buffer);
3131 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3132 result.append(buffer);
3133 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3134 result.append(buffer);
3135 write(fd, result.string(), result.size());
3140 // --- StreamDescriptor class implementation
3142 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3143 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3145 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3148 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3150 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3151 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3152 if (mIndexCur.indexOfKey(device) < 0) {
3153 device = AUDIO_DEVICE_OUT_DEFAULT;
3155 return mIndexCur.valueFor(device);
3158 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3160 const size_t SIZE = 256;
3164 snprintf(buffer, SIZE, "%s %02d %02d ",
3165 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3166 result.append(buffer);
3167 for (size_t i = 0; i < mIndexCur.size(); i++) {
3168 snprintf(buffer, SIZE, "%04x : %02d, ",
3170 mIndexCur.valueAt(i));
3171 result.append(buffer);
3173 result.append("\n");
3175 write(fd, result.string(), result.size());
3178 // --- EffectDescriptor class implementation
3180 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3182 const size_t SIZE = 256;
3186 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3187 result.append(buffer);
3188 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3189 result.append(buffer);
3190 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3191 result.append(buffer);
3192 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3193 result.append(buffer);
3194 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3195 result.append(buffer);
3196 write(fd, result.string(), result.size());
3201 // --- IOProfile class implementation
3203 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3204 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3208 AudioPolicyManagerBase::HwModule::~HwModule()
3210 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3211 delete mOutputProfiles[i];
3213 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3214 delete mInputProfiles[i];
3216 free((void *)mName);
3219 void AudioPolicyManagerBase::HwModule::dump(int fd)
3221 const size_t SIZE = 256;
3225 snprintf(buffer, SIZE, " - name: %s\n", mName);
3226 result.append(buffer);
3227 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3228 result.append(buffer);
3229 write(fd, result.string(), result.size());
3230 if (mOutputProfiles.size()) {
3231 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3232 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3233 snprintf(buffer, SIZE, " output %d:\n", i);
3234 write(fd, buffer, strlen(buffer));
3235 mOutputProfiles[i]->dump(fd);
3238 if (mInputProfiles.size()) {
3239 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3240 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3241 snprintf(buffer, SIZE, " input %d:\n", i);
3242 write(fd, buffer, strlen(buffer));
3243 mInputProfiles[i]->dump(fd);
3248 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3249 : mFlags((audio_output_flags_t)0), mModule(module)
3253 AudioPolicyManagerBase::IOProfile::~IOProfile()
3257 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3258 // means a parameter is don't care
3259 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3260 uint32_t samplingRate,
3262 uint32_t channelMask,
3263 audio_output_flags_t flags) const
3265 if ((mSupportedDevices & device) != device) {
3268 if ((mFlags & flags) != flags) {
3271 if (samplingRate != 0) {
3273 for (i = 0; i < mSamplingRates.size(); i++)
3275 if (mSamplingRates[i] == samplingRate) {
3279 if (i == mSamplingRates.size()) {
3285 for (i = 0; i < mFormats.size(); i++)
3287 if (mFormats[i] == format) {
3291 if (i == mFormats.size()) {
3295 if (channelMask != 0) {
3297 for (i = 0; i < mChannelMasks.size(); i++)
3299 if (mChannelMasks[i] == channelMask) {
3303 if (i == mChannelMasks.size()) {
3310 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3312 const size_t SIZE = 256;
3316 snprintf(buffer, SIZE, " - sampling rates: ");
3317 result.append(buffer);
3318 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3319 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3320 result.append(buffer);
3321 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3324 snprintf(buffer, SIZE, " - channel masks: ");
3325 result.append(buffer);
3326 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3327 snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3328 result.append(buffer);
3329 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3332 snprintf(buffer, SIZE, " - formats: ");
3333 result.append(buffer);
3334 for (size_t i = 0; i < mFormats.size(); i++) {
3335 snprintf(buffer, SIZE, "%d", mFormats[i]);
3336 result.append(buffer);
3337 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3340 snprintf(buffer, SIZE, " - devices: %04x\n", mSupportedDevices);
3341 result.append(buffer);
3342 snprintf(buffer, SIZE, " - flags: %04x\n", mFlags);
3343 result.append(buffer);
3345 write(fd, result.string(), result.size());
3348 // --- audio_policy.conf file parsing
3350 struct StringToEnum {
3355 #define STRING_TO_ENUM(string) { #string, string }
3356 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3358 const struct StringToEnum sDeviceNameToEnumTable[] = {
3359 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3360 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3361 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3362 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3363 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3364 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3365 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3366 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3367 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3368 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3369 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3370 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3371 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3372 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3373 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3374 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3375 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3376 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3377 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3378 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3379 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3380 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3381 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3384 const struct StringToEnum sFlagNameToEnumTable[] = {
3385 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3386 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3387 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3388 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3391 const struct StringToEnum sFormatNameToEnumTable[] = {
3392 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3393 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3394 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3395 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3396 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3399 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3400 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3401 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3402 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3403 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3406 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3407 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3408 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3412 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3416 for (size_t i = 0; i < size; i++) {
3417 if (strcmp(table[i].name, name) == 0) {
3418 ALOGV("stringToEnum() found %s", table[i].name);
3419 return table[i].value;
3425 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3429 // it is OK to cast name to non const here as we are not going to use it after
3430 // strtok() modifies it
3431 char *flagName = strtok(name, "|");
3432 while (flagName != NULL) {
3433 if (strlen(flagName) != 0) {
3434 flag |= stringToEnum(sFlagNameToEnumTable,
3435 ARRAY_SIZE(sFlagNameToEnumTable),
3438 flagName = strtok(NULL, "|");
3440 return (audio_output_flags_t)flag;
3443 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3445 uint32_t device = 0;
3447 char *devName = strtok(name, "|");
3448 while (devName != NULL) {
3449 if (strlen(devName) != 0) {
3450 device |= stringToEnum(sDeviceNameToEnumTable,
3451 ARRAY_SIZE(sDeviceNameToEnumTable),
3454 devName = strtok(NULL, "|");
3459 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3461 char *str = strtok(name, "|");
3463 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3464 // rates should be read from the output stream after it is opened for the first time
3465 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3466 profile->mSamplingRates.add(0);
3470 while (str != NULL) {
3471 uint32_t rate = atoi(str);
3473 ALOGV("loadSamplingRates() adding rate %d", rate);
3474 profile->mSamplingRates.add(rate);
3476 str = strtok(NULL, "|");
3481 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3483 char *str = strtok(name, "|");
3485 // by convention, "0' in the first entry in mFormats indicates the supported formats
3486 // should be read from the output stream after it is opened for the first time
3487 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3488 profile->mFormats.add((audio_format_t)0);
3492 while (str != NULL) {
3493 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3494 ARRAY_SIZE(sFormatNameToEnumTable),
3497 profile->mFormats.add(format);
3499 str = strtok(NULL, "|");
3504 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3506 const char *str = strtok(name, "|");
3508 ALOGV("loadInChannels() %s", name);
3510 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3511 profile->mChannelMasks.add((audio_channel_mask_t)0);
3515 while (str != NULL) {
3516 audio_channel_mask_t channelMask =
3517 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3518 ARRAY_SIZE(sInChannelsNameToEnumTable),
3520 if (channelMask != 0) {
3521 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3522 profile->mChannelMasks.add(channelMask);
3524 str = strtok(NULL, "|");
3529 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3531 const char *str = strtok(name, "|");
3533 ALOGV("loadOutChannels() %s", name);
3535 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3536 // masks should be read from the output stream after it is opened for the first time
3537 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3538 profile->mChannelMasks.add((audio_channel_mask_t)0);
3542 while (str != NULL) {
3543 audio_channel_mask_t channelMask =
3544 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3545 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3547 if (channelMask != 0) {
3548 profile->mChannelMasks.add(channelMask);
3550 str = strtok(NULL, "|");
3555 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3557 cnode *node = root->first_child;
3559 IOProfile *profile = new IOProfile(module);
3562 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3563 loadSamplingRates((char *)node->value, profile);
3564 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3565 loadFormats((char *)node->value, profile);
3566 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3567 loadInChannels((char *)node->value, profile);
3568 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3569 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3573 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3574 "loadInput() invalid supported devices");
3575 ALOGW_IF(profile->mChannelMasks.size() == 0,
3576 "loadInput() invalid supported channel masks");
3577 ALOGW_IF(profile->mSamplingRates.size() == 0,
3578 "loadInput() invalid supported sampling rates");
3579 ALOGW_IF(profile->mFormats.size() == 0,
3580 "loadInput() invalid supported formats");
3581 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3582 (profile->mChannelMasks.size() != 0) &&
3583 (profile->mSamplingRates.size() != 0) &&
3584 (profile->mFormats.size() != 0)) {
3586 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3588 module->mInputProfiles.add(profile);
3596 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3598 cnode *node = root->first_child;
3600 IOProfile *profile = new IOProfile(module);
3603 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3604 loadSamplingRates((char *)node->value, profile);
3605 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3606 loadFormats((char *)node->value, profile);
3607 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3608 loadOutChannels((char *)node->value, profile);
3609 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3610 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3611 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3612 profile->mFlags = parseFlagNames((char *)node->value);
3616 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3617 "loadOutput() invalid supported devices");
3618 ALOGW_IF(profile->mChannelMasks.size() == 0,
3619 "loadOutput() invalid supported channel masks");
3620 ALOGW_IF(profile->mSamplingRates.size() == 0,
3621 "loadOutput() invalid supported sampling rates");
3622 ALOGW_IF(profile->mFormats.size() == 0,
3623 "loadOutput() invalid supported formats");
3624 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3625 (profile->mChannelMasks.size() != 0) &&
3626 (profile->mSamplingRates.size() != 0) &&
3627 (profile->mFormats.size() != 0)) {
3629 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3630 profile->mSupportedDevices, profile->mFlags);
3632 module->mOutputProfiles.add(profile);
3640 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3642 cnode *node = config_find(root, OUTPUTS_TAG);
3643 status_t status = NAME_NOT_FOUND;
3645 HwModule *module = new HwModule(root->name);
3648 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3650 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3652 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
3653 mHasRemoteSubmix = true;
3656 node = node->first_child;
3658 ALOGV("loadHwModule() loading output %s", node->name);
3659 status_t tmpStatus = loadOutput(node, module);
3660 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3666 node = config_find(root, INPUTS_TAG);
3668 node = node->first_child;
3670 ALOGV("loadHwModule() loading input %s", node->name);
3671 status_t tmpStatus = loadInput(node, module);
3672 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3678 if (status == NO_ERROR) {
3679 mHwModules.add(module);
3685 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3687 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3692 node = node->first_child;
3694 ALOGV("loadHwModules() loading module %s", node->name);
3700 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3702 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3706 node = node->first_child;
3708 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3709 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3710 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
3711 "loadGlobalConfig() no attached output devices");
3712 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3713 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3714 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3715 ARRAY_SIZE(sDeviceNameToEnumTable),
3716 (char *)node->value);
3717 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
3718 "loadGlobalConfig() default device not specified");
3719 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3720 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3721 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
3722 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3728 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3733 data = (char *)load_file(path, NULL);
3737 root = config_node("", "");
3738 config_load(root, data);
3740 loadGlobalConfig(root);
3741 loadHwModules(root);
3747 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3752 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3757 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3758 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3759 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
3761 module = new HwModule("primary");
3763 profile = new IOProfile(module);
3764 profile->mSamplingRates.add(44100);
3765 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3766 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3767 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3768 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3769 module->mOutputProfiles.add(profile);
3771 profile = new IOProfile(module);
3772 profile->mSamplingRates.add(8000);
3773 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3774 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3775 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3776 module->mInputProfiles.add(profile);
3778 mHwModules.add(module);
3781 }; // namespace android