2 * Copyright (C) 2009 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define LOG_TAG "AudioPolicyManagerBase"
18 //#define LOG_NDEBUG 0
20 //#define VERY_VERBOSE_LOGGING
21 #ifdef VERY_VERBOSE_LOGGING
24 #define ALOGVV(a...) do { } while(0)
27 // A device mask for all audio input devices that are considered "virtual" when evaluating
28 // active inputs in getActiveInput()
29 #define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30 // A device mask for all audio output devices that are considered "remote" when evaluating
31 // active output devices in isStreamActiveRemotely()
32 #define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
34 #include <utils/Log.h>
35 #include <hardware_legacy/AudioPolicyManagerBase.h>
36 #include <hardware/audio_effect.h>
37 #include <hardware/audio.h>
39 #include <hardware_legacy/audio_policy_conf.h>
41 namespace android_audio_legacy {
43 // ----------------------------------------------------------------------------
44 // AudioPolicyInterface implementation
45 // ----------------------------------------------------------------------------
48 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
49 AudioSystem::device_connection_state state,
50 const char *device_address)
52 SortedVector <audio_io_handle_t> outputs;
54 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
56 // connect/disconnect only 1 device at a time
57 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
59 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
60 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
64 // handle output devices
65 if (audio_is_output_device(device)) {
67 if (!mHasA2dp && audio_is_a2dp_device(device)) {
68 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
71 if (!mHasUsb && audio_is_usb_device(device)) {
72 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
75 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
76 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
80 // save a copy of the opened output descriptors before any output is opened or closed
81 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
82 mPreviousOutputs = mOutputs;
85 // handle output device connection
86 case AudioSystem::DEVICE_STATE_AVAILABLE:
87 if (mAvailableOutputDevices & device) {
88 ALOGW("setDeviceConnectionState() device already connected: %x", device);
89 return INVALID_OPERATION;
91 ALOGV("setDeviceConnectionState() connecting device %x", device);
93 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
94 return INVALID_OPERATION;
96 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
98 // register new device as available
99 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
101 if (!outputs.isEmpty()) {
103 if (mHasA2dp && audio_is_a2dp_device(device)) {
104 // handle A2DP device connection
105 AudioParameter param;
106 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
107 paramStr = param.toString();
108 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
109 mA2dpSuspended = false;
110 } else if (audio_is_bluetooth_sco_device(device)) {
111 // handle SCO device connection
112 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
113 } else if (mHasUsb && audio_is_usb_device(device)) {
114 // handle USB device connection
115 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
116 paramStr = mUsbCardAndDevice;
118 // not currently handling multiple simultaneous submixes: ignoring remote submix
120 if (!paramStr.isEmpty()) {
121 for (size_t i = 0; i < outputs.size(); i++) {
122 mpClientInterface->setParameters(outputs[i], paramStr);
127 // handle output device disconnection
128 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
129 if (!(mAvailableOutputDevices & device)) {
130 ALOGW("setDeviceConnectionState() device not connected: %x", device);
131 return INVALID_OPERATION;
134 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
135 // remove device from available output devices
136 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
138 checkOutputsForDevice(device, state, outputs);
139 if (mHasA2dp && audio_is_a2dp_device(device)) {
140 // handle A2DP device disconnection
141 mA2dpDeviceAddress = "";
142 mA2dpSuspended = false;
143 } else if (audio_is_bluetooth_sco_device(device)) {
144 // handle SCO device disconnection
145 mScoDeviceAddress = "";
146 } else if (mHasUsb && audio_is_usb_device(device)) {
147 // handle USB device disconnection
148 mUsbCardAndDevice = "";
150 // not currently handling multiple simultaneous submixes: ignoring remote submix
155 ALOGE("setDeviceConnectionState() invalid state: %x", state);
160 checkOutputForAllStrategies();
161 // outputs must be closed after checkOutputForAllStrategies() is executed
162 if (!outputs.isEmpty()) {
163 for (size_t i = 0; i < outputs.size(); i++) {
164 // close unused outputs after device disconnection or direct outputs that have been
165 // opened by checkOutputsForDevice() to query dynamic parameters
166 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
167 (mOutputs.valueFor(outputs[i])->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
168 closeOutput(outputs[i]);
173 updateDevicesAndOutputs();
174 for (size_t i = 0; i < mOutputs.size(); i++) {
175 // do not force device change on duplicated output because if device is 0, it will
176 // also force a device 0 for the two outputs it is duplicated to which may override
177 // a valid device selection on those outputs.
178 setOutputDevice(mOutputs.keyAt(i),
179 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
180 !mOutputs.valueAt(i)->isDuplicated(),
184 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
185 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
186 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
187 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
188 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
189 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
194 // handle input devices
195 if (audio_is_input_device(device)) {
199 // handle input device connection
200 case AudioSystem::DEVICE_STATE_AVAILABLE: {
201 if (mAvailableInputDevices & device) {
202 ALOGW("setDeviceConnectionState() device already connected: %d", device);
203 return INVALID_OPERATION;
205 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
209 // handle input device disconnection
210 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
211 if (!(mAvailableInputDevices & device)) {
212 ALOGW("setDeviceConnectionState() device not connected: %d", device);
213 return INVALID_OPERATION;
215 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
219 ALOGE("setDeviceConnectionState() invalid state: %x", state);
223 audio_io_handle_t activeInput = getActiveInput();
224 if (activeInput != 0) {
225 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
226 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
227 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
228 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
229 inputDesc->mDevice, newDevice, activeInput);
230 inputDesc->mDevice = newDevice;
231 AudioParameter param = AudioParameter();
232 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
233 mpClientInterface->setParameters(activeInput, param.toString());
240 ALOGW("setDeviceConnectionState() invalid device: %x", device);
244 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
245 const char *device_address)
247 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
248 String8 address = String8(device_address);
249 if (audio_is_output_device(device)) {
250 if (device & mAvailableOutputDevices) {
251 if (audio_is_a2dp_device(device) &&
252 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
255 if (audio_is_bluetooth_sco_device(device) &&
256 address != "" && mScoDeviceAddress != address) {
259 if (audio_is_usb_device(device) &&
260 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
261 ALOGE("getDeviceConnectionState() invalid device: %x", device);
264 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
267 state = AudioSystem::DEVICE_STATE_AVAILABLE;
269 } else if (audio_is_input_device(device)) {
270 if (device & mAvailableInputDevices) {
271 state = AudioSystem::DEVICE_STATE_AVAILABLE;
278 void AudioPolicyManagerBase::setPhoneState(int state)
280 ALOGV("setPhoneState() state %d", state);
281 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
282 if (state < 0 || state >= AudioSystem::NUM_MODES) {
283 ALOGW("setPhoneState() invalid state %d", state);
287 if (state == mPhoneState ) {
288 ALOGW("setPhoneState() setting same state %d", state);
292 // if leaving call state, handle special case of active streams
293 // pertaining to sonification strategy see handleIncallSonification()
295 ALOGV("setPhoneState() in call state management: new state is %d", state);
296 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
297 handleIncallSonification(stream, false, true);
301 // store previous phone state for management of sonification strategy below
302 int oldState = mPhoneState;
306 // are we entering or starting a call
307 if (!isStateInCall(oldState) && isStateInCall(state)) {
308 ALOGV(" Entering call in setPhoneState()");
309 // force routing command to audio hardware when starting a call
310 // even if no device change is needed
312 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
313 ALOGV(" Exiting call in setPhoneState()");
314 // force routing command to audio hardware when exiting a call
315 // even if no device change is needed
317 } else if (isStateInCall(state) && (state != oldState)) {
318 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
319 // force routing command to audio hardware when switching between telephony and VoIP
320 // even if no device change is needed
324 // check for device and output changes triggered by new phone state
325 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
327 checkOutputForAllStrategies();
328 updateDevicesAndOutputs();
330 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
332 // force routing command to audio hardware when ending call
333 // even if no device change is needed
334 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
335 newDevice = hwOutputDesc->device();
339 if (isStateInCall(state)) {
340 nsecs_t sysTime = systemTime();
341 for (size_t i = 0; i < mOutputs.size(); i++) {
342 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
343 // mute media and sonification strategies and delay device switch by the largest
344 // latency of any output where either strategy is active.
345 // This avoid sending the ring tone or music tail into the earpiece or headset.
346 if ((desc->isStrategyActive(STRATEGY_MEDIA,
347 SONIFICATION_HEADSET_MUSIC_DELAY,
349 desc->isStrategyActive(STRATEGY_SONIFICATION,
350 SONIFICATION_HEADSET_MUSIC_DELAY,
352 (delayMs < (int)desc->mLatency*2)) {
353 delayMs = desc->mLatency*2;
355 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
356 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
357 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
358 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
359 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
360 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
364 // change routing is necessary
365 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
367 // if entering in call state, handle special case of active streams
368 // pertaining to sonification strategy see handleIncallSonification()
369 if (isStateInCall(state)) {
370 ALOGV("setPhoneState() in call state management: new state is %d", state);
371 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
372 handleIncallSonification(stream, true, true);
376 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
377 if (state == AudioSystem::MODE_RINGTONE &&
378 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
379 mLimitRingtoneVolume = true;
381 mLimitRingtoneVolume = false;
385 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
387 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
389 bool forceVolumeReeval = false;
391 case AudioSystem::FOR_COMMUNICATION:
392 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
393 config != AudioSystem::FORCE_NONE) {
394 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
397 forceVolumeReeval = true;
398 mForceUse[usage] = config;
400 case AudioSystem::FOR_MEDIA:
401 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
402 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
403 config != AudioSystem::FORCE_ANALOG_DOCK &&
404 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
405 config != AudioSystem::FORCE_NO_BT_A2DP) {
406 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
409 mForceUse[usage] = config;
411 case AudioSystem::FOR_RECORD:
412 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
413 config != AudioSystem::FORCE_NONE) {
414 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
417 mForceUse[usage] = config;
419 case AudioSystem::FOR_DOCK:
420 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
421 config != AudioSystem::FORCE_BT_DESK_DOCK &&
422 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
423 config != AudioSystem::FORCE_ANALOG_DOCK &&
424 config != AudioSystem::FORCE_DIGITAL_DOCK) {
425 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
427 forceVolumeReeval = true;
428 mForceUse[usage] = config;
430 case AudioSystem::FOR_SYSTEM:
431 if (config != AudioSystem::FORCE_NONE &&
432 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
433 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
435 forceVolumeReeval = true;
436 mForceUse[usage] = config;
439 ALOGW("setForceUse() invalid usage %d", usage);
443 // check for device and output changes triggered by new force usage
445 checkOutputForAllStrategies();
446 updateDevicesAndOutputs();
447 for (size_t i = 0; i < mOutputs.size(); i++) {
448 audio_io_handle_t output = mOutputs.keyAt(i);
449 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
450 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
451 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
452 applyStreamVolumes(output, newDevice, 0, true);
456 audio_io_handle_t activeInput = getActiveInput();
457 if (activeInput != 0) {
458 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
459 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
460 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
461 ALOGV("setForceUse() changing device from %x to %x for input %d",
462 inputDesc->mDevice, newDevice, activeInput);
463 inputDesc->mDevice = newDevice;
464 AudioParameter param = AudioParameter();
465 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
466 mpClientInterface->setParameters(activeInput, param.toString());
472 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
474 return mForceUse[usage];
477 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
479 ALOGV("setSystemProperty() property %s, value %s", property, value);
482 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
483 audio_devices_t device,
484 uint32_t samplingRate,
486 uint32_t channelMask,
487 audio_output_flags_t flags)
489 for (size_t i = 0; i < mHwModules.size(); i++) {
490 if (mHwModules[i]->mHandle == 0) {
493 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
494 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
495 if (profile->isCompatibleProfile(device, samplingRate, format,
497 AUDIO_OUTPUT_FLAG_DIRECT)) {
498 if (mAvailableOutputDevices & profile->mSupportedDevices) {
499 return mHwModules[i]->mOutputProfiles[j];
507 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
508 uint32_t samplingRate,
510 uint32_t channelMask,
511 AudioSystem::output_flags flags)
513 audio_io_handle_t output = 0;
514 uint32_t latency = 0;
515 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
516 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
517 ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
518 stream, samplingRate, format, channelMask, flags);
520 #ifdef AUDIO_POLICY_TEST
521 if (mCurOutput != 0) {
522 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
523 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
525 if (mTestOutputs[mCurOutput] == 0) {
526 ALOGV("getOutput() opening test output");
527 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
528 outputDesc->mDevice = mTestDevice;
529 outputDesc->mSamplingRate = mTestSamplingRate;
530 outputDesc->mFormat = mTestFormat;
531 outputDesc->mChannelMask = mTestChannels;
532 outputDesc->mLatency = mTestLatencyMs;
533 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
534 outputDesc->mRefCount[stream] = 0;
535 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
536 &outputDesc->mSamplingRate,
537 &outputDesc->mFormat,
538 &outputDesc->mChannelMask,
539 &outputDesc->mLatency,
541 if (mTestOutputs[mCurOutput]) {
542 AudioParameter outputCmd = AudioParameter();
543 outputCmd.addInt(String8("set_id"),mCurOutput);
544 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
545 addOutput(mTestOutputs[mCurOutput], outputDesc);
548 return mTestOutputs[mCurOutput];
550 #endif //AUDIO_POLICY_TEST
552 // open a direct output if required by specified parameters
553 IOProfile *profile = getProfileForDirectOutput(device,
557 (audio_output_flags_t)flags);
558 if (profile != NULL) {
559 AudioOutputDescriptor *outputDesc = NULL;
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
563 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
565 // reuse direct output if currently open and configured with same parameters
566 if ((samplingRate == outputDesc->mSamplingRate) &&
567 (format == outputDesc->mFormat) &&
568 (channelMask == outputDesc->mChannelMask)) {
569 outputDesc->mDirectOpenCount++;
570 ALOGV("getOutput() reusing direct output %d", output);
571 return mOutputs.keyAt(i);
575 // close direct output if currently open and configured with different parameters
576 if (outputDesc != NULL) {
577 closeOutput(outputDesc->mId);
579 outputDesc = new AudioOutputDescriptor(profile);
580 outputDesc->mDevice = device;
581 outputDesc->mSamplingRate = samplingRate;
582 outputDesc->mFormat = (audio_format_t)format;
583 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
584 outputDesc->mLatency = 0;
585 outputDesc->mFlags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);;
586 outputDesc->mRefCount[stream] = 0;
587 outputDesc->mStopTime[stream] = 0;
588 outputDesc->mDirectOpenCount = 1;
589 output = mpClientInterface->openOutput(profile->mModule->mHandle,
590 &outputDesc->mDevice,
591 &outputDesc->mSamplingRate,
592 &outputDesc->mFormat,
593 &outputDesc->mChannelMask,
594 &outputDesc->mLatency,
597 // only accept an output with the requested parameters
599 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
600 (format != 0 && format != outputDesc->mFormat) ||
601 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
602 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
603 "format %d %d, channelMask %04x %04x", output, samplingRate,
604 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
605 outputDesc->mChannelMask);
607 mpClientInterface->closeOutput(output);
612 addOutput(output, outputDesc);
613 mPreviousOutputs = mOutputs;
614 ALOGV("getOutput() returns new direct output %d", output);
618 // ignoring channel mask due to downmix capability in mixer
620 // open a non direct output
622 // get which output is suitable for the specified stream. The actual routing change will happen
623 // when startOutput() will be called
624 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
626 output = selectOutput(outputs, flags);
628 ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
629 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
631 ALOGV("getOutput() returns output %d", output);
636 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
637 AudioSystem::output_flags flags)
639 // select one output among several that provide a path to a particular device or set of
640 // devices (the list was previously build by getOutputsForDevice()).
641 // The priority is as follows:
642 // 1: the output with the highest number of requested policy flags
643 // 2: the primary output
644 // 3: the first output in the list
646 if (outputs.size() == 0) {
649 if (outputs.size() == 1) {
653 int maxCommonFlags = 0;
654 audio_io_handle_t outputFlags = 0;
655 audio_io_handle_t outputPrimary = 0;
657 for (size_t i = 0; i < outputs.size(); i++) {
658 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
659 if (!outputDesc->isDuplicated()) {
660 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
661 if (commonFlags > maxCommonFlags) {
662 outputFlags = outputs[i];
663 maxCommonFlags = commonFlags;
664 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
666 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
667 outputPrimary = outputs[i];
672 if (outputFlags != 0) {
675 if (outputPrimary != 0) {
676 return outputPrimary;
682 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
683 AudioSystem::stream_type stream,
686 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
687 ssize_t index = mOutputs.indexOfKey(output);
689 ALOGW("startOutput() unknow output %d", output);
693 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
695 // increment usage count for this stream on the requested output:
696 // NOTE that the usage count is the same for duplicated output and hardware output which is
697 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
698 outputDesc->changeRefCount(stream, 1);
700 if (outputDesc->mRefCount[stream] == 1) {
701 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
702 routing_strategy strategy = getStrategy(stream);
703 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
704 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
707 for (size_t i = 0; i < mOutputs.size(); i++) {
708 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
709 if (desc != outputDesc) {
710 // force a device change if any other output is managed by the same hw
711 // module and has a current device selection that differs from selected device.
712 // In this case, the audio HAL must receive the new device selection so that it can
713 // change the device currently selected by the other active output.
714 if (outputDesc->sharesHwModuleWith(desc) &&
715 desc->device() != newDevice) {
718 // wait for audio on other active outputs to be presented when starting
719 // a notification so that audio focus effect can propagate.
720 uint32_t latency = desc->latency();
721 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
726 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
728 // handle special case for sonification while in call
730 handleIncallSonification(stream, true, false);
733 // apply volume rules for current stream and device if necessary
734 checkAndSetVolume(stream,
735 mStreams[stream].getVolumeIndex(newDevice),
739 // update the outputs if starting an output with a stream that can affect notification
741 handleNotificationRoutingForStream(stream);
742 if (waitMs > muteWaitMs) {
743 usleep((waitMs - muteWaitMs) * 2 * 1000);
750 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
751 AudioSystem::stream_type stream,
754 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
755 ssize_t index = mOutputs.indexOfKey(output);
757 ALOGW("stopOutput() unknow output %d", output);
761 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
763 // handle special case for sonification while in call
765 handleIncallSonification(stream, false, false);
768 if (outputDesc->mRefCount[stream] > 0) {
769 // decrement usage count of this stream on the output
770 outputDesc->changeRefCount(stream, -1);
771 // store time at which the stream was stopped - see isStreamActive()
772 if (outputDesc->mRefCount[stream] == 0) {
773 outputDesc->mStopTime[stream] = systemTime();
774 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
775 // delay the device switch by twice the latency because stopOutput() is executed when
776 // the track stop() command is received and at that time the audio track buffer can
777 // still contain data that needs to be drained. The latency only covers the audio HAL
778 // and kernel buffers. Also the latency does not always include additional delay in the
779 // audio path (audio DSP, CODEC ...)
780 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
782 // force restoring the device selection on other active outputs if it differs from the
783 // one being selected for this output
784 for (size_t i = 0; i < mOutputs.size(); i++) {
785 audio_io_handle_t curOutput = mOutputs.keyAt(i);
786 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
787 if (curOutput != output &&
789 outputDesc->sharesHwModuleWith(desc) &&
790 newDevice != desc->device()) {
791 setOutputDevice(curOutput,
792 getNewDevice(curOutput, false /*fromCache*/),
794 outputDesc->mLatency*2);
797 // update the outputs if stopping one with a stream that can affect notification routing
798 handleNotificationRoutingForStream(stream);
802 ALOGW("stopOutput() refcount is already 0 for output %d", output);
803 return INVALID_OPERATION;
807 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
809 ALOGV("releaseOutput() %d", output);
810 ssize_t index = mOutputs.indexOfKey(output);
812 ALOGW("releaseOutput() releasing unknown output %d", output);
816 #ifdef AUDIO_POLICY_TEST
817 int testIndex = testOutputIndex(output);
818 if (testIndex != 0) {
819 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
820 if (outputDesc->isActive()) {
821 mpClientInterface->closeOutput(output);
822 delete mOutputs.valueAt(index);
823 mOutputs.removeItem(output);
824 mTestOutputs[testIndex] = 0;
828 #endif //AUDIO_POLICY_TEST
830 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
831 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
832 if (desc->mDirectOpenCount <= 0) {
833 ALOGW("releaseOutput() invalid open count %d for output %d",
834 desc->mDirectOpenCount, output);
837 if (--desc->mDirectOpenCount == 0) {
844 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
845 uint32_t samplingRate,
847 uint32_t channelMask,
848 AudioSystem::audio_in_acoustics acoustics)
850 audio_io_handle_t input = 0;
851 audio_devices_t device = getDeviceForInputSource(inputSource);
853 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
854 inputSource, samplingRate, format, channelMask, acoustics);
856 if (device == AUDIO_DEVICE_NONE) {
857 ALOGW("getInput() could not find device for inputSource %d", inputSource);
861 // adapt channel selection to input source
862 switch(inputSource) {
863 case AUDIO_SOURCE_VOICE_UPLINK:
864 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
866 case AUDIO_SOURCE_VOICE_DOWNLINK:
867 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
869 case AUDIO_SOURCE_VOICE_CALL:
870 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
876 IOProfile *profile = getInputProfile(device,
880 if (profile == NULL) {
881 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
883 device, samplingRate, format, channelMask);
887 if (profile->mModule->mHandle == 0) {
888 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
892 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
894 inputDesc->mInputSource = inputSource;
895 inputDesc->mDevice = device;
896 inputDesc->mSamplingRate = samplingRate;
897 inputDesc->mFormat = (audio_format_t)format;
898 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
899 inputDesc->mRefCount = 0;
900 input = mpClientInterface->openInput(profile->mModule->mHandle,
902 &inputDesc->mSamplingRate,
904 &inputDesc->mChannelMask);
906 // only accept input with the exact requested set of parameters
908 (samplingRate != inputDesc->mSamplingRate) ||
909 (format != inputDesc->mFormat) ||
910 (channelMask != inputDesc->mChannelMask)) {
911 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
912 samplingRate, format, channelMask);
914 mpClientInterface->closeInput(input);
919 mInputs.add(input, inputDesc);
923 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
925 ALOGV("startInput() input %d", input);
926 ssize_t index = mInputs.indexOfKey(input);
928 ALOGW("startInput() unknow input %d", input);
931 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
933 #ifdef AUDIO_POLICY_TEST
935 #endif //AUDIO_POLICY_TEST
937 // refuse 2 active AudioRecord clients at the same time
938 if (getActiveInput() != 0) {
939 ALOGW("startInput() input %d failed: other input already started", input);
940 return INVALID_OPERATION;
944 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
945 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
946 inputDesc->mDevice = newDevice;
948 AudioParameter param = AudioParameter();
949 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
951 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
952 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
954 mpClientInterface->setParameters(input, param.toString());
956 inputDesc->mRefCount = 1;
960 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
962 ALOGV("stopInput() input %d", input);
963 ssize_t index = mInputs.indexOfKey(input);
965 ALOGW("stopInput() unknow input %d", input);
968 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
970 if (inputDesc->mRefCount == 0) {
971 ALOGW("stopInput() input %d already stopped", input);
972 return INVALID_OPERATION;
974 AudioParameter param = AudioParameter();
975 param.addInt(String8(AudioParameter::keyRouting), 0);
976 mpClientInterface->setParameters(input, param.toString());
977 inputDesc->mRefCount = 0;
982 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
984 ALOGV("releaseInput() %d", input);
985 ssize_t index = mInputs.indexOfKey(input);
987 ALOGW("releaseInput() releasing unknown input %d", input);
990 mpClientInterface->closeInput(input);
991 delete mInputs.valueAt(index);
992 mInputs.removeItem(input);
993 ALOGV("releaseInput() exit");
996 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1000 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1001 if (indexMin < 0 || indexMin >= indexMax) {
1002 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1005 mStreams[stream].mIndexMin = indexMin;
1006 mStreams[stream].mIndexMax = indexMax;
1009 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1011 audio_devices_t device)
1014 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1017 if (!audio_is_output_device(device)) {
1021 // Force max volume if stream cannot be muted
1022 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1024 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1025 stream, device, index);
1027 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1028 // clear all device specific values
1029 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1030 mStreams[stream].mIndexCur.clear();
1032 mStreams[stream].mIndexCur.add(device, index);
1034 // compute and apply stream volume on all outputs according to connected device
1035 status_t status = NO_ERROR;
1036 for (size_t i = 0; i < mOutputs.size(); i++) {
1037 audio_devices_t curDevice =
1038 getDeviceForVolume(mOutputs.valueAt(i)->device());
1039 if (device == curDevice) {
1040 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1041 if (volStatus != NO_ERROR) {
1049 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1051 audio_devices_t device)
1053 if (index == NULL) {
1056 if (!audio_is_output_device(device)) {
1059 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1060 // the strategy the stream belongs to.
1061 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1062 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1064 device = getDeviceForVolume(device);
1066 *index = mStreams[stream].getVolumeIndex(device);
1067 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1071 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1073 ALOGV("getOutputForEffect()");
1074 // apply simple rule where global effects are attached to the same output as MUSIC streams
1076 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1077 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1078 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1080 for (size_t i = 0; i < dstOutputs.size(); i++) {
1081 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1082 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1086 return dstOutputs[outIdx];
1089 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1090 audio_io_handle_t io,
1095 ssize_t index = mOutputs.indexOfKey(io);
1097 index = mInputs.indexOfKey(io);
1099 ALOGW("registerEffect() unknown io %d", io);
1100 return INVALID_OPERATION;
1104 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1105 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1106 desc->name, desc->memoryUsage);
1107 return INVALID_OPERATION;
1109 mTotalEffectsMemory += desc->memoryUsage;
1110 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1111 desc->name, io, strategy, session, id);
1112 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1114 EffectDescriptor *pDesc = new EffectDescriptor();
1115 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1117 pDesc->mStrategy = (routing_strategy)strategy;
1118 pDesc->mSession = session;
1119 pDesc->mEnabled = false;
1121 mEffects.add(id, pDesc);
1126 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1128 ssize_t index = mEffects.indexOfKey(id);
1130 ALOGW("unregisterEffect() unknown effect ID %d", id);
1131 return INVALID_OPERATION;
1134 EffectDescriptor *pDesc = mEffects.valueAt(index);
1136 setEffectEnabled(pDesc, false);
1138 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1139 ALOGW("unregisterEffect() memory %d too big for total %d",
1140 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1141 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1143 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1144 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1145 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1147 mEffects.removeItem(id);
1153 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1155 ssize_t index = mEffects.indexOfKey(id);
1157 ALOGW("unregisterEffect() unknown effect ID %d", id);
1158 return INVALID_OPERATION;
1161 return setEffectEnabled(mEffects.valueAt(index), enabled);
1164 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1166 if (enabled == pDesc->mEnabled) {
1167 ALOGV("setEffectEnabled(%s) effect already %s",
1168 enabled?"true":"false", enabled?"enabled":"disabled");
1169 return INVALID_OPERATION;
1173 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1174 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1175 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1176 return INVALID_OPERATION;
1178 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1179 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1181 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1182 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1183 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1184 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1186 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1187 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1189 pDesc->mEnabled = enabled;
1193 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1195 nsecs_t sysTime = systemTime();
1196 for (size_t i = 0; i < mOutputs.size(); i++) {
1197 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1198 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1205 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1207 nsecs_t sysTime = systemTime();
1208 for (size_t i = 0; i < mOutputs.size(); i++) {
1209 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1210 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1211 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1218 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1220 for (size_t i = 0; i < mInputs.size(); i++) {
1221 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1222 if ((inputDescriptor->mInputSource == (int) source)
1223 && (inputDescriptor->mRefCount > 0)) {
1232 status_t AudioPolicyManagerBase::dump(int fd)
1234 const size_t SIZE = 256;
1238 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1239 result.append(buffer);
1241 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1242 result.append(buffer);
1243 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1244 result.append(buffer);
1245 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1246 result.append(buffer);
1247 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1248 result.append(buffer);
1249 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1250 result.append(buffer);
1251 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1252 result.append(buffer);
1253 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1254 result.append(buffer);
1255 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1256 result.append(buffer);
1257 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1258 result.append(buffer);
1259 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1260 result.append(buffer);
1261 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1262 result.append(buffer);
1263 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1264 result.append(buffer);
1265 write(fd, result.string(), result.size());
1268 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1269 write(fd, buffer, strlen(buffer));
1270 for (size_t i = 0; i < mHwModules.size(); i++) {
1271 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1272 write(fd, buffer, strlen(buffer));
1273 mHwModules[i]->dump(fd);
1276 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1277 write(fd, buffer, strlen(buffer));
1278 for (size_t i = 0; i < mOutputs.size(); i++) {
1279 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1280 write(fd, buffer, strlen(buffer));
1281 mOutputs.valueAt(i)->dump(fd);
1284 snprintf(buffer, SIZE, "\nInputs dump:\n");
1285 write(fd, buffer, strlen(buffer));
1286 for (size_t i = 0; i < mInputs.size(); i++) {
1287 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1288 write(fd, buffer, strlen(buffer));
1289 mInputs.valueAt(i)->dump(fd);
1292 snprintf(buffer, SIZE, "\nStreams dump:\n");
1293 write(fd, buffer, strlen(buffer));
1294 snprintf(buffer, SIZE,
1295 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1296 write(fd, buffer, strlen(buffer));
1297 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1298 snprintf(buffer, SIZE, " %02d ", i);
1299 write(fd, buffer, strlen(buffer));
1300 mStreams[i].dump(fd);
1303 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1304 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1305 write(fd, buffer, strlen(buffer));
1307 snprintf(buffer, SIZE, "Registered effects:\n");
1308 write(fd, buffer, strlen(buffer));
1309 for (size_t i = 0; i < mEffects.size(); i++) {
1310 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1311 write(fd, buffer, strlen(buffer));
1312 mEffects.valueAt(i)->dump(fd);
1319 // ----------------------------------------------------------------------------
1320 // AudioPolicyManagerBase
1321 // ----------------------------------------------------------------------------
1323 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1325 #ifdef AUDIO_POLICY_TEST
1327 #endif //AUDIO_POLICY_TEST
1328 mPrimaryOutput((audio_io_handle_t)0),
1329 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1330 mPhoneState(AudioSystem::MODE_NORMAL),
1331 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1332 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1333 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false)
1335 mpClientInterface = clientInterface;
1337 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1338 mForceUse[i] = AudioSystem::FORCE_NONE;
1341 initializeVolumeCurves();
1343 mA2dpDeviceAddress = String8("");
1344 mScoDeviceAddress = String8("");
1345 mUsbCardAndDevice = String8("");
1347 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1348 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1349 ALOGE("could not load audio policy configuration file, setting defaults");
1350 defaultAudioPolicyConfig();
1354 // open all output streams needed to access attached devices
1355 for (size_t i = 0; i < mHwModules.size(); i++) {
1356 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1357 if (mHwModules[i]->mHandle == 0) {
1358 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1361 // open all output streams needed to access attached devices
1362 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1364 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1366 if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1367 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1368 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1369 outProfile->mSupportedDevices);
1370 audio_io_handle_t output = mpClientInterface->openOutput(
1371 outProfile->mModule->mHandle,
1372 &outputDesc->mDevice,
1373 &outputDesc->mSamplingRate,
1374 &outputDesc->mFormat,
1375 &outputDesc->mChannelMask,
1376 &outputDesc->mLatency,
1377 outputDesc->mFlags);
1381 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1382 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1383 if (mPrimaryOutput == 0 &&
1384 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1385 mPrimaryOutput = output;
1387 addOutput(output, outputDesc);
1388 setOutputDevice(output,
1389 (audio_devices_t)(mDefaultOutputDevice &
1390 outProfile->mSupportedDevices),
1397 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1398 "Not output found for attached devices %08x",
1399 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1401 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1403 updateDevicesAndOutputs();
1405 #ifdef AUDIO_POLICY_TEST
1406 if (mPrimaryOutput != 0) {
1407 AudioParameter outputCmd = AudioParameter();
1408 outputCmd.addInt(String8("set_id"), 0);
1409 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1411 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1412 mTestSamplingRate = 44100;
1413 mTestFormat = AudioSystem::PCM_16_BIT;
1414 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1417 mDirectOutput = false;
1418 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1419 mTestOutputs[i] = 0;
1422 const size_t SIZE = 256;
1424 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1425 run(buffer, ANDROID_PRIORITY_AUDIO);
1427 #endif //AUDIO_POLICY_TEST
1430 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1432 #ifdef AUDIO_POLICY_TEST
1434 #endif //AUDIO_POLICY_TEST
1435 for (size_t i = 0; i < mOutputs.size(); i++) {
1436 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1437 delete mOutputs.valueAt(i);
1439 for (size_t i = 0; i < mInputs.size(); i++) {
1440 mpClientInterface->closeInput(mInputs.keyAt(i));
1441 delete mInputs.valueAt(i);
1443 for (size_t i = 0; i < mHwModules.size(); i++) {
1444 delete mHwModules[i];
1448 status_t AudioPolicyManagerBase::initCheck()
1450 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1453 #ifdef AUDIO_POLICY_TEST
1454 bool AudioPolicyManagerBase::threadLoop()
1456 ALOGV("entering threadLoop()");
1457 while (!exitPending())
1463 Mutex::Autolock _l(mLock);
1464 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1466 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1467 AudioParameter param = AudioParameter(command);
1469 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1471 ALOGV("Test command %s received", command.string());
1473 if (param.get(String8("target"), target) != NO_ERROR) {
1476 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1477 param.remove(String8("test_cmd_policy_output"));
1478 mCurOutput = valueInt;
1480 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1481 param.remove(String8("test_cmd_policy_direct"));
1482 if (value == "false") {
1483 mDirectOutput = false;
1484 } else if (value == "true") {
1485 mDirectOutput = true;
1488 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1489 param.remove(String8("test_cmd_policy_input"));
1490 mTestInput = valueInt;
1493 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1494 param.remove(String8("test_cmd_policy_format"));
1495 int format = AudioSystem::INVALID_FORMAT;
1496 if (value == "PCM 16 bits") {
1497 format = AudioSystem::PCM_16_BIT;
1498 } else if (value == "PCM 8 bits") {
1499 format = AudioSystem::PCM_8_BIT;
1500 } else if (value == "Compressed MP3") {
1501 format = AudioSystem::MP3;
1503 if (format != AudioSystem::INVALID_FORMAT) {
1504 if (target == "Manager") {
1505 mTestFormat = format;
1506 } else if (mTestOutputs[mCurOutput] != 0) {
1507 AudioParameter outputParam = AudioParameter();
1508 outputParam.addInt(String8("format"), format);
1509 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1513 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1514 param.remove(String8("test_cmd_policy_channels"));
1517 if (value == "Channels Stereo") {
1518 channels = AudioSystem::CHANNEL_OUT_STEREO;
1519 } else if (value == "Channels Mono") {
1520 channels = AudioSystem::CHANNEL_OUT_MONO;
1522 if (channels != 0) {
1523 if (target == "Manager") {
1524 mTestChannels = channels;
1525 } else if (mTestOutputs[mCurOutput] != 0) {
1526 AudioParameter outputParam = AudioParameter();
1527 outputParam.addInt(String8("channels"), channels);
1528 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1532 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1533 param.remove(String8("test_cmd_policy_sampleRate"));
1534 if (valueInt >= 0 && valueInt <= 96000) {
1535 int samplingRate = valueInt;
1536 if (target == "Manager") {
1537 mTestSamplingRate = samplingRate;
1538 } else if (mTestOutputs[mCurOutput] != 0) {
1539 AudioParameter outputParam = AudioParameter();
1540 outputParam.addInt(String8("sampling_rate"), samplingRate);
1541 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1546 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1547 param.remove(String8("test_cmd_policy_reopen"));
1549 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1550 mpClientInterface->closeOutput(mPrimaryOutput);
1552 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1554 delete mOutputs.valueFor(mPrimaryOutput);
1555 mOutputs.removeItem(mPrimaryOutput);
1557 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1558 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1559 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1560 &outputDesc->mDevice,
1561 &outputDesc->mSamplingRate,
1562 &outputDesc->mFormat,
1563 &outputDesc->mChannelMask,
1564 &outputDesc->mLatency,
1565 outputDesc->mFlags);
1566 if (mPrimaryOutput == 0) {
1567 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1568 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1570 AudioParameter outputCmd = AudioParameter();
1571 outputCmd.addInt(String8("set_id"), 0);
1572 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1573 addOutput(mPrimaryOutput, outputDesc);
1578 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1584 void AudioPolicyManagerBase::exit()
1587 AutoMutex _l(mLock);
1589 mWaitWorkCV.signal();
1591 requestExitAndWait();
1594 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1596 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1597 if (output == mTestOutputs[i]) return i;
1601 #endif //AUDIO_POLICY_TEST
1605 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1607 outputDesc->mId = id;
1608 mOutputs.add(id, outputDesc);
1612 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1613 AudioSystem::device_connection_state state,
1614 SortedVector<audio_io_handle_t>& outputs)
1616 AudioOutputDescriptor *desc;
1618 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1619 // first list already open outputs that can be routed to this device
1620 for (size_t i = 0; i < mOutputs.size(); i++) {
1621 desc = mOutputs.valueAt(i);
1622 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1623 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1624 outputs.add(mOutputs.keyAt(i));
1627 // then look for output profiles that can be routed to this device
1628 SortedVector<IOProfile *> profiles;
1629 for (size_t i = 0; i < mHwModules.size(); i++)
1631 if (mHwModules[i]->mHandle == 0) {
1634 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1636 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1637 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1638 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1643 if (profiles.isEmpty() && outputs.isEmpty()) {
1644 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1648 // open outputs for matching profiles if needed. Direct outputs are also opened to
1649 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1650 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1651 IOProfile *profile = profiles[profile_index];
1653 // nothing to do if one output is already opened for this profile
1655 for (j = 0; j < mOutputs.size(); j++) {
1656 desc = mOutputs.valueAt(j);
1657 if (!desc->isDuplicated() && desc->mProfile == profile) {
1661 if (j != mOutputs.size()) {
1665 ALOGV("opening output for device %08x", device);
1666 desc = new AudioOutputDescriptor(profile);
1667 desc->mDevice = device;
1668 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1670 &desc->mSamplingRate,
1672 &desc->mChannelMask,
1676 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1679 if (profile->mSamplingRates[0] == 0) {
1680 reply = mpClientInterface->getParameters(output,
1681 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1682 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1684 value = strpbrk((char *)reply.string(), "=");
1685 if (value != NULL) {
1686 loadSamplingRates(value + 1, profile);
1689 if (profile->mFormats[0] == 0) {
1690 reply = mpClientInterface->getParameters(output,
1691 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1692 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1694 value = strpbrk((char *)reply.string(), "=");
1695 if (value != NULL) {
1696 loadFormats(value + 1, profile);
1699 if (profile->mChannelMasks[0] == 0) {
1700 reply = mpClientInterface->getParameters(output,
1701 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1702 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1704 value = strpbrk((char *)reply.string(), "=");
1705 if (value != NULL) {
1706 loadOutChannels(value + 1, profile);
1709 if (((profile->mSamplingRates[0] == 0) &&
1710 (profile->mSamplingRates.size() < 2)) ||
1711 ((profile->mFormats[0] == 0) &&
1712 (profile->mFormats.size() < 2)) ||
1713 ((profile->mFormats[0] == 0) &&
1714 (profile->mChannelMasks.size() < 2))) {
1715 ALOGW("checkOutputsForDevice() direct output missing param");
1716 mpClientInterface->closeOutput(output);
1719 addOutput(output, desc);
1722 audio_io_handle_t duplicatedOutput = 0;
1723 // add output descriptor
1724 addOutput(output, desc);
1725 // set initial stream volume for device
1726 applyStreamVolumes(output, device, 0, true);
1728 //TODO: configure audio effect output stage here
1730 // open a duplicating output thread for the new output and the primary output
1731 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1733 if (duplicatedOutput != 0) {
1734 // add duplicated output descriptor
1735 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1736 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1737 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1738 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1739 dupOutputDesc->mFormat = desc->mFormat;
1740 dupOutputDesc->mChannelMask = desc->mChannelMask;
1741 dupOutputDesc->mLatency = desc->mLatency;
1742 addOutput(duplicatedOutput, dupOutputDesc);
1743 applyStreamVolumes(duplicatedOutput, device, 0, true);
1745 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1746 mPrimaryOutput, output);
1747 mpClientInterface->closeOutput(output);
1748 mOutputs.removeItem(output);
1754 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1756 profiles.removeAt(profile_index);
1759 outputs.add(output);
1760 ALOGV("checkOutputsForDevice(): adding output %d", output);
1764 if (profiles.isEmpty()) {
1765 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1769 // check if one opened output is not needed any more after disconnecting one device
1770 for (size_t i = 0; i < mOutputs.size(); i++) {
1771 desc = mOutputs.valueAt(i);
1772 if (!desc->isDuplicated() &&
1773 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1774 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1775 outputs.add(mOutputs.keyAt(i));
1778 for (size_t i = 0; i < mHwModules.size(); i++)
1780 if (mHwModules[i]->mHandle == 0) {
1783 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1785 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1786 if ((profile->mSupportedDevices & device) &&
1787 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1788 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1790 if (profile->mSamplingRates[0] == 0) {
1791 profile->mSamplingRates.clear();
1792 profile->mSamplingRates.add(0);
1794 if (profile->mFormats[0] == 0) {
1795 profile->mFormats.clear();
1796 profile->mFormats.add((audio_format_t)0);
1798 if (profile->mChannelMasks[0] == 0) {
1799 profile->mChannelMasks.clear();
1800 profile->mChannelMasks.add((audio_channel_mask_t)0);
1809 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1811 ALOGV("closeOutput(%d)", output);
1813 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1814 if (outputDesc == NULL) {
1815 ALOGW("closeOutput() unknown output %d", output);
1819 // look for duplicated outputs connected to the output being removed.
1820 for (size_t i = 0; i < mOutputs.size(); i++) {
1821 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1822 if (dupOutputDesc->isDuplicated() &&
1823 (dupOutputDesc->mOutput1 == outputDesc ||
1824 dupOutputDesc->mOutput2 == outputDesc)) {
1825 AudioOutputDescriptor *outputDesc2;
1826 if (dupOutputDesc->mOutput1 == outputDesc) {
1827 outputDesc2 = dupOutputDesc->mOutput2;
1829 outputDesc2 = dupOutputDesc->mOutput1;
1831 // As all active tracks on duplicated output will be deleted,
1832 // and as they were also referenced on the other output, the reference
1833 // count for their stream type must be adjusted accordingly on
1834 // the other output.
1835 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1836 int refCount = dupOutputDesc->mRefCount[j];
1837 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1839 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1840 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1842 mpClientInterface->closeOutput(duplicatedOutput);
1843 delete mOutputs.valueFor(duplicatedOutput);
1844 mOutputs.removeItem(duplicatedOutput);
1848 AudioParameter param;
1849 param.add(String8("closing"), String8("true"));
1850 mpClientInterface->setParameters(output, param.toString());
1852 mpClientInterface->closeOutput(output);
1854 mOutputs.removeItem(output);
1855 mPreviousOutputs = mOutputs;
1858 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
1859 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
1861 SortedVector<audio_io_handle_t> outputs;
1863 ALOGVV("getOutputsForDevice() device %04x", device);
1864 for (size_t i = 0; i < openOutputs.size(); i++) {
1865 ALOGVV("output %d isDuplicated=%d device=%04x",
1866 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
1867 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
1868 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
1869 outputs.add(openOutputs.keyAt(i));
1875 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1876 SortedVector<audio_io_handle_t>& outputs2)
1878 if (outputs1.size() != outputs2.size()) {
1881 for (size_t i = 0; i < outputs1.size(); i++) {
1882 if (outputs1[i] != outputs2[i]) {
1889 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1891 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
1892 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
1893 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
1894 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
1896 if (!vectorsEqual(srcOutputs,dstOutputs)) {
1897 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1898 strategy, srcOutputs[0], dstOutputs[0]);
1899 // mute strategy while moving tracks from one output to another
1900 for (size_t i = 0; i < srcOutputs.size(); i++) {
1901 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
1902 if (desc->isStrategyActive(strategy)) {
1903 setStrategyMute(strategy, true, srcOutputs[i]);
1904 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
1908 // Move effects associated to this strategy from previous output to new output
1909 if (strategy == STRATEGY_MEDIA) {
1911 for (size_t i = 0; i < dstOutputs.size(); i++) {
1912 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1913 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1917 SortedVector<audio_io_handle_t> moved;
1918 for (size_t i = 0; i < mEffects.size(); i++) {
1919 EffectDescriptor *desc = mEffects.valueAt(i);
1920 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
1921 desc->mIo != dstOutputs[outIdx]) {
1922 if (moved.indexOf(desc->mIo) < 0) {
1923 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1924 mEffects.keyAt(i), dstOutputs[outIdx]);
1925 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
1926 dstOutputs[outIdx]);
1927 moved.add(desc->mIo);
1929 desc->mIo = dstOutputs[outIdx];
1933 // Move tracks associated to this strategy from previous output to new output
1934 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1935 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1936 //FIXME see fixme on name change
1937 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
1938 dstOutputs[0] /* ignored */);
1944 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1946 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1947 checkOutputForStrategy(STRATEGY_PHONE);
1948 checkOutputForStrategy(STRATEGY_SONIFICATION);
1949 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1950 checkOutputForStrategy(STRATEGY_MEDIA);
1951 checkOutputForStrategy(STRATEGY_DTMF);
1954 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1960 for (size_t i = 0; i < mOutputs.size(); i++) {
1961 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1962 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1963 return mOutputs.keyAt(i);
1970 void AudioPolicyManagerBase::checkA2dpSuspend()
1975 audio_io_handle_t a2dpOutput = getA2dpOutput();
1976 if (a2dpOutput == 0) {
1980 // suspend A2DP output if:
1981 // (NOT already suspended) &&
1982 // ((SCO device is connected &&
1983 // (forced usage for communication || for record is SCO))) ||
1984 // (phone state is ringing || in call)
1986 // restore A2DP output if:
1987 // (Already suspended) &&
1988 // ((SCO device is NOT connected ||
1989 // (forced usage NOT for communication && NOT for record is SCO))) &&
1990 // (phone state is NOT ringing && NOT in call)
1992 if (mA2dpSuspended) {
1993 if (((mScoDeviceAddress == "") ||
1994 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1995 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1996 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1997 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1999 mpClientInterface->restoreOutput(a2dpOutput);
2000 mA2dpSuspended = false;
2003 if (((mScoDeviceAddress != "") &&
2004 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2005 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2006 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2007 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2009 mpClientInterface->suspendOutput(a2dpOutput);
2010 mA2dpSuspended = true;
2015 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2017 audio_devices_t device = AUDIO_DEVICE_NONE;
2019 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2020 // check the following by order of priority to request a routing change if necessary:
2021 // 1: the strategy enforced audible is active on the output:
2022 // use device for strategy enforced audible
2023 // 2: we are in call or the strategy phone is active on the output:
2024 // use device for strategy phone
2025 // 3: the strategy sonification is active on the output:
2026 // use device for strategy sonification
2027 // 4: the strategy "respectful" sonification is active on the output:
2028 // use device for strategy "respectful" sonification
2029 // 5: the strategy media is active on the output:
2030 // use device for strategy media
2031 // 6: the strategy DTMF is active on the output:
2032 // use device for strategy DTMF
2033 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2034 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2035 } else if (isInCall() ||
2036 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2037 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2038 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2039 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2040 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2041 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2042 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2043 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2044 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2045 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2048 ALOGV("getNewDevice() selected device %x", device);
2052 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2053 return (uint32_t)getStrategy(stream);
2056 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2057 audio_devices_t devices;
2058 // By checking the range of stream before calling getStrategy, we avoid
2059 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2060 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2061 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2062 devices = AUDIO_DEVICE_NONE;
2064 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2065 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2070 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2071 AudioSystem::stream_type stream) {
2072 // stream to strategy mapping
2074 case AudioSystem::VOICE_CALL:
2075 case AudioSystem::BLUETOOTH_SCO:
2076 return STRATEGY_PHONE;
2077 case AudioSystem::RING:
2078 case AudioSystem::ALARM:
2079 return STRATEGY_SONIFICATION;
2080 case AudioSystem::NOTIFICATION:
2081 return STRATEGY_SONIFICATION_RESPECTFUL;
2082 case AudioSystem::DTMF:
2083 return STRATEGY_DTMF;
2085 ALOGE("unknown stream type");
2086 case AudioSystem::SYSTEM:
2087 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2088 // while key clicks are played produces a poor result
2089 case AudioSystem::TTS:
2090 case AudioSystem::MUSIC:
2091 return STRATEGY_MEDIA;
2092 case AudioSystem::ENFORCED_AUDIBLE:
2093 return STRATEGY_ENFORCED_AUDIBLE;
2097 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2099 case AudioSystem::MUSIC:
2100 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2101 updateDevicesAndOutputs();
2108 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2111 uint32_t device = AUDIO_DEVICE_NONE;
2114 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2115 strategy, mDeviceForStrategy[strategy]);
2116 return mDeviceForStrategy[strategy];
2121 case STRATEGY_SONIFICATION_RESPECTFUL:
2123 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2124 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2125 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2126 // while media is playing on a remote device, use the the sonification behavior.
2127 // Note that we test this usecase before testing if media is playing because
2128 // the isStreamActive() method only informs about the activity of a stream, not
2129 // if it's for local playback. Note also that we use the same delay between both tests
2130 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2131 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2132 // while media is playing (or has recently played), use the same device
2133 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2135 // when media is not playing anymore, fall back on the sonification behavior
2136 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2143 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2144 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2147 // when in call, DTMF and PHONE strategies follow the same rules
2150 case STRATEGY_PHONE:
2151 // for phone strategy, we first consider the forced use and then the available devices by order
2153 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2154 case AudioSystem::FORCE_BT_SCO:
2155 if (!isInCall() || strategy != STRATEGY_DTMF) {
2156 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2159 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2161 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2163 // if SCO device is requested but no SCO device is available, fall back to default case
2166 default: // FORCE_NONE
2167 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2168 if (mHasA2dp && !isInCall() &&
2169 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2170 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2171 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2173 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2176 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2178 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2180 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2181 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2183 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2185 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2187 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2189 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2192 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2194 device = mDefaultOutputDevice;
2195 if (device == AUDIO_DEVICE_NONE) {
2196 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2200 case AudioSystem::FORCE_SPEAKER:
2201 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2202 // A2DP speaker when forcing to speaker output
2203 if (mHasA2dp && !isInCall() &&
2204 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2205 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2206 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2209 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2210 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2212 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2214 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2216 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2218 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2221 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2223 device = mDefaultOutputDevice;
2224 if (device == AUDIO_DEVICE_NONE) {
2225 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2231 case STRATEGY_SONIFICATION:
2233 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2234 // handleIncallSonification().
2236 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2241 case STRATEGY_ENFORCED_AUDIBLE:
2242 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2244 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2245 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2247 if ((strategy == STRATEGY_SONIFICATION) ||
2248 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2249 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2250 if (device == AUDIO_DEVICE_NONE) {
2251 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2254 // The second device used for sonification is the same as the device used by media strategy
2257 case STRATEGY_MEDIA: {
2258 uint32_t device2 = AUDIO_DEVICE_NONE;
2259 if (strategy != STRATEGY_SONIFICATION) {
2260 // no sonification on remote submix (e.g. WFD)
2261 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2263 if ((device2 == AUDIO_DEVICE_NONE) &&
2264 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2265 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2266 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2267 if (device2 == AUDIO_DEVICE_NONE) {
2268 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2270 if (device2 == AUDIO_DEVICE_NONE) {
2271 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2274 if (device2 == AUDIO_DEVICE_NONE) {
2275 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2277 if (device2 == AUDIO_DEVICE_NONE) {
2278 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2280 if (device2 == AUDIO_DEVICE_NONE) {
2281 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2283 if (device2 == AUDIO_DEVICE_NONE) {
2284 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2286 if (device2 == AUDIO_DEVICE_NONE) {
2287 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2289 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2290 // no sonification on aux digital (e.g. HDMI)
2291 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2293 if ((device2 == AUDIO_DEVICE_NONE) &&
2294 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2295 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2297 if (device2 == AUDIO_DEVICE_NONE) {
2298 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2301 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2302 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2305 device = mDefaultOutputDevice;
2306 if (device == AUDIO_DEVICE_NONE) {
2307 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2312 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2316 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2320 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2322 for (int i = 0; i < NUM_STRATEGIES; i++) {
2323 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2325 mPreviousOutputs = mOutputs;
2328 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2329 audio_devices_t prevDevice,
2332 // mute/unmute strategies using an incompatible device combination
2333 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2334 // if unmuting, unmute only after the specified delay
2335 if (outputDesc->isDuplicated()) {
2339 uint32_t muteWaitMs = 0;
2340 audio_devices_t device = outputDesc->device();
2341 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2342 // temporary mute output if device selection changes to avoid volume bursts due to
2343 // different per device volumes
2344 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2346 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2347 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2348 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2349 bool doMute = false;
2351 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2353 outputDesc->mStrategyMutedByDevice[i] = true;
2354 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2356 outputDesc->mStrategyMutedByDevice[i] = false;
2358 if (doMute || tempMute) {
2359 for (size_t j = 0; j < mOutputs.size(); j++) {
2360 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2361 // skip output if it does not share any device with current output
2362 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2363 == AUDIO_DEVICE_NONE) {
2366 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2367 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2368 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2369 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2370 if (desc->isStrategyActive((routing_strategy)i)) {
2371 // do tempMute only for current output
2372 if (tempMute && (desc == outputDesc)) {
2373 setStrategyMute((routing_strategy)i, true, curOutput);
2374 setStrategyMute((routing_strategy)i, false, curOutput,
2375 desc->latency() * 2, device);
2377 if ((tempMute && (desc == outputDesc)) || mute) {
2378 if (muteWaitMs < desc->latency()) {
2379 muteWaitMs = desc->latency();
2387 // FIXME: should not need to double latency if volume could be applied immediately by the
2388 // audioflinger mixer. We must account for the delay between now and the next time
2389 // the audioflinger thread for this output will process a buffer (which corresponds to
2390 // one buffer size, usually 1/2 or 1/4 of the latency).
2392 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2393 if (muteWaitMs > delayMs) {
2394 muteWaitMs -= delayMs;
2395 usleep(muteWaitMs * 1000);
2401 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2402 audio_devices_t device,
2406 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2407 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2408 AudioParameter param;
2409 uint32_t muteWaitMs;
2411 if (outputDesc->isDuplicated()) {
2412 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2413 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2416 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2418 if ((device != AUDIO_DEVICE_NONE) &&
2419 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2423 // filter devices according to output selected
2424 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2426 audio_devices_t prevDevice = outputDesc->mDevice;
2428 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2430 if (device != AUDIO_DEVICE_NONE) {
2431 outputDesc->mDevice = device;
2433 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2435 // Do not change the routing if:
2436 // - the requested device is AUDIO_DEVICE_NONE
2437 // - the requested device is the same as current device and force is not specified.
2438 // Doing this check here allows the caller to call setOutputDevice() without conditions
2439 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2440 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2444 ALOGV("setOutputDevice() changing device");
2446 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2447 mpClientInterface->setParameters(output, param.toString(), delayMs);
2449 // update stream volumes according to new device
2450 applyStreamVolumes(output, device, delayMs);
2455 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2456 uint32_t samplingRate,
2458 uint32_t channelMask)
2460 // Choose an input profile based on the requested capture parameters: select the first available
2461 // profile supporting all requested parameters.
2463 for (size_t i = 0; i < mHwModules.size(); i++)
2465 if (mHwModules[i]->mHandle == 0) {
2468 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2470 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2471 if (profile->isCompatibleProfile(device, samplingRate, format,
2472 channelMask,(audio_output_flags_t)0)) {
2480 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2482 uint32_t device = AUDIO_DEVICE_NONE;
2484 switch (inputSource) {
2485 case AUDIO_SOURCE_VOICE_UPLINK:
2486 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2487 device = AUDIO_DEVICE_IN_VOICE_CALL;
2492 case AUDIO_SOURCE_DEFAULT:
2493 case AUDIO_SOURCE_MIC:
2494 case AUDIO_SOURCE_VOICE_RECOGNITION:
2495 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2496 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2497 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2498 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2499 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2500 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2501 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2502 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2505 case AUDIO_SOURCE_CAMCORDER:
2506 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2507 device = AUDIO_DEVICE_IN_BACK_MIC;
2508 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2509 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2512 case AUDIO_SOURCE_VOICE_DOWNLINK:
2513 case AUDIO_SOURCE_VOICE_CALL:
2514 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2515 device = AUDIO_DEVICE_IN_VOICE_CALL;
2518 case AUDIO_SOURCE_REMOTE_SUBMIX:
2519 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2520 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2524 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2527 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2531 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2533 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2534 device &= ~AUDIO_DEVICE_BIT_IN;
2535 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2541 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2543 for (size_t i = 0; i < mInputs.size(); i++) {
2544 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2545 if ((input_descriptor->mRefCount > 0)
2546 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2547 return mInputs.keyAt(i);
2554 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2556 if (device == AUDIO_DEVICE_NONE) {
2557 // this happens when forcing a route update and no track is active on an output.
2558 // In this case the returned category is not important.
2559 device = AUDIO_DEVICE_OUT_SPEAKER;
2560 } else if (AudioSystem::popCount(device) > 1) {
2561 // Multiple device selection is either:
2562 // - speaker + one other device: give priority to speaker in this case.
2563 // - one A2DP device + another device: happens with duplicated output. In this case
2564 // retain the device on the A2DP output as the other must not correspond to an active
2565 // selection if not the speaker.
2566 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2567 device = AUDIO_DEVICE_OUT_SPEAKER;
2569 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2573 ALOGW_IF(AudioSystem::popCount(device) != 1,
2574 "getDeviceForVolume() invalid device combination: %08x",
2580 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2582 switch(getDeviceForVolume(device)) {
2583 case AUDIO_DEVICE_OUT_EARPIECE:
2584 return DEVICE_CATEGORY_EARPIECE;
2585 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2586 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2587 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2588 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2589 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2590 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2591 return DEVICE_CATEGORY_HEADSET;
2592 case AUDIO_DEVICE_OUT_SPEAKER:
2593 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2594 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2595 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2596 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2597 case AUDIO_DEVICE_OUT_USB_DEVICE:
2598 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
2600 return DEVICE_CATEGORY_SPEAKER;
2604 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2607 device_category deviceCategory = getDeviceCategory(device);
2608 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2610 // the volume index in the UI is relative to the min and max volume indices for this stream type
2611 int nbSteps = 1 + curve[VOLMAX].mIndex -
2612 curve[VOLMIN].mIndex;
2613 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2614 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2616 // find what part of the curve this index volume belongs to, or if it's out of bounds
2618 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2620 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2622 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2624 } else if (volIdx <= curve[VOLMAX].mIndex) {
2626 } else { // out of bounds
2630 // linear interpolation in the attenuation table in dB
2631 float decibels = curve[segment].mDBAttenuation +
2632 ((float)(volIdx - curve[segment].mIndex)) *
2633 ( (curve[segment+1].mDBAttenuation -
2634 curve[segment].mDBAttenuation) /
2635 ((float)(curve[segment+1].mIndex -
2636 curve[segment].mIndex)) );
2638 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2640 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2641 curve[segment].mIndex, volIdx,
2642 curve[segment+1].mIndex,
2643 curve[segment].mDBAttenuation,
2645 curve[segment+1].mDBAttenuation,
2648 return amplification;
2651 const AudioPolicyManagerBase::VolumeCurvePoint
2652 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2653 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2656 const AudioPolicyManagerBase::VolumeCurvePoint
2657 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2658 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2661 const AudioPolicyManagerBase::VolumeCurvePoint
2662 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2663 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2666 const AudioPolicyManagerBase::VolumeCurvePoint
2667 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2668 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2671 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2672 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2673 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2674 const AudioPolicyManagerBase::VolumeCurvePoint
2675 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2676 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2679 const AudioPolicyManagerBase::VolumeCurvePoint
2680 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2681 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2684 const AudioPolicyManagerBase::VolumeCurvePoint
2685 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2686 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
2689 const AudioPolicyManagerBase::VolumeCurvePoint
2690 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2691 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
2694 const AudioPolicyManagerBase::VolumeCurvePoint
2695 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2696 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2697 { // AUDIO_STREAM_VOICE_CALL
2698 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2699 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2700 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2702 { // AUDIO_STREAM_SYSTEM
2703 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2704 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2705 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2707 { // AUDIO_STREAM_RING
2708 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2709 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2710 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2712 { // AUDIO_STREAM_MUSIC
2713 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2714 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2715 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2717 { // AUDIO_STREAM_ALARM
2718 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2719 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2720 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2722 { // AUDIO_STREAM_NOTIFICATION
2723 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2724 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2725 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2727 { // AUDIO_STREAM_BLUETOOTH_SCO
2728 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2729 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2730 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2732 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2733 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2734 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2735 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2737 { // AUDIO_STREAM_DTMF
2738 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2739 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2740 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2742 { // AUDIO_STREAM_TTS
2743 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2744 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2745 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2749 void AudioPolicyManagerBase::initializeVolumeCurves()
2751 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2752 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2753 mStreams[i].mVolumeCurve[j] =
2754 sVolumeProfiles[i][j];
2759 float AudioPolicyManagerBase::computeVolume(int stream,
2761 audio_io_handle_t output,
2762 audio_devices_t device)
2765 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2766 StreamDescriptor &streamDesc = mStreams[stream];
2768 if (device == AUDIO_DEVICE_NONE) {
2769 device = outputDesc->device();
2772 // if volume is not 0 (not muted), force media volume to max on digital output
2773 if (stream == AudioSystem::MUSIC &&
2774 index != mStreams[stream].mIndexMin &&
2775 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2776 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2777 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2778 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2782 volume = volIndexToAmpl(device, streamDesc, index);
2784 // if a headset is connected, apply the following rules to ring tones and notifications
2785 // to avoid sound level bursts in user's ears:
2786 // - always attenuate ring tones and notifications volume by 6dB
2787 // - if music is playing, always limit the volume to current music volume,
2788 // with a minimum threshold at -36dB so that notification is always perceived.
2789 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2790 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
2791 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2792 AUDIO_DEVICE_OUT_WIRED_HEADSET |
2793 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
2794 ((stream_strategy == STRATEGY_SONIFICATION)
2795 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2796 || (stream == AudioSystem::SYSTEM)
2797 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
2798 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
2799 streamDesc.mCanBeMuted) {
2800 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2801 // when the phone is ringing we must consider that music could have been paused just before
2802 // by the music application and behave as if music was active if the last music track was
2804 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2805 mLimitRingtoneVolume) {
2806 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
2807 float musicVol = computeVolume(AudioSystem::MUSIC,
2808 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
2811 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2812 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2813 if (volume > minVol) {
2815 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2823 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2825 audio_io_handle_t output,
2826 audio_devices_t device,
2831 // do not change actual stream volume if the stream is muted
2832 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2833 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2834 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2838 // do not change in call volume if bluetooth is connected and vice versa
2839 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2840 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2841 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2842 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2843 return INVALID_OPERATION;
2846 float volume = computeVolume(stream, index, output, device);
2847 // We actually change the volume if:
2848 // - the float value returned by computeVolume() changed
2849 // - the force flag is set
2850 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2852 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2853 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2854 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2856 if (stream == AudioSystem::BLUETOOTH_SCO) {
2857 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2859 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2862 if (stream == AudioSystem::VOICE_CALL ||
2863 stream == AudioSystem::BLUETOOTH_SCO) {
2865 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2866 if (stream == AudioSystem::VOICE_CALL) {
2867 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2872 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2873 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2874 mLastVoiceVolume = voiceVolume;
2881 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2882 audio_devices_t device,
2886 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2888 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2889 checkAndSetVolume(stream,
2890 mStreams[stream].getVolumeIndex(device),
2898 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2900 audio_io_handle_t output,
2902 audio_devices_t device)
2904 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2905 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2906 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2907 setStreamMute(stream, on, output, delayMs, device);
2912 void AudioPolicyManagerBase::setStreamMute(int stream,
2914 audio_io_handle_t output,
2916 audio_devices_t device)
2918 StreamDescriptor &streamDesc = mStreams[stream];
2919 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2920 if (device == AUDIO_DEVICE_NONE) {
2921 device = outputDesc->device();
2924 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
2925 stream, on, output, outputDesc->mMuteCount[stream], device);
2928 if (outputDesc->mMuteCount[stream] == 0) {
2929 if (streamDesc.mCanBeMuted &&
2930 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
2931 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
2932 checkAndSetVolume(stream, 0, output, device, delayMs);
2935 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2936 outputDesc->mMuteCount[stream]++;
2938 if (outputDesc->mMuteCount[stream] == 0) {
2939 ALOGV("setStreamMute() unmuting non muted stream!");
2942 if (--outputDesc->mMuteCount[stream] == 0) {
2943 checkAndSetVolume(stream,
2944 streamDesc.getVolumeIndex(device),
2952 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2954 // if the stream pertains to sonification strategy and we are in call we must
2955 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2956 // in the device used for phone strategy and play the tone if the selected device does not
2957 // interfere with the device used for phone strategy
2958 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2959 // many times as there are active tracks on the output
2960 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2961 if ((stream_strategy == STRATEGY_SONIFICATION) ||
2962 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2963 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2964 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2965 stream, starting, outputDesc->mDevice, stateChange);
2966 if (outputDesc->mRefCount[stream]) {
2969 muteCount = outputDesc->mRefCount[stream];
2971 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2972 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2973 for (int i = 0; i < muteCount; i++) {
2974 setStreamMute(stream, starting, mPrimaryOutput);
2977 ALOGV("handleIncallSonification() high visibility");
2978 if (outputDesc->device() &
2979 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2980 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2981 for (int i = 0; i < muteCount; i++) {
2982 setStreamMute(stream, starting, mPrimaryOutput);
2986 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2988 mpClientInterface->stopTone();
2995 bool AudioPolicyManagerBase::isInCall()
2997 return isStateInCall(mPhoneState);
3000 bool AudioPolicyManagerBase::isStateInCall(int state) {
3001 return ((state == AudioSystem::MODE_IN_CALL) ||
3002 (state == AudioSystem::MODE_IN_COMMUNICATION));
3005 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
3006 uint32_t samplingRate,
3007 audio_format_t format,
3008 audio_channel_mask_t channelMask,
3009 audio_output_flags_t flags,
3010 audio_devices_t device)
3012 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3013 (format != 0 && !AudioSystem::isLinearPCM(format)));
3016 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3018 return MAX_EFFECTS_CPU_LOAD;
3021 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3023 return MAX_EFFECTS_MEMORY;
3026 // --- AudioOutputDescriptor class implementation
3028 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3029 const IOProfile *profile)
3030 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
3031 mChannelMask((audio_channel_mask_t)0), mLatency(0),
3032 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3033 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3035 // clear usage count for all stream types
3036 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3038 mCurVolume[i] = -1.0;
3042 for (int i = 0; i < NUM_STRATEGIES; i++) {
3043 mStrategyMutedByDevice[i] = false;
3045 if (profile != NULL) {
3046 mSamplingRate = profile->mSamplingRates[0];
3047 mFormat = profile->mFormats[0];
3048 mChannelMask = profile->mChannelMasks[0];
3049 mFlags = profile->mFlags;
3053 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3055 if (isDuplicated()) {
3056 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3062 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3064 if (isDuplicated()) {
3065 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3071 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3072 const AudioOutputDescriptor *outputDesc)
3074 if (isDuplicated()) {
3075 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3076 } else if (outputDesc->isDuplicated()){
3077 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3079 return (mProfile->mModule == outputDesc->mProfile->mModule);
3083 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3085 // forward usage count change to attached outputs
3086 if (isDuplicated()) {
3087 mOutput1->changeRefCount(stream, delta);
3088 mOutput2->changeRefCount(stream, delta);
3090 if ((delta + (int)mRefCount[stream]) < 0) {
3091 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3092 mRefCount[stream] = 0;
3095 mRefCount[stream] += delta;
3096 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3099 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3101 if (isDuplicated()) {
3102 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3104 return mProfile->mSupportedDevices ;
3108 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3110 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3113 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3115 nsecs_t sysTime) const
3117 if ((sysTime == 0) && (inPastMs != 0)) {
3118 sysTime = systemTime();
3120 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3121 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3122 (NUM_STRATEGIES == strategy)) &&
3123 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3130 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3132 nsecs_t sysTime) const
3134 if (mRefCount[stream] != 0) {
3137 if (inPastMs == 0) {
3141 sysTime = systemTime();
3143 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3150 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3152 const size_t SIZE = 256;
3156 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3157 result.append(buffer);
3158 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3159 result.append(buffer);
3160 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3161 result.append(buffer);
3162 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3163 result.append(buffer);
3164 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3165 result.append(buffer);
3166 snprintf(buffer, SIZE, " Devices %08x\n", device());
3167 result.append(buffer);
3168 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3169 result.append(buffer);
3170 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3171 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3172 result.append(buffer);
3174 write(fd, result.string(), result.size());
3179 // --- AudioInputDescriptor class implementation
3181 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3182 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3183 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3184 mInputSource(0), mProfile(profile)
3188 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3190 const size_t SIZE = 256;
3194 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3195 result.append(buffer);
3196 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3197 result.append(buffer);
3198 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3199 result.append(buffer);
3200 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3201 result.append(buffer);
3202 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3203 result.append(buffer);
3204 write(fd, result.string(), result.size());
3209 // --- StreamDescriptor class implementation
3211 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3212 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3214 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3217 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3219 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3220 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3221 if (mIndexCur.indexOfKey(device) < 0) {
3222 device = AUDIO_DEVICE_OUT_DEFAULT;
3224 return mIndexCur.valueFor(device);
3227 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3229 const size_t SIZE = 256;
3233 snprintf(buffer, SIZE, "%s %02d %02d ",
3234 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3235 result.append(buffer);
3236 for (size_t i = 0; i < mIndexCur.size(); i++) {
3237 snprintf(buffer, SIZE, "%04x : %02d, ",
3239 mIndexCur.valueAt(i));
3240 result.append(buffer);
3242 result.append("\n");
3244 write(fd, result.string(), result.size());
3247 // --- EffectDescriptor class implementation
3249 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3251 const size_t SIZE = 256;
3255 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3256 result.append(buffer);
3257 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3258 result.append(buffer);
3259 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3260 result.append(buffer);
3261 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3262 result.append(buffer);
3263 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3264 result.append(buffer);
3265 write(fd, result.string(), result.size());
3270 // --- IOProfile class implementation
3272 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3273 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3277 AudioPolicyManagerBase::HwModule::~HwModule()
3279 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3280 delete mOutputProfiles[i];
3282 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3283 delete mInputProfiles[i];
3285 free((void *)mName);
3288 void AudioPolicyManagerBase::HwModule::dump(int fd)
3290 const size_t SIZE = 256;
3294 snprintf(buffer, SIZE, " - name: %s\n", mName);
3295 result.append(buffer);
3296 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3297 result.append(buffer);
3298 write(fd, result.string(), result.size());
3299 if (mOutputProfiles.size()) {
3300 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3301 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3302 snprintf(buffer, SIZE, " output %d:\n", i);
3303 write(fd, buffer, strlen(buffer));
3304 mOutputProfiles[i]->dump(fd);
3307 if (mInputProfiles.size()) {
3308 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3309 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3310 snprintf(buffer, SIZE, " input %d:\n", i);
3311 write(fd, buffer, strlen(buffer));
3312 mInputProfiles[i]->dump(fd);
3317 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3318 : mFlags((audio_output_flags_t)0), mModule(module)
3322 AudioPolicyManagerBase::IOProfile::~IOProfile()
3326 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3327 // means a parameter is don't care
3328 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3329 uint32_t samplingRate,
3331 uint32_t channelMask,
3332 audio_output_flags_t flags) const
3334 if ((mSupportedDevices & device) != device) {
3337 if ((mFlags & flags) != flags) {
3340 if (samplingRate != 0) {
3342 for (i = 0; i < mSamplingRates.size(); i++)
3344 if (mSamplingRates[i] == samplingRate) {
3348 if (i == mSamplingRates.size()) {
3354 for (i = 0; i < mFormats.size(); i++)
3356 if (mFormats[i] == format) {
3360 if (i == mFormats.size()) {
3364 if (channelMask != 0) {
3366 for (i = 0; i < mChannelMasks.size(); i++)
3368 if (mChannelMasks[i] == channelMask) {
3372 if (i == mChannelMasks.size()) {
3379 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3381 const size_t SIZE = 256;
3385 snprintf(buffer, SIZE, " - sampling rates: ");
3386 result.append(buffer);
3387 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3388 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3389 result.append(buffer);
3390 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3393 snprintf(buffer, SIZE, " - channel masks: ");
3394 result.append(buffer);
3395 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3396 snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3397 result.append(buffer);
3398 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3401 snprintf(buffer, SIZE, " - formats: ");
3402 result.append(buffer);
3403 for (size_t i = 0; i < mFormats.size(); i++) {
3404 snprintf(buffer, SIZE, "%d", mFormats[i]);
3405 result.append(buffer);
3406 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3409 snprintf(buffer, SIZE, " - devices: %04x\n", mSupportedDevices);
3410 result.append(buffer);
3411 snprintf(buffer, SIZE, " - flags: %04x\n", mFlags);
3412 result.append(buffer);
3414 write(fd, result.string(), result.size());
3417 // --- audio_policy.conf file parsing
3419 struct StringToEnum {
3424 #define STRING_TO_ENUM(string) { #string, string }
3425 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3427 const struct StringToEnum sDeviceNameToEnumTable[] = {
3428 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3429 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3430 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3431 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3432 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3433 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3434 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3435 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3436 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3437 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3438 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3439 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3440 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3441 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3442 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3443 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3444 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3445 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3446 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3447 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3448 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3449 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3450 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3453 const struct StringToEnum sFlagNameToEnumTable[] = {
3454 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3455 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3456 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3457 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3460 const struct StringToEnum sFormatNameToEnumTable[] = {
3461 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3462 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3463 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3464 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3465 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3468 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3469 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3470 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3471 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3472 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3475 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3476 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3477 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3478 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3482 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3486 for (size_t i = 0; i < size; i++) {
3487 if (strcmp(table[i].name, name) == 0) {
3488 ALOGV("stringToEnum() found %s", table[i].name);
3489 return table[i].value;
3495 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3499 // it is OK to cast name to non const here as we are not going to use it after
3500 // strtok() modifies it
3501 char *flagName = strtok(name, "|");
3502 while (flagName != NULL) {
3503 if (strlen(flagName) != 0) {
3504 flag |= stringToEnum(sFlagNameToEnumTable,
3505 ARRAY_SIZE(sFlagNameToEnumTable),
3508 flagName = strtok(NULL, "|");
3510 return (audio_output_flags_t)flag;
3513 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3515 uint32_t device = 0;
3517 char *devName = strtok(name, "|");
3518 while (devName != NULL) {
3519 if (strlen(devName) != 0) {
3520 device |= stringToEnum(sDeviceNameToEnumTable,
3521 ARRAY_SIZE(sDeviceNameToEnumTable),
3524 devName = strtok(NULL, "|");
3529 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3531 char *str = strtok(name, "|");
3533 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3534 // rates should be read from the output stream after it is opened for the first time
3535 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3536 profile->mSamplingRates.add(0);
3540 while (str != NULL) {
3541 uint32_t rate = atoi(str);
3543 ALOGV("loadSamplingRates() adding rate %d", rate);
3544 profile->mSamplingRates.add(rate);
3546 str = strtok(NULL, "|");
3551 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3553 char *str = strtok(name, "|");
3555 // by convention, "0' in the first entry in mFormats indicates the supported formats
3556 // should be read from the output stream after it is opened for the first time
3557 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3558 profile->mFormats.add((audio_format_t)0);
3562 while (str != NULL) {
3563 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3564 ARRAY_SIZE(sFormatNameToEnumTable),
3567 profile->mFormats.add(format);
3569 str = strtok(NULL, "|");
3574 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3576 const char *str = strtok(name, "|");
3578 ALOGV("loadInChannels() %s", name);
3580 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3581 profile->mChannelMasks.add((audio_channel_mask_t)0);
3585 while (str != NULL) {
3586 audio_channel_mask_t channelMask =
3587 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3588 ARRAY_SIZE(sInChannelsNameToEnumTable),
3590 if (channelMask != 0) {
3591 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3592 profile->mChannelMasks.add(channelMask);
3594 str = strtok(NULL, "|");
3599 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3601 const char *str = strtok(name, "|");
3603 ALOGV("loadOutChannels() %s", name);
3605 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3606 // masks should be read from the output stream after it is opened for the first time
3607 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3608 profile->mChannelMasks.add((audio_channel_mask_t)0);
3612 while (str != NULL) {
3613 audio_channel_mask_t channelMask =
3614 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3615 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3617 if (channelMask != 0) {
3618 profile->mChannelMasks.add(channelMask);
3620 str = strtok(NULL, "|");
3625 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3627 cnode *node = root->first_child;
3629 IOProfile *profile = new IOProfile(module);
3632 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3633 loadSamplingRates((char *)node->value, profile);
3634 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3635 loadFormats((char *)node->value, profile);
3636 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3637 loadInChannels((char *)node->value, profile);
3638 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3639 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3643 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3644 "loadInput() invalid supported devices");
3645 ALOGW_IF(profile->mChannelMasks.size() == 0,
3646 "loadInput() invalid supported channel masks");
3647 ALOGW_IF(profile->mSamplingRates.size() == 0,
3648 "loadInput() invalid supported sampling rates");
3649 ALOGW_IF(profile->mFormats.size() == 0,
3650 "loadInput() invalid supported formats");
3651 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3652 (profile->mChannelMasks.size() != 0) &&
3653 (profile->mSamplingRates.size() != 0) &&
3654 (profile->mFormats.size() != 0)) {
3656 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3658 module->mInputProfiles.add(profile);
3666 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3668 cnode *node = root->first_child;
3670 IOProfile *profile = new IOProfile(module);
3673 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3674 loadSamplingRates((char *)node->value, profile);
3675 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3676 loadFormats((char *)node->value, profile);
3677 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3678 loadOutChannels((char *)node->value, profile);
3679 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3680 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3681 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3682 profile->mFlags = parseFlagNames((char *)node->value);
3686 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3687 "loadOutput() invalid supported devices");
3688 ALOGW_IF(profile->mChannelMasks.size() == 0,
3689 "loadOutput() invalid supported channel masks");
3690 ALOGW_IF(profile->mSamplingRates.size() == 0,
3691 "loadOutput() invalid supported sampling rates");
3692 ALOGW_IF(profile->mFormats.size() == 0,
3693 "loadOutput() invalid supported formats");
3694 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3695 (profile->mChannelMasks.size() != 0) &&
3696 (profile->mSamplingRates.size() != 0) &&
3697 (profile->mFormats.size() != 0)) {
3699 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3700 profile->mSupportedDevices, profile->mFlags);
3702 module->mOutputProfiles.add(profile);
3710 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3712 cnode *node = config_find(root, OUTPUTS_TAG);
3713 status_t status = NAME_NOT_FOUND;
3715 HwModule *module = new HwModule(root->name);
3718 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3720 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3722 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
3723 mHasRemoteSubmix = true;
3726 node = node->first_child;
3728 ALOGV("loadHwModule() loading output %s", node->name);
3729 status_t tmpStatus = loadOutput(node, module);
3730 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3736 node = config_find(root, INPUTS_TAG);
3738 node = node->first_child;
3740 ALOGV("loadHwModule() loading input %s", node->name);
3741 status_t tmpStatus = loadInput(node, module);
3742 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3748 if (status == NO_ERROR) {
3749 mHwModules.add(module);
3755 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3757 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3762 node = node->first_child;
3764 ALOGV("loadHwModules() loading module %s", node->name);
3770 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3772 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3776 node = node->first_child;
3778 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3779 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3780 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
3781 "loadGlobalConfig() no attached output devices");
3782 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3783 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3784 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3785 ARRAY_SIZE(sDeviceNameToEnumTable),
3786 (char *)node->value);
3787 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
3788 "loadGlobalConfig() default device not specified");
3789 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3790 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3791 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
3792 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3798 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3803 data = (char *)load_file(path, NULL);
3807 root = config_node("", "");
3808 config_load(root, data);
3810 loadGlobalConfig(root);
3811 loadHwModules(root);
3817 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3822 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3827 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3828 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3829 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
3831 module = new HwModule("primary");
3833 profile = new IOProfile(module);
3834 profile->mSamplingRates.add(44100);
3835 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3836 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3837 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3838 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3839 module->mOutputProfiles.add(profile);
3841 profile = new IOProfile(module);
3842 profile->mSamplingRates.add(8000);
3843 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3844 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3845 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3846 module->mInputProfiles.add(profile);
3848 mHwModules.add(module);
3851 }; // namespace android