2 * Copyright (C) 2009 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define LOG_TAG "AudioPolicyManagerBase"
18 //#define LOG_NDEBUG 0
20 //#define VERY_VERBOSE_LOGGING
21 #ifdef VERY_VERBOSE_LOGGING
24 #define ALOGVV(a...) do { } while(0)
27 // A device mask for all audio input devices that are considered "virtual" when evaluating
28 // active inputs in getActiveInput()
29 #define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30 // A device mask for all audio output devices that are considered "remote" when evaluating
31 // active output devices in isStreamActiveRemotely()
32 #define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
34 #include <utils/Log.h>
35 #include <hardware_legacy/AudioPolicyManagerBase.h>
36 #include <hardware/audio_effect.h>
37 #include <hardware/audio.h>
39 #include <hardware_legacy/audio_policy_conf.h>
40 #include <cutils/properties.h>
42 namespace android_audio_legacy {
44 // ----------------------------------------------------------------------------
45 // AudioPolicyInterface implementation
46 // ----------------------------------------------------------------------------
49 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
50 AudioSystem::device_connection_state state,
51 const char *device_address)
53 SortedVector <audio_io_handle_t> outputs;
55 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
57 // connect/disconnect only 1 device at a time
58 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
60 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
61 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
65 // handle output devices
66 if (audio_is_output_device(device)) {
68 if (!mHasA2dp && audio_is_a2dp_device(device)) {
69 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
72 if (!mHasUsb && audio_is_usb_device(device)) {
73 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
76 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
77 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
81 // save a copy of the opened output descriptors before any output is opened or closed
82 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
83 mPreviousOutputs = mOutputs;
86 // handle output device connection
87 case AudioSystem::DEVICE_STATE_AVAILABLE:
88 if (mAvailableOutputDevices & device) {
89 ALOGW("setDeviceConnectionState() device already connected: %x", device);
90 return INVALID_OPERATION;
92 ALOGV("setDeviceConnectionState() connecting device %x", device);
94 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
95 return INVALID_OPERATION;
97 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
99 // register new device as available
100 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
102 if (!outputs.isEmpty()) {
104 if (mHasA2dp && audio_is_a2dp_device(device)) {
105 // handle A2DP device connection
106 AudioParameter param;
107 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
108 paramStr = param.toString();
109 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
110 mA2dpSuspended = false;
111 } else if (audio_is_bluetooth_sco_device(device)) {
112 // handle SCO device connection
113 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
114 } else if (mHasUsb && audio_is_usb_device(device)) {
115 // handle USB device connection
116 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
117 paramStr = mUsbCardAndDevice;
119 // not currently handling multiple simultaneous submixes: ignoring remote submix
121 if (!paramStr.isEmpty()) {
122 for (size_t i = 0; i < outputs.size(); i++) {
123 mpClientInterface->setParameters(outputs[i], paramStr);
128 // handle output device disconnection
129 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
130 if (!(mAvailableOutputDevices & device)) {
131 ALOGW("setDeviceConnectionState() device not connected: %x", device);
132 return INVALID_OPERATION;
135 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
136 // remove device from available output devices
137 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
139 checkOutputsForDevice(device, state, outputs);
140 if (mHasA2dp && audio_is_a2dp_device(device)) {
141 // handle A2DP device disconnection
142 mA2dpDeviceAddress = "";
143 mA2dpSuspended = false;
144 } else if (audio_is_bluetooth_sco_device(device)) {
145 // handle SCO device disconnection
146 mScoDeviceAddress = "";
147 } else if (mHasUsb && audio_is_usb_device(device)) {
148 // handle USB device disconnection
149 mUsbCardAndDevice = "";
151 // not currently handling multiple simultaneous submixes: ignoring remote submix
156 ALOGE("setDeviceConnectionState() invalid state: %x", state);
161 checkOutputForAllStrategies();
162 // outputs must be closed after checkOutputForAllStrategies() is executed
163 if (!outputs.isEmpty()) {
164 for (size_t i = 0; i < outputs.size(); i++) {
165 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
166 // close unused outputs after device disconnection or direct outputs that have been
167 // opened by checkOutputsForDevice() to query dynamic parameters
168 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
169 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
170 (desc->mDirectOpenCount == 0))) {
171 closeOutput(outputs[i]);
176 updateDevicesAndOutputs();
177 for (size_t i = 0; i < mOutputs.size(); i++) {
178 // do not force device change on duplicated output because if device is 0, it will
179 // also force a device 0 for the two outputs it is duplicated to which may override
180 // a valid device selection on those outputs.
181 setOutputDevice(mOutputs.keyAt(i),
182 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
183 !mOutputs.valueAt(i)->isDuplicated(),
187 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
188 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
189 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
190 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
191 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
192 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
197 // handle input devices
198 if (audio_is_input_device(device)) {
202 // handle input device connection
203 case AudioSystem::DEVICE_STATE_AVAILABLE: {
204 if (mAvailableInputDevices & device) {
205 ALOGW("setDeviceConnectionState() device already connected: %d", device);
206 return INVALID_OPERATION;
208 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
212 // handle input device disconnection
213 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
214 if (!(mAvailableInputDevices & device)) {
215 ALOGW("setDeviceConnectionState() device not connected: %d", device);
216 return INVALID_OPERATION;
218 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
222 ALOGE("setDeviceConnectionState() invalid state: %x", state);
226 audio_io_handle_t activeInput = getActiveInput();
227 if (activeInput != 0) {
228 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
229 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
230 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
231 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
232 inputDesc->mDevice, newDevice, activeInput);
233 inputDesc->mDevice = newDevice;
234 AudioParameter param = AudioParameter();
235 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
236 mpClientInterface->setParameters(activeInput, param.toString());
243 ALOGW("setDeviceConnectionState() invalid device: %x", device);
247 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
248 const char *device_address)
250 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
251 String8 address = String8(device_address);
252 if (audio_is_output_device(device)) {
253 if (device & mAvailableOutputDevices) {
254 if (audio_is_a2dp_device(device) &&
255 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
258 if (audio_is_bluetooth_sco_device(device) &&
259 address != "" && mScoDeviceAddress != address) {
262 if (audio_is_usb_device(device) &&
263 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
264 ALOGE("getDeviceConnectionState() invalid device: %x", device);
267 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
270 state = AudioSystem::DEVICE_STATE_AVAILABLE;
272 } else if (audio_is_input_device(device)) {
273 if (device & mAvailableInputDevices) {
274 state = AudioSystem::DEVICE_STATE_AVAILABLE;
281 void AudioPolicyManagerBase::setPhoneState(int state)
283 ALOGV("setPhoneState() state %d", state);
284 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
285 if (state < 0 || state >= AudioSystem::NUM_MODES) {
286 ALOGW("setPhoneState() invalid state %d", state);
290 if (state == mPhoneState ) {
291 ALOGW("setPhoneState() setting same state %d", state);
295 // if leaving call state, handle special case of active streams
296 // pertaining to sonification strategy see handleIncallSonification()
298 ALOGV("setPhoneState() in call state management: new state is %d", state);
299 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
300 handleIncallSonification(stream, false, true);
304 // store previous phone state for management of sonification strategy below
305 int oldState = mPhoneState;
309 // are we entering or starting a call
310 if (!isStateInCall(oldState) && isStateInCall(state)) {
311 ALOGV(" Entering call in setPhoneState()");
312 // force routing command to audio hardware when starting a call
313 // even if no device change is needed
315 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
316 ALOGV(" Exiting call in setPhoneState()");
317 // force routing command to audio hardware when exiting a call
318 // even if no device change is needed
320 } else if (isStateInCall(state) && (state != oldState)) {
321 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
322 // force routing command to audio hardware when switching between telephony and VoIP
323 // even if no device change is needed
327 // check for device and output changes triggered by new phone state
328 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
330 checkOutputForAllStrategies();
331 updateDevicesAndOutputs();
333 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
335 // force routing command to audio hardware when ending call
336 // even if no device change is needed
337 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
338 newDevice = hwOutputDesc->device();
342 if (isStateInCall(state)) {
343 nsecs_t sysTime = systemTime();
344 for (size_t i = 0; i < mOutputs.size(); i++) {
345 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
346 // mute media and sonification strategies and delay device switch by the largest
347 // latency of any output where either strategy is active.
348 // This avoid sending the ring tone or music tail into the earpiece or headset.
349 if ((desc->isStrategyActive(STRATEGY_MEDIA,
350 SONIFICATION_HEADSET_MUSIC_DELAY,
352 desc->isStrategyActive(STRATEGY_SONIFICATION,
353 SONIFICATION_HEADSET_MUSIC_DELAY,
355 (delayMs < (int)desc->mLatency*2)) {
356 delayMs = desc->mLatency*2;
358 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
359 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
360 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
361 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
362 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
363 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
367 // change routing is necessary
368 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
370 // if entering in call state, handle special case of active streams
371 // pertaining to sonification strategy see handleIncallSonification()
372 if (isStateInCall(state)) {
373 ALOGV("setPhoneState() in call state management: new state is %d", state);
374 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
375 handleIncallSonification(stream, true, true);
379 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
380 if (state == AudioSystem::MODE_RINGTONE &&
381 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
382 mLimitRingtoneVolume = true;
384 mLimitRingtoneVolume = false;
388 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
390 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
392 bool forceVolumeReeval = false;
394 case AudioSystem::FOR_COMMUNICATION:
395 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
396 config != AudioSystem::FORCE_NONE) {
397 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
400 forceVolumeReeval = true;
401 mForceUse[usage] = config;
403 case AudioSystem::FOR_MEDIA:
404 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
405 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
406 config != AudioSystem::FORCE_ANALOG_DOCK &&
407 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
408 config != AudioSystem::FORCE_NO_BT_A2DP) {
409 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
412 mForceUse[usage] = config;
414 case AudioSystem::FOR_RECORD:
415 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
416 config != AudioSystem::FORCE_NONE) {
417 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
420 mForceUse[usage] = config;
422 case AudioSystem::FOR_DOCK:
423 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
424 config != AudioSystem::FORCE_BT_DESK_DOCK &&
425 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
426 config != AudioSystem::FORCE_ANALOG_DOCK &&
427 config != AudioSystem::FORCE_DIGITAL_DOCK) {
428 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
430 forceVolumeReeval = true;
431 mForceUse[usage] = config;
433 case AudioSystem::FOR_SYSTEM:
434 if (config != AudioSystem::FORCE_NONE &&
435 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
436 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
438 forceVolumeReeval = true;
439 mForceUse[usage] = config;
442 ALOGW("setForceUse() invalid usage %d", usage);
446 // check for device and output changes triggered by new force usage
448 checkOutputForAllStrategies();
449 updateDevicesAndOutputs();
450 for (size_t i = 0; i < mOutputs.size(); i++) {
451 audio_io_handle_t output = mOutputs.keyAt(i);
452 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
453 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
454 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
455 applyStreamVolumes(output, newDevice, 0, true);
459 audio_io_handle_t activeInput = getActiveInput();
460 if (activeInput != 0) {
461 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
462 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
463 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
464 ALOGV("setForceUse() changing device from %x to %x for input %d",
465 inputDesc->mDevice, newDevice, activeInput);
466 inputDesc->mDevice = newDevice;
467 AudioParameter param = AudioParameter();
468 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
469 mpClientInterface->setParameters(activeInput, param.toString());
475 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
477 return mForceUse[usage];
480 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
482 ALOGV("setSystemProperty() property %s, value %s", property, value);
485 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
486 audio_devices_t device,
487 uint32_t samplingRate,
489 uint32_t channelMask,
490 audio_output_flags_t flags)
492 for (size_t i = 0; i < mHwModules.size(); i++) {
493 if (mHwModules[i]->mHandle == 0) {
496 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
497 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
498 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
499 if (profile->isCompatibleProfile(device, samplingRate, format,
501 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
502 if (mAvailableOutputDevices & profile->mSupportedDevices) {
503 return mHwModules[i]->mOutputProfiles[j];
506 } else if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
507 if (profile->isCompatibleProfile(device, samplingRate, format,
509 AUDIO_OUTPUT_FLAG_DIRECT)) {
510 if (mAvailableOutputDevices & profile->mSupportedDevices) {
511 return mHwModules[i]->mOutputProfiles[j];
520 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
521 uint32_t samplingRate,
523 uint32_t channelMask,
524 AudioSystem::output_flags flags,
525 const audio_offload_info_t *offloadInfo)
527 audio_io_handle_t output = 0;
528 uint32_t latency = 0;
529 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
530 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
531 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
532 device, stream, samplingRate, format, channelMask, flags);
534 #ifdef AUDIO_POLICY_TEST
535 if (mCurOutput != 0) {
536 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
537 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
539 if (mTestOutputs[mCurOutput] == 0) {
540 ALOGV("getOutput() opening test output");
541 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
542 outputDesc->mDevice = mTestDevice;
543 outputDesc->mSamplingRate = mTestSamplingRate;
544 outputDesc->mFormat = mTestFormat;
545 outputDesc->mChannelMask = mTestChannels;
546 outputDesc->mLatency = mTestLatencyMs;
547 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
548 outputDesc->mRefCount[stream] = 0;
549 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
550 &outputDesc->mSamplingRate,
551 &outputDesc->mFormat,
552 &outputDesc->mChannelMask,
553 &outputDesc->mLatency,
556 if (mTestOutputs[mCurOutput]) {
557 AudioParameter outputCmd = AudioParameter();
558 outputCmd.addInt(String8("set_id"),mCurOutput);
559 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
560 addOutput(mTestOutputs[mCurOutput], outputDesc);
563 return mTestOutputs[mCurOutput];
565 #endif //AUDIO_POLICY_TEST
567 // open a direct output if required by specified parameters
568 //force direct flag if offload flag is set: offloading implies a direct output stream
569 // and all common behaviors are driven by checking only the direct flag
570 // this should normally be set appropriately in the policy configuration file
571 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
572 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
575 IOProfile *profile = getProfileForDirectOutput(device,
579 (audio_output_flags_t)flags);
580 if (profile != NULL) {
581 AudioOutputDescriptor *outputDesc = NULL;
583 for (size_t i = 0; i < mOutputs.size(); i++) {
584 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
585 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
587 // reuse direct output if currently open and configured with same parameters
588 if ((samplingRate == outputDesc->mSamplingRate) &&
589 (format == outputDesc->mFormat) &&
590 (channelMask == outputDesc->mChannelMask)) {
591 outputDesc->mDirectOpenCount++;
592 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
593 return mOutputs.keyAt(i);
597 // close direct output if currently open and configured with different parameters
598 if (outputDesc != NULL) {
599 closeOutput(outputDesc->mId);
601 outputDesc = new AudioOutputDescriptor(profile);
602 outputDesc->mDevice = device;
603 outputDesc->mSamplingRate = samplingRate;
604 outputDesc->mFormat = (audio_format_t)format;
605 outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
606 outputDesc->mLatency = 0;
607 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
608 outputDesc->mRefCount[stream] = 0;
609 outputDesc->mStopTime[stream] = 0;
610 outputDesc->mDirectOpenCount = 1;
611 output = mpClientInterface->openOutput(profile->mModule->mHandle,
612 &outputDesc->mDevice,
613 &outputDesc->mSamplingRate,
614 &outputDesc->mFormat,
615 &outputDesc->mChannelMask,
616 &outputDesc->mLatency,
620 // only accept an output with the requested parameters
622 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
623 (format != 0 && format != outputDesc->mFormat) ||
624 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
625 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
626 "format %d %d, channelMask %04x %04x", output, samplingRate,
627 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
628 outputDesc->mChannelMask);
630 mpClientInterface->closeOutput(output);
635 audio_io_handle_t srcOutput = getOutputForEffect();
636 addOutput(output, outputDesc);
637 audio_io_handle_t dstOutput = getOutputForEffect();
638 if (dstOutput == output) {
639 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
641 mPreviousOutputs = mOutputs;
642 ALOGV("getOutput() returns new direct output %d", output);
646 // ignoring channel mask due to downmix capability in mixer
648 // open a non direct output
650 // for non direct outputs, only PCM is supported
651 if (audio_is_linear_pcm((audio_format_t)format)) {
652 // get which output is suitable for the specified stream. The actual
653 // routing change will happen when startOutput() will be called
654 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
656 output = selectOutput(outputs, flags);
658 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
659 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
661 ALOGV("getOutput() returns output %d", output);
666 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
667 AudioSystem::output_flags flags)
669 // select one output among several that provide a path to a particular device or set of
670 // devices (the list was previously build by getOutputsForDevice()).
671 // The priority is as follows:
672 // 1: the output with the highest number of requested policy flags
673 // 2: the primary output
674 // 3: the first output in the list
676 if (outputs.size() == 0) {
679 if (outputs.size() == 1) {
683 int maxCommonFlags = 0;
684 audio_io_handle_t outputFlags = 0;
685 audio_io_handle_t outputPrimary = 0;
687 for (size_t i = 0; i < outputs.size(); i++) {
688 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
689 if (!outputDesc->isDuplicated()) {
690 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
691 if (commonFlags > maxCommonFlags) {
692 outputFlags = outputs[i];
693 maxCommonFlags = commonFlags;
694 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
696 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
697 outputPrimary = outputs[i];
702 if (outputFlags != 0) {
705 if (outputPrimary != 0) {
706 return outputPrimary;
712 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
713 AudioSystem::stream_type stream,
716 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
717 ssize_t index = mOutputs.indexOfKey(output);
719 ALOGW("startOutput() unknow output %d", output);
723 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
725 // increment usage count for this stream on the requested output:
726 // NOTE that the usage count is the same for duplicated output and hardware output which is
727 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
728 outputDesc->changeRefCount(stream, 1);
730 if (outputDesc->mRefCount[stream] == 1) {
731 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
732 routing_strategy strategy = getStrategy(stream);
733 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
734 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
737 for (size_t i = 0; i < mOutputs.size(); i++) {
738 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
739 if (desc != outputDesc) {
740 // force a device change if any other output is managed by the same hw
741 // module and has a current device selection that differs from selected device.
742 // In this case, the audio HAL must receive the new device selection so that it can
743 // change the device currently selected by the other active output.
744 if (outputDesc->sharesHwModuleWith(desc) &&
745 desc->device() != newDevice) {
748 // wait for audio on other active outputs to be presented when starting
749 // a notification so that audio focus effect can propagate.
750 uint32_t latency = desc->latency();
751 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
756 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
758 // handle special case for sonification while in call
760 handleIncallSonification(stream, true, false);
763 // apply volume rules for current stream and device if necessary
764 checkAndSetVolume(stream,
765 mStreams[stream].getVolumeIndex(newDevice),
769 // update the outputs if starting an output with a stream that can affect notification
771 handleNotificationRoutingForStream(stream);
772 if (waitMs > muteWaitMs) {
773 usleep((waitMs - muteWaitMs) * 2 * 1000);
780 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
781 AudioSystem::stream_type stream,
784 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
785 ssize_t index = mOutputs.indexOfKey(output);
787 ALOGW("stopOutput() unknow output %d", output);
791 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
793 // handle special case for sonification while in call
795 handleIncallSonification(stream, false, false);
798 if (outputDesc->mRefCount[stream] > 0) {
799 // decrement usage count of this stream on the output
800 outputDesc->changeRefCount(stream, -1);
801 // store time at which the stream was stopped - see isStreamActive()
802 if (outputDesc->mRefCount[stream] == 0) {
803 outputDesc->mStopTime[stream] = systemTime();
804 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
805 // delay the device switch by twice the latency because stopOutput() is executed when
806 // the track stop() command is received and at that time the audio track buffer can
807 // still contain data that needs to be drained. The latency only covers the audio HAL
808 // and kernel buffers. Also the latency does not always include additional delay in the
809 // audio path (audio DSP, CODEC ...)
810 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
812 // force restoring the device selection on other active outputs if it differs from the
813 // one being selected for this output
814 for (size_t i = 0; i < mOutputs.size(); i++) {
815 audio_io_handle_t curOutput = mOutputs.keyAt(i);
816 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
817 if (curOutput != output &&
819 outputDesc->sharesHwModuleWith(desc) &&
820 (newDevice != desc->device())) {
821 setOutputDevice(curOutput,
822 getNewDevice(curOutput, false /*fromCache*/),
824 outputDesc->mLatency*2);
827 // update the outputs if stopping one with a stream that can affect notification routing
828 handleNotificationRoutingForStream(stream);
832 ALOGW("stopOutput() refcount is already 0 for output %d", output);
833 return INVALID_OPERATION;
837 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
839 ALOGV("releaseOutput() %d", output);
840 ssize_t index = mOutputs.indexOfKey(output);
842 ALOGW("releaseOutput() releasing unknown output %d", output);
846 #ifdef AUDIO_POLICY_TEST
847 int testIndex = testOutputIndex(output);
848 if (testIndex != 0) {
849 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
850 if (outputDesc->isActive()) {
851 mpClientInterface->closeOutput(output);
852 delete mOutputs.valueAt(index);
853 mOutputs.removeItem(output);
854 mTestOutputs[testIndex] = 0;
858 #endif //AUDIO_POLICY_TEST
860 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
861 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
862 if (desc->mDirectOpenCount <= 0) {
863 ALOGW("releaseOutput() invalid open count %d for output %d",
864 desc->mDirectOpenCount, output);
867 if (--desc->mDirectOpenCount == 0) {
869 // If effects where present on the output, audioflinger moved them to the primary
870 // output by default: move them back to the appropriate output.
871 audio_io_handle_t dstOutput = getOutputForEffect();
872 if (dstOutput != mPrimaryOutput) {
873 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
880 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
881 uint32_t samplingRate,
883 uint32_t channelMask,
884 AudioSystem::audio_in_acoustics acoustics)
886 audio_io_handle_t input = 0;
887 audio_devices_t device = getDeviceForInputSource(inputSource);
889 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
890 inputSource, samplingRate, format, channelMask, acoustics);
892 if (device == AUDIO_DEVICE_NONE) {
893 ALOGW("getInput() could not find device for inputSource %d", inputSource);
897 // adapt channel selection to input source
898 switch(inputSource) {
899 case AUDIO_SOURCE_VOICE_UPLINK:
900 channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
902 case AUDIO_SOURCE_VOICE_DOWNLINK:
903 channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
905 case AUDIO_SOURCE_VOICE_CALL:
906 channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
912 IOProfile *profile = getInputProfile(device,
916 if (profile == NULL) {
917 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
919 device, samplingRate, format, channelMask);
923 if (profile->mModule->mHandle == 0) {
924 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
928 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
930 inputDesc->mInputSource = inputSource;
931 inputDesc->mDevice = device;
932 inputDesc->mSamplingRate = samplingRate;
933 inputDesc->mFormat = (audio_format_t)format;
934 inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
935 inputDesc->mRefCount = 0;
936 input = mpClientInterface->openInput(profile->mModule->mHandle,
938 &inputDesc->mSamplingRate,
940 &inputDesc->mChannelMask);
942 // only accept input with the exact requested set of parameters
944 (samplingRate != inputDesc->mSamplingRate) ||
945 (format != inputDesc->mFormat) ||
946 (channelMask != inputDesc->mChannelMask)) {
947 ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
948 samplingRate, format, channelMask);
950 mpClientInterface->closeInput(input);
955 mInputs.add(input, inputDesc);
959 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
961 ALOGV("startInput() input %d", input);
962 ssize_t index = mInputs.indexOfKey(input);
964 ALOGW("startInput() unknow input %d", input);
967 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
969 #ifdef AUDIO_POLICY_TEST
971 #endif //AUDIO_POLICY_TEST
973 // refuse 2 active AudioRecord clients at the same time except if the active input
974 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
975 audio_io_handle_t activeInput = getActiveInput();
976 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
977 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
978 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
979 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
980 stopInput(activeInput);
981 releaseInput(activeInput);
983 ALOGW("startInput() input %d failed: other input already started..", input);
984 return INVALID_OPERATION;
989 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
990 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
991 inputDesc->mDevice = newDevice;
994 // automatically enable the remote submix output when input is started
995 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
996 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
997 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1000 AudioParameter param = AudioParameter();
1001 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1003 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1004 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1006 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1007 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1009 mpClientInterface->setParameters(input, param.toString());
1011 inputDesc->mRefCount = 1;
1015 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
1017 ALOGV("stopInput() input %d", input);
1018 ssize_t index = mInputs.indexOfKey(input);
1020 ALOGW("stopInput() unknow input %d", input);
1023 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1025 if (inputDesc->mRefCount == 0) {
1026 ALOGW("stopInput() input %d already stopped", input);
1027 return INVALID_OPERATION;
1029 // automatically disable the remote submix output when input is stopped
1030 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1031 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1032 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1035 AudioParameter param = AudioParameter();
1036 param.addInt(String8(AudioParameter::keyRouting), 0);
1037 mpClientInterface->setParameters(input, param.toString());
1038 inputDesc->mRefCount = 0;
1043 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1045 ALOGV("releaseInput() %d", input);
1046 ssize_t index = mInputs.indexOfKey(input);
1048 ALOGW("releaseInput() releasing unknown input %d", input);
1051 mpClientInterface->closeInput(input);
1052 delete mInputs.valueAt(index);
1053 mInputs.removeItem(input);
1054 ALOGV("releaseInput() exit");
1057 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1061 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1062 if (indexMin < 0 || indexMin >= indexMax) {
1063 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1066 mStreams[stream].mIndexMin = indexMin;
1067 mStreams[stream].mIndexMax = indexMax;
1070 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1072 audio_devices_t device)
1075 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1078 if (!audio_is_output_device(device)) {
1082 // Force max volume if stream cannot be muted
1083 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1085 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1086 stream, device, index);
1088 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1089 // clear all device specific values
1090 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1091 mStreams[stream].mIndexCur.clear();
1093 mStreams[stream].mIndexCur.add(device, index);
1095 // compute and apply stream volume on all outputs according to connected device
1096 status_t status = NO_ERROR;
1097 for (size_t i = 0; i < mOutputs.size(); i++) {
1098 audio_devices_t curDevice =
1099 getDeviceForVolume(mOutputs.valueAt(i)->device());
1100 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1101 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1102 if (volStatus != NO_ERROR) {
1110 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1112 audio_devices_t device)
1114 if (index == NULL) {
1117 if (!audio_is_output_device(device)) {
1120 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1121 // the strategy the stream belongs to.
1122 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1123 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1125 device = getDeviceForVolume(device);
1127 *index = mStreams[stream].getVolumeIndex(device);
1128 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1132 audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
1133 const SortedVector<audio_io_handle_t>& outputs)
1135 // select one output among several suitable for global effects.
1136 // The priority is as follows:
1137 // 1: An offloaded output. If the effect ends up not being offloadable,
1138 // AudioFlinger will invalidate the track and the offloaded output
1139 // will be closed causing the effect to be moved to a PCM output.
1140 // 2: A deep buffer output
1141 // 3: the first output in the list
1143 if (outputs.size() == 0) {
1147 audio_io_handle_t outputOffloaded = 0;
1148 audio_io_handle_t outputDeepBuffer = 0;
1150 for (size_t i = 0; i < outputs.size(); i++) {
1151 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1152 ALOGV("selectOutputForEffects outputs[%d] flags %x", i, desc->mFlags);
1153 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1154 outputOffloaded = outputs[i];
1156 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1157 outputDeepBuffer = outputs[i];
1161 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1162 outputOffloaded, outputDeepBuffer);
1163 if (outputOffloaded != 0) {
1164 return outputOffloaded;
1166 if (outputDeepBuffer != 0) {
1167 return outputDeepBuffer;
1173 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1175 // apply simple rule where global effects are attached to the same output as MUSIC streams
1177 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1178 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1179 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1181 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1182 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1183 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1188 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1189 audio_io_handle_t io,
1194 ssize_t index = mOutputs.indexOfKey(io);
1196 index = mInputs.indexOfKey(io);
1198 ALOGW("registerEffect() unknown io %d", io);
1199 return INVALID_OPERATION;
1203 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1204 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1205 desc->name, desc->memoryUsage);
1206 return INVALID_OPERATION;
1208 mTotalEffectsMemory += desc->memoryUsage;
1209 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1210 desc->name, io, strategy, session, id);
1211 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1213 EffectDescriptor *pDesc = new EffectDescriptor();
1214 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1216 pDesc->mStrategy = (routing_strategy)strategy;
1217 pDesc->mSession = session;
1218 pDesc->mEnabled = false;
1220 mEffects.add(id, pDesc);
1225 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1227 ssize_t index = mEffects.indexOfKey(id);
1229 ALOGW("unregisterEffect() unknown effect ID %d", id);
1230 return INVALID_OPERATION;
1233 EffectDescriptor *pDesc = mEffects.valueAt(index);
1235 setEffectEnabled(pDesc, false);
1237 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1238 ALOGW("unregisterEffect() memory %d too big for total %d",
1239 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1240 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1242 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1243 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1244 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1246 mEffects.removeItem(id);
1252 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1254 ssize_t index = mEffects.indexOfKey(id);
1256 ALOGW("unregisterEffect() unknown effect ID %d", id);
1257 return INVALID_OPERATION;
1260 return setEffectEnabled(mEffects.valueAt(index), enabled);
1263 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1265 if (enabled == pDesc->mEnabled) {
1266 ALOGV("setEffectEnabled(%s) effect already %s",
1267 enabled?"true":"false", enabled?"enabled":"disabled");
1268 return INVALID_OPERATION;
1272 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1273 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1274 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1275 return INVALID_OPERATION;
1277 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1278 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1280 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1281 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1282 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1283 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1285 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1286 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1288 pDesc->mEnabled = enabled;
1292 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1294 nsecs_t sysTime = systemTime();
1295 for (size_t i = 0; i < mOutputs.size(); i++) {
1296 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1297 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1304 bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1306 nsecs_t sysTime = systemTime();
1307 for (size_t i = 0; i < mOutputs.size(); i++) {
1308 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1309 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1310 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1317 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1319 for (size_t i = 0; i < mInputs.size(); i++) {
1320 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1321 if ((inputDescriptor->mInputSource == (int)source ||
1322 (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
1323 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1324 && (inputDescriptor->mRefCount > 0)) {
1332 status_t AudioPolicyManagerBase::dump(int fd)
1334 const size_t SIZE = 256;
1338 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1339 result.append(buffer);
1341 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1342 result.append(buffer);
1343 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1344 result.append(buffer);
1345 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1346 result.append(buffer);
1347 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1348 result.append(buffer);
1349 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1350 result.append(buffer);
1351 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1352 result.append(buffer);
1353 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1354 result.append(buffer);
1355 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1356 result.append(buffer);
1357 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1358 result.append(buffer);
1359 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1360 result.append(buffer);
1361 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1362 result.append(buffer);
1363 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1364 result.append(buffer);
1365 write(fd, result.string(), result.size());
1368 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1369 write(fd, buffer, strlen(buffer));
1370 for (size_t i = 0; i < mHwModules.size(); i++) {
1371 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1372 write(fd, buffer, strlen(buffer));
1373 mHwModules[i]->dump(fd);
1376 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1377 write(fd, buffer, strlen(buffer));
1378 for (size_t i = 0; i < mOutputs.size(); i++) {
1379 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1380 write(fd, buffer, strlen(buffer));
1381 mOutputs.valueAt(i)->dump(fd);
1384 snprintf(buffer, SIZE, "\nInputs dump:\n");
1385 write(fd, buffer, strlen(buffer));
1386 for (size_t i = 0; i < mInputs.size(); i++) {
1387 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1388 write(fd, buffer, strlen(buffer));
1389 mInputs.valueAt(i)->dump(fd);
1392 snprintf(buffer, SIZE, "\nStreams dump:\n");
1393 write(fd, buffer, strlen(buffer));
1394 snprintf(buffer, SIZE,
1395 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1396 write(fd, buffer, strlen(buffer));
1397 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1398 snprintf(buffer, SIZE, " %02d ", i);
1399 write(fd, buffer, strlen(buffer));
1400 mStreams[i].dump(fd);
1403 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1404 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1405 write(fd, buffer, strlen(buffer));
1407 snprintf(buffer, SIZE, "Registered effects:\n");
1408 write(fd, buffer, strlen(buffer));
1409 for (size_t i = 0; i < mEffects.size(); i++) {
1410 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1411 write(fd, buffer, strlen(buffer));
1412 mEffects.valueAt(i)->dump(fd);
1419 // This function checks for the parameters which can be offloaded.
1420 // This can be enhanced depending on the capability of the DSP and policy
1422 bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1424 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1425 " BitRate=%u, duration=%lld us, has_video=%d",
1426 offloadInfo.sample_rate, offloadInfo.channel_mask,
1428 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1429 offloadInfo.has_video);
1431 // Check if offload has been disabled
1432 char propValue[PROPERTY_VALUE_MAX];
1433 if (property_get("audio.offload.disable", propValue, "0")) {
1434 if (atoi(propValue) != 0) {
1435 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1440 // Check if stream type is music, then only allow offload as of now.
1441 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1443 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1447 //TODO: enable audio offloading with video when ready
1448 if (offloadInfo.has_video)
1450 ALOGV("isOffloadSupported: has_video == true, returning false");
1454 //If duration is less than minimum value defined in property, return false
1455 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1456 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1457 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1460 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1461 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1465 // See if there is a profile to support this.
1466 // AUDIO_DEVICE_NONE
1467 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1468 offloadInfo.sample_rate,
1470 offloadInfo.channel_mask,
1471 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1472 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1473 return (profile != NULL);
1476 // ----------------------------------------------------------------------------
1477 // AudioPolicyManagerBase
1478 // ----------------------------------------------------------------------------
1480 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1482 #ifdef AUDIO_POLICY_TEST
1484 #endif //AUDIO_POLICY_TEST
1485 mPrimaryOutput((audio_io_handle_t)0),
1486 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1487 mPhoneState(AudioSystem::MODE_NORMAL),
1488 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1489 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1490 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false)
1492 mpClientInterface = clientInterface;
1494 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1495 mForceUse[i] = AudioSystem::FORCE_NONE;
1498 initializeVolumeCurves();
1500 mA2dpDeviceAddress = String8("");
1501 mScoDeviceAddress = String8("");
1502 mUsbCardAndDevice = String8("");
1504 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1505 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1506 ALOGE("could not load audio policy configuration file, setting defaults");
1507 defaultAudioPolicyConfig();
1511 // open all output streams needed to access attached devices
1512 for (size_t i = 0; i < mHwModules.size(); i++) {
1513 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1514 if (mHwModules[i]->mHandle == 0) {
1515 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1518 // open all output streams needed to access attached devices
1519 // except for direct output streams that are only opened when they are actually
1520 // required by an app.
1521 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1523 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1525 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1526 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1527 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1528 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1529 outProfile->mSupportedDevices);
1530 audio_io_handle_t output = mpClientInterface->openOutput(
1531 outProfile->mModule->mHandle,
1532 &outputDesc->mDevice,
1533 &outputDesc->mSamplingRate,
1534 &outputDesc->mFormat,
1535 &outputDesc->mChannelMask,
1536 &outputDesc->mLatency,
1537 outputDesc->mFlags);
1541 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1542 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1543 if (mPrimaryOutput == 0 &&
1544 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1545 mPrimaryOutput = output;
1547 addOutput(output, outputDesc);
1548 setOutputDevice(output,
1549 (audio_devices_t)(mDefaultOutputDevice &
1550 outProfile->mSupportedDevices),
1557 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1558 "Not output found for attached devices %08x",
1559 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1561 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1563 updateDevicesAndOutputs();
1565 #ifdef AUDIO_POLICY_TEST
1566 if (mPrimaryOutput != 0) {
1567 AudioParameter outputCmd = AudioParameter();
1568 outputCmd.addInt(String8("set_id"), 0);
1569 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1571 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1572 mTestSamplingRate = 44100;
1573 mTestFormat = AudioSystem::PCM_16_BIT;
1574 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1577 mDirectOutput = false;
1578 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1579 mTestOutputs[i] = 0;
1582 const size_t SIZE = 256;
1584 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1585 run(buffer, ANDROID_PRIORITY_AUDIO);
1587 #endif //AUDIO_POLICY_TEST
1590 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1592 #ifdef AUDIO_POLICY_TEST
1594 #endif //AUDIO_POLICY_TEST
1595 for (size_t i = 0; i < mOutputs.size(); i++) {
1596 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1597 delete mOutputs.valueAt(i);
1599 for (size_t i = 0; i < mInputs.size(); i++) {
1600 mpClientInterface->closeInput(mInputs.keyAt(i));
1601 delete mInputs.valueAt(i);
1603 for (size_t i = 0; i < mHwModules.size(); i++) {
1604 delete mHwModules[i];
1608 status_t AudioPolicyManagerBase::initCheck()
1610 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1613 #ifdef AUDIO_POLICY_TEST
1614 bool AudioPolicyManagerBase::threadLoop()
1616 ALOGV("entering threadLoop()");
1617 while (!exitPending())
1623 Mutex::Autolock _l(mLock);
1624 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1626 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1627 AudioParameter param = AudioParameter(command);
1629 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1631 ALOGV("Test command %s received", command.string());
1633 if (param.get(String8("target"), target) != NO_ERROR) {
1636 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1637 param.remove(String8("test_cmd_policy_output"));
1638 mCurOutput = valueInt;
1640 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1641 param.remove(String8("test_cmd_policy_direct"));
1642 if (value == "false") {
1643 mDirectOutput = false;
1644 } else if (value == "true") {
1645 mDirectOutput = true;
1648 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1649 param.remove(String8("test_cmd_policy_input"));
1650 mTestInput = valueInt;
1653 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1654 param.remove(String8("test_cmd_policy_format"));
1655 int format = AudioSystem::INVALID_FORMAT;
1656 if (value == "PCM 16 bits") {
1657 format = AudioSystem::PCM_16_BIT;
1658 } else if (value == "PCM 8 bits") {
1659 format = AudioSystem::PCM_8_BIT;
1660 } else if (value == "Compressed MP3") {
1661 format = AudioSystem::MP3;
1663 if (format != AudioSystem::INVALID_FORMAT) {
1664 if (target == "Manager") {
1665 mTestFormat = format;
1666 } else if (mTestOutputs[mCurOutput] != 0) {
1667 AudioParameter outputParam = AudioParameter();
1668 outputParam.addInt(String8("format"), format);
1669 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1673 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1674 param.remove(String8("test_cmd_policy_channels"));
1677 if (value == "Channels Stereo") {
1678 channels = AudioSystem::CHANNEL_OUT_STEREO;
1679 } else if (value == "Channels Mono") {
1680 channels = AudioSystem::CHANNEL_OUT_MONO;
1682 if (channels != 0) {
1683 if (target == "Manager") {
1684 mTestChannels = channels;
1685 } else if (mTestOutputs[mCurOutput] != 0) {
1686 AudioParameter outputParam = AudioParameter();
1687 outputParam.addInt(String8("channels"), channels);
1688 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1692 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1693 param.remove(String8("test_cmd_policy_sampleRate"));
1694 if (valueInt >= 0 && valueInt <= 96000) {
1695 int samplingRate = valueInt;
1696 if (target == "Manager") {
1697 mTestSamplingRate = samplingRate;
1698 } else if (mTestOutputs[mCurOutput] != 0) {
1699 AudioParameter outputParam = AudioParameter();
1700 outputParam.addInt(String8("sampling_rate"), samplingRate);
1701 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1706 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1707 param.remove(String8("test_cmd_policy_reopen"));
1709 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1710 mpClientInterface->closeOutput(mPrimaryOutput);
1712 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1714 delete mOutputs.valueFor(mPrimaryOutput);
1715 mOutputs.removeItem(mPrimaryOutput);
1717 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1718 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1719 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1720 &outputDesc->mDevice,
1721 &outputDesc->mSamplingRate,
1722 &outputDesc->mFormat,
1723 &outputDesc->mChannelMask,
1724 &outputDesc->mLatency,
1725 outputDesc->mFlags);
1726 if (mPrimaryOutput == 0) {
1727 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1728 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1730 AudioParameter outputCmd = AudioParameter();
1731 outputCmd.addInt(String8("set_id"), 0);
1732 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1733 addOutput(mPrimaryOutput, outputDesc);
1738 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1744 void AudioPolicyManagerBase::exit()
1747 AutoMutex _l(mLock);
1749 mWaitWorkCV.signal();
1751 requestExitAndWait();
1754 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1756 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1757 if (output == mTestOutputs[i]) return i;
1761 #endif //AUDIO_POLICY_TEST
1765 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1767 outputDesc->mId = id;
1768 mOutputs.add(id, outputDesc);
1772 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1773 AudioSystem::device_connection_state state,
1774 SortedVector<audio_io_handle_t>& outputs)
1776 AudioOutputDescriptor *desc;
1778 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1779 // first list already open outputs that can be routed to this device
1780 for (size_t i = 0; i < mOutputs.size(); i++) {
1781 desc = mOutputs.valueAt(i);
1782 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1783 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1784 outputs.add(mOutputs.keyAt(i));
1787 // then look for output profiles that can be routed to this device
1788 SortedVector<IOProfile *> profiles;
1789 for (size_t i = 0; i < mHwModules.size(); i++)
1791 if (mHwModules[i]->mHandle == 0) {
1794 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1796 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1797 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1798 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1803 if (profiles.isEmpty() && outputs.isEmpty()) {
1804 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1808 // open outputs for matching profiles if needed. Direct outputs are also opened to
1809 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1810 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1811 IOProfile *profile = profiles[profile_index];
1813 // nothing to do if one output is already opened for this profile
1815 for (j = 0; j < mOutputs.size(); j++) {
1816 desc = mOutputs.valueAt(j);
1817 if (!desc->isDuplicated() && desc->mProfile == profile) {
1821 if (j != mOutputs.size()) {
1825 ALOGV("opening output for device %08x", device);
1826 desc = new AudioOutputDescriptor(profile);
1827 desc->mDevice = device;
1828 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1830 &desc->mSamplingRate,
1832 &desc->mChannelMask,
1836 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1839 if (profile->mSamplingRates[0] == 0) {
1840 reply = mpClientInterface->getParameters(output,
1841 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1842 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1844 value = strpbrk((char *)reply.string(), "=");
1845 if (value != NULL) {
1846 loadSamplingRates(value + 1, profile);
1849 if (profile->mFormats[0] == 0) {
1850 reply = mpClientInterface->getParameters(output,
1851 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1852 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1854 value = strpbrk((char *)reply.string(), "=");
1855 if (value != NULL) {
1856 loadFormats(value + 1, profile);
1859 if (profile->mChannelMasks[0] == 0) {
1860 reply = mpClientInterface->getParameters(output,
1861 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1862 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1864 value = strpbrk((char *)reply.string(), "=");
1865 if (value != NULL) {
1866 loadOutChannels(value + 1, profile);
1869 if (((profile->mSamplingRates[0] == 0) &&
1870 (profile->mSamplingRates.size() < 2)) ||
1871 ((profile->mFormats[0] == 0) &&
1872 (profile->mFormats.size() < 2)) ||
1873 ((profile->mFormats[0] == 0) &&
1874 (profile->mChannelMasks.size() < 2))) {
1875 ALOGW("checkOutputsForDevice() direct output missing param");
1876 mpClientInterface->closeOutput(output);
1879 addOutput(output, desc);
1882 audio_io_handle_t duplicatedOutput = 0;
1883 // add output descriptor
1884 addOutput(output, desc);
1885 // set initial stream volume for device
1886 applyStreamVolumes(output, device, 0, true);
1888 //TODO: configure audio effect output stage here
1890 // open a duplicating output thread for the new output and the primary output
1891 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1893 if (duplicatedOutput != 0) {
1894 // add duplicated output descriptor
1895 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1896 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1897 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1898 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1899 dupOutputDesc->mFormat = desc->mFormat;
1900 dupOutputDesc->mChannelMask = desc->mChannelMask;
1901 dupOutputDesc->mLatency = desc->mLatency;
1902 addOutput(duplicatedOutput, dupOutputDesc);
1903 applyStreamVolumes(duplicatedOutput, device, 0, true);
1905 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1906 mPrimaryOutput, output);
1907 mpClientInterface->closeOutput(output);
1908 mOutputs.removeItem(output);
1914 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1916 profiles.removeAt(profile_index);
1919 outputs.add(output);
1920 ALOGV("checkOutputsForDevice(): adding output %d", output);
1924 if (profiles.isEmpty()) {
1925 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1929 // check if one opened output is not needed any more after disconnecting one device
1930 for (size_t i = 0; i < mOutputs.size(); i++) {
1931 desc = mOutputs.valueAt(i);
1932 if (!desc->isDuplicated() &&
1933 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1934 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1935 outputs.add(mOutputs.keyAt(i));
1938 for (size_t i = 0; i < mHwModules.size(); i++)
1940 if (mHwModules[i]->mHandle == 0) {
1943 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1945 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1946 if ((profile->mSupportedDevices & device) &&
1947 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1948 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1950 if (profile->mSamplingRates[0] == 0) {
1951 profile->mSamplingRates.clear();
1952 profile->mSamplingRates.add(0);
1954 if (profile->mFormats[0] == 0) {
1955 profile->mFormats.clear();
1956 profile->mFormats.add((audio_format_t)0);
1958 if (profile->mChannelMasks[0] == 0) {
1959 profile->mChannelMasks.clear();
1960 profile->mChannelMasks.add((audio_channel_mask_t)0);
1969 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1971 ALOGV("closeOutput(%d)", output);
1973 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1974 if (outputDesc == NULL) {
1975 ALOGW("closeOutput() unknown output %d", output);
1979 // look for duplicated outputs connected to the output being removed.
1980 for (size_t i = 0; i < mOutputs.size(); i++) {
1981 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1982 if (dupOutputDesc->isDuplicated() &&
1983 (dupOutputDesc->mOutput1 == outputDesc ||
1984 dupOutputDesc->mOutput2 == outputDesc)) {
1985 AudioOutputDescriptor *outputDesc2;
1986 if (dupOutputDesc->mOutput1 == outputDesc) {
1987 outputDesc2 = dupOutputDesc->mOutput2;
1989 outputDesc2 = dupOutputDesc->mOutput1;
1991 // As all active tracks on duplicated output will be deleted,
1992 // and as they were also referenced on the other output, the reference
1993 // count for their stream type must be adjusted accordingly on
1994 // the other output.
1995 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1996 int refCount = dupOutputDesc->mRefCount[j];
1997 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1999 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2000 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2002 mpClientInterface->closeOutput(duplicatedOutput);
2003 delete mOutputs.valueFor(duplicatedOutput);
2004 mOutputs.removeItem(duplicatedOutput);
2008 AudioParameter param;
2009 param.add(String8("closing"), String8("true"));
2010 mpClientInterface->setParameters(output, param.toString());
2012 mpClientInterface->closeOutput(output);
2014 mOutputs.removeItem(output);
2015 mPreviousOutputs = mOutputs;
2018 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
2019 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2021 SortedVector<audio_io_handle_t> outputs;
2023 ALOGVV("getOutputsForDevice() device %04x", device);
2024 for (size_t i = 0; i < openOutputs.size(); i++) {
2025 ALOGVV("output %d isDuplicated=%d device=%04x",
2026 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2027 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2028 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2029 outputs.add(openOutputs.keyAt(i));
2035 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2036 SortedVector<audio_io_handle_t>& outputs2)
2038 if (outputs1.size() != outputs2.size()) {
2041 for (size_t i = 0; i < outputs1.size(); i++) {
2042 if (outputs1[i] != outputs2[i]) {
2049 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
2051 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2052 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2053 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2054 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2056 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2057 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2058 strategy, srcOutputs[0], dstOutputs[0]);
2059 // mute strategy while moving tracks from one output to another
2060 for (size_t i = 0; i < srcOutputs.size(); i++) {
2061 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2062 if (desc->isStrategyActive(strategy)) {
2063 setStrategyMute(strategy, true, srcOutputs[i]);
2064 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2068 // Move effects associated to this strategy from previous output to new output
2069 if (strategy == STRATEGY_MEDIA) {
2070 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2071 SortedVector<audio_io_handle_t> moved;
2072 for (size_t i = 0; i < mEffects.size(); i++) {
2073 EffectDescriptor *desc = mEffects.valueAt(i);
2074 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2075 desc->mIo != fxOutput) {
2076 if (moved.indexOf(desc->mIo) < 0) {
2077 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2078 mEffects.keyAt(i), fxOutput);
2079 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2081 moved.add(desc->mIo);
2083 desc->mIo = fxOutput;
2087 // Move tracks associated to this strategy from previous output to new output
2088 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2089 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2090 //FIXME see fixme on name change
2091 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
2092 dstOutputs[0] /* ignored */);
2098 void AudioPolicyManagerBase::checkOutputForAllStrategies()
2100 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2101 checkOutputForStrategy(STRATEGY_PHONE);
2102 checkOutputForStrategy(STRATEGY_SONIFICATION);
2103 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2104 checkOutputForStrategy(STRATEGY_MEDIA);
2105 checkOutputForStrategy(STRATEGY_DTMF);
2108 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2114 for (size_t i = 0; i < mOutputs.size(); i++) {
2115 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2116 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2117 return mOutputs.keyAt(i);
2124 void AudioPolicyManagerBase::checkA2dpSuspend()
2129 audio_io_handle_t a2dpOutput = getA2dpOutput();
2130 if (a2dpOutput == 0) {
2134 // suspend A2DP output if:
2135 // (NOT already suspended) &&
2136 // ((SCO device is connected &&
2137 // (forced usage for communication || for record is SCO))) ||
2138 // (phone state is ringing || in call)
2140 // restore A2DP output if:
2141 // (Already suspended) &&
2142 // ((SCO device is NOT connected ||
2143 // (forced usage NOT for communication && NOT for record is SCO))) &&
2144 // (phone state is NOT ringing && NOT in call)
2146 if (mA2dpSuspended) {
2147 if (((mScoDeviceAddress == "") ||
2148 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2149 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2150 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2151 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2153 mpClientInterface->restoreOutput(a2dpOutput);
2154 mA2dpSuspended = false;
2157 if (((mScoDeviceAddress != "") &&
2158 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2159 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2160 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2161 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2163 mpClientInterface->suspendOutput(a2dpOutput);
2164 mA2dpSuspended = true;
2169 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2171 audio_devices_t device = AUDIO_DEVICE_NONE;
2173 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2174 // check the following by order of priority to request a routing change if necessary:
2175 // 1: the strategy enforced audible is active on the output:
2176 // use device for strategy enforced audible
2177 // 2: we are in call or the strategy phone is active on the output:
2178 // use device for strategy phone
2179 // 3: the strategy sonification is active on the output:
2180 // use device for strategy sonification
2181 // 4: the strategy "respectful" sonification is active on the output:
2182 // use device for strategy "respectful" sonification
2183 // 5: the strategy media is active on the output:
2184 // use device for strategy media
2185 // 6: the strategy DTMF is active on the output:
2186 // use device for strategy DTMF
2187 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2188 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2189 } else if (isInCall() ||
2190 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2191 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2192 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2193 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2194 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2195 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2196 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2197 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2198 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2199 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2202 ALOGV("getNewDevice() selected device %x", device);
2206 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2207 return (uint32_t)getStrategy(stream);
2210 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2211 audio_devices_t devices;
2212 // By checking the range of stream before calling getStrategy, we avoid
2213 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2214 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2215 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2216 devices = AUDIO_DEVICE_NONE;
2218 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2219 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2224 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2225 AudioSystem::stream_type stream) {
2226 // stream to strategy mapping
2228 case AudioSystem::VOICE_CALL:
2229 case AudioSystem::BLUETOOTH_SCO:
2230 return STRATEGY_PHONE;
2231 case AudioSystem::RING:
2232 case AudioSystem::ALARM:
2233 return STRATEGY_SONIFICATION;
2234 case AudioSystem::NOTIFICATION:
2235 return STRATEGY_SONIFICATION_RESPECTFUL;
2236 case AudioSystem::DTMF:
2237 return STRATEGY_DTMF;
2239 ALOGE("unknown stream type");
2240 case AudioSystem::SYSTEM:
2241 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2242 // while key clicks are played produces a poor result
2243 case AudioSystem::TTS:
2244 case AudioSystem::MUSIC:
2245 return STRATEGY_MEDIA;
2246 case AudioSystem::ENFORCED_AUDIBLE:
2247 return STRATEGY_ENFORCED_AUDIBLE;
2251 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2253 case AudioSystem::MUSIC:
2254 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2255 updateDevicesAndOutputs();
2262 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2265 uint32_t device = AUDIO_DEVICE_NONE;
2268 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2269 strategy, mDeviceForStrategy[strategy]);
2270 return mDeviceForStrategy[strategy];
2275 case STRATEGY_SONIFICATION_RESPECTFUL:
2277 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2278 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2279 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2280 // while media is playing on a remote device, use the the sonification behavior.
2281 // Note that we test this usecase before testing if media is playing because
2282 // the isStreamActive() method only informs about the activity of a stream, not
2283 // if it's for local playback. Note also that we use the same delay between both tests
2284 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2285 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2286 // while media is playing (or has recently played), use the same device
2287 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2289 // when media is not playing anymore, fall back on the sonification behavior
2290 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2297 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2298 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2301 // when in call, DTMF and PHONE strategies follow the same rules
2304 case STRATEGY_PHONE:
2305 // for phone strategy, we first consider the forced use and then the available devices by order
2307 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2308 case AudioSystem::FORCE_BT_SCO:
2309 if (!isInCall() || strategy != STRATEGY_DTMF) {
2310 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2313 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2315 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2317 // if SCO device is requested but no SCO device is available, fall back to default case
2320 default: // FORCE_NONE
2321 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2322 if (mHasA2dp && !isInCall() &&
2323 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2324 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2325 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2327 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2330 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2332 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2334 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2335 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2337 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2339 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2341 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2343 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2346 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2348 device = mDefaultOutputDevice;
2349 if (device == AUDIO_DEVICE_NONE) {
2350 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2354 case AudioSystem::FORCE_SPEAKER:
2355 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2356 // A2DP speaker when forcing to speaker output
2357 if (mHasA2dp && !isInCall() &&
2358 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2359 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2360 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2363 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2364 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2366 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2368 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2370 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2372 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2375 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2377 device = mDefaultOutputDevice;
2378 if (device == AUDIO_DEVICE_NONE) {
2379 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2385 case STRATEGY_SONIFICATION:
2387 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2388 // handleIncallSonification().
2390 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2395 case STRATEGY_ENFORCED_AUDIBLE:
2396 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2398 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2399 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2401 if ((strategy == STRATEGY_SONIFICATION) ||
2402 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2403 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2404 if (device == AUDIO_DEVICE_NONE) {
2405 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2408 // The second device used for sonification is the same as the device used by media strategy
2411 case STRATEGY_MEDIA: {
2412 uint32_t device2 = AUDIO_DEVICE_NONE;
2413 if (strategy != STRATEGY_SONIFICATION) {
2414 // no sonification on remote submix (e.g. WFD)
2415 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2417 if ((device2 == AUDIO_DEVICE_NONE) &&
2418 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2419 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2420 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2421 if (device2 == AUDIO_DEVICE_NONE) {
2422 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2424 if (device2 == AUDIO_DEVICE_NONE) {
2425 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2428 if (device2 == AUDIO_DEVICE_NONE) {
2429 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2431 if (device2 == AUDIO_DEVICE_NONE) {
2432 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2434 if (device2 == AUDIO_DEVICE_NONE) {
2435 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2437 if (device2 == AUDIO_DEVICE_NONE) {
2438 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2440 if (device2 == AUDIO_DEVICE_NONE) {
2441 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2443 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2444 // no sonification on aux digital (e.g. HDMI)
2445 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2447 if ((device2 == AUDIO_DEVICE_NONE) &&
2448 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2449 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2451 if (device2 == AUDIO_DEVICE_NONE) {
2452 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2455 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2456 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2459 device = mDefaultOutputDevice;
2460 if (device == AUDIO_DEVICE_NONE) {
2461 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2466 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2470 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2474 void AudioPolicyManagerBase::updateDevicesAndOutputs()
2476 for (int i = 0; i < NUM_STRATEGIES; i++) {
2477 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2479 mPreviousOutputs = mOutputs;
2482 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2483 audio_devices_t prevDevice,
2486 // mute/unmute strategies using an incompatible device combination
2487 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2488 // if unmuting, unmute only after the specified delay
2489 if (outputDesc->isDuplicated()) {
2493 uint32_t muteWaitMs = 0;
2494 audio_devices_t device = outputDesc->device();
2495 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2496 // temporary mute output if device selection changes to avoid volume bursts due to
2497 // different per device volumes
2498 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2500 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2501 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2502 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2503 bool doMute = false;
2505 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2507 outputDesc->mStrategyMutedByDevice[i] = true;
2508 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2510 outputDesc->mStrategyMutedByDevice[i] = false;
2512 if (doMute || tempMute) {
2513 for (size_t j = 0; j < mOutputs.size(); j++) {
2514 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2515 // skip output if it does not share any device with current output
2516 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2517 == AUDIO_DEVICE_NONE) {
2520 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2521 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2522 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2523 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2524 if (desc->isStrategyActive((routing_strategy)i)) {
2525 // do tempMute only for current output
2526 if (tempMute && (desc == outputDesc)) {
2527 setStrategyMute((routing_strategy)i, true, curOutput);
2528 setStrategyMute((routing_strategy)i, false, curOutput,
2529 desc->latency() * 2, device);
2531 if ((tempMute && (desc == outputDesc)) || mute) {
2532 if (muteWaitMs < desc->latency()) {
2533 muteWaitMs = desc->latency();
2541 // FIXME: should not need to double latency if volume could be applied immediately by the
2542 // audioflinger mixer. We must account for the delay between now and the next time
2543 // the audioflinger thread for this output will process a buffer (which corresponds to
2544 // one buffer size, usually 1/2 or 1/4 of the latency).
2546 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2547 if (muteWaitMs > delayMs) {
2548 muteWaitMs -= delayMs;
2549 usleep(muteWaitMs * 1000);
2555 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2556 audio_devices_t device,
2560 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2561 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2562 AudioParameter param;
2563 uint32_t muteWaitMs;
2565 if (outputDesc->isDuplicated()) {
2566 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2567 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2570 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2572 if ((device != AUDIO_DEVICE_NONE) &&
2573 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2577 // filter devices according to output selected
2578 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2580 audio_devices_t prevDevice = outputDesc->mDevice;
2582 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2584 if (device != AUDIO_DEVICE_NONE) {
2585 outputDesc->mDevice = device;
2587 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2589 // Do not change the routing if:
2590 // - the requested device is AUDIO_DEVICE_NONE
2591 // - the requested device is the same as current device and force is not specified.
2592 // Doing this check here allows the caller to call setOutputDevice() without conditions
2593 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2594 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2598 ALOGV("setOutputDevice() changing device");
2600 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2601 mpClientInterface->setParameters(output, param.toString(), delayMs);
2603 // update stream volumes according to new device
2604 applyStreamVolumes(output, device, delayMs);
2609 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2610 uint32_t samplingRate,
2612 uint32_t channelMask)
2614 // Choose an input profile based on the requested capture parameters: select the first available
2615 // profile supporting all requested parameters.
2617 for (size_t i = 0; i < mHwModules.size(); i++)
2619 if (mHwModules[i]->mHandle == 0) {
2622 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2624 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2625 if (profile->isCompatibleProfile(device, samplingRate, format,
2626 channelMask,(audio_output_flags_t)0)) {
2634 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2636 uint32_t device = AUDIO_DEVICE_NONE;
2638 switch (inputSource) {
2639 case AUDIO_SOURCE_VOICE_UPLINK:
2640 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2641 device = AUDIO_DEVICE_IN_VOICE_CALL;
2646 case AUDIO_SOURCE_DEFAULT:
2647 case AUDIO_SOURCE_MIC:
2648 case AUDIO_SOURCE_VOICE_RECOGNITION:
2649 case AUDIO_SOURCE_HOTWORD:
2650 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2651 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2652 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2653 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2654 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2655 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2656 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2657 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2660 case AUDIO_SOURCE_CAMCORDER:
2661 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2662 device = AUDIO_DEVICE_IN_BACK_MIC;
2663 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2664 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2667 case AUDIO_SOURCE_VOICE_DOWNLINK:
2668 case AUDIO_SOURCE_VOICE_CALL:
2669 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2670 device = AUDIO_DEVICE_IN_VOICE_CALL;
2673 case AUDIO_SOURCE_REMOTE_SUBMIX:
2674 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2675 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2679 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2682 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2686 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2688 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2689 device &= ~AUDIO_DEVICE_BIT_IN;
2690 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2696 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2698 for (size_t i = 0; i < mInputs.size(); i++) {
2699 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2700 if ((input_descriptor->mRefCount > 0)
2701 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2702 return mInputs.keyAt(i);
2709 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2711 if (device == AUDIO_DEVICE_NONE) {
2712 // this happens when forcing a route update and no track is active on an output.
2713 // In this case the returned category is not important.
2714 device = AUDIO_DEVICE_OUT_SPEAKER;
2715 } else if (AudioSystem::popCount(device) > 1) {
2716 // Multiple device selection is either:
2717 // - speaker + one other device: give priority to speaker in this case.
2718 // - one A2DP device + another device: happens with duplicated output. In this case
2719 // retain the device on the A2DP output as the other must not correspond to an active
2720 // selection if not the speaker.
2721 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2722 device = AUDIO_DEVICE_OUT_SPEAKER;
2724 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2728 ALOGW_IF(AudioSystem::popCount(device) != 1,
2729 "getDeviceForVolume() invalid device combination: %08x",
2735 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2737 switch(getDeviceForVolume(device)) {
2738 case AUDIO_DEVICE_OUT_EARPIECE:
2739 return DEVICE_CATEGORY_EARPIECE;
2740 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2741 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2742 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2743 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2744 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2745 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2746 return DEVICE_CATEGORY_HEADSET;
2747 case AUDIO_DEVICE_OUT_SPEAKER:
2748 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2749 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2750 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2751 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2752 case AUDIO_DEVICE_OUT_USB_DEVICE:
2753 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
2755 return DEVICE_CATEGORY_SPEAKER;
2759 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2762 device_category deviceCategory = getDeviceCategory(device);
2763 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2765 // the volume index in the UI is relative to the min and max volume indices for this stream type
2766 int nbSteps = 1 + curve[VOLMAX].mIndex -
2767 curve[VOLMIN].mIndex;
2768 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2769 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2771 // find what part of the curve this index volume belongs to, or if it's out of bounds
2773 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2775 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2777 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2779 } else if (volIdx <= curve[VOLMAX].mIndex) {
2781 } else { // out of bounds
2785 // linear interpolation in the attenuation table in dB
2786 float decibels = curve[segment].mDBAttenuation +
2787 ((float)(volIdx - curve[segment].mIndex)) *
2788 ( (curve[segment+1].mDBAttenuation -
2789 curve[segment].mDBAttenuation) /
2790 ((float)(curve[segment+1].mIndex -
2791 curve[segment].mIndex)) );
2793 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2795 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2796 curve[segment].mIndex, volIdx,
2797 curve[segment+1].mIndex,
2798 curve[segment].mDBAttenuation,
2800 curve[segment+1].mDBAttenuation,
2803 return amplification;
2806 const AudioPolicyManagerBase::VolumeCurvePoint
2807 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2808 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2811 const AudioPolicyManagerBase::VolumeCurvePoint
2812 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2813 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2816 const AudioPolicyManagerBase::VolumeCurvePoint
2817 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2818 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2821 const AudioPolicyManagerBase::VolumeCurvePoint
2822 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2823 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2826 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2827 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2828 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2829 const AudioPolicyManagerBase::VolumeCurvePoint
2830 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2831 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2834 const AudioPolicyManagerBase::VolumeCurvePoint
2835 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2836 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2839 const AudioPolicyManagerBase::VolumeCurvePoint
2840 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2841 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
2844 const AudioPolicyManagerBase::VolumeCurvePoint
2845 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2846 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
2849 const AudioPolicyManagerBase::VolumeCurvePoint
2850 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2851 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2852 { // AUDIO_STREAM_VOICE_CALL
2853 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2854 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2855 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2857 { // AUDIO_STREAM_SYSTEM
2858 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2859 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2860 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2862 { // AUDIO_STREAM_RING
2863 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2864 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2865 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2867 { // AUDIO_STREAM_MUSIC
2868 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2869 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2870 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2872 { // AUDIO_STREAM_ALARM
2873 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2874 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2875 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2877 { // AUDIO_STREAM_NOTIFICATION
2878 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2879 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2880 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2882 { // AUDIO_STREAM_BLUETOOTH_SCO
2883 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2884 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2885 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2887 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2888 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2889 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2890 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2892 { // AUDIO_STREAM_DTMF
2893 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2894 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2895 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2897 { // AUDIO_STREAM_TTS
2898 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2899 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2900 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2904 void AudioPolicyManagerBase::initializeVolumeCurves()
2906 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2907 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2908 mStreams[i].mVolumeCurve[j] =
2909 sVolumeProfiles[i][j];
2914 float AudioPolicyManagerBase::computeVolume(int stream,
2916 audio_io_handle_t output,
2917 audio_devices_t device)
2920 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2921 StreamDescriptor &streamDesc = mStreams[stream];
2923 if (device == AUDIO_DEVICE_NONE) {
2924 device = outputDesc->device();
2927 // if volume is not 0 (not muted), force media volume to max on digital output
2928 if (stream == AudioSystem::MUSIC &&
2929 index != mStreams[stream].mIndexMin &&
2930 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2931 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2932 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2933 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2937 volume = volIndexToAmpl(device, streamDesc, index);
2939 // if a headset is connected, apply the following rules to ring tones and notifications
2940 // to avoid sound level bursts in user's ears:
2941 // - always attenuate ring tones and notifications volume by 6dB
2942 // - if music is playing, always limit the volume to current music volume,
2943 // with a minimum threshold at -36dB so that notification is always perceived.
2944 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2945 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
2946 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2947 AUDIO_DEVICE_OUT_WIRED_HEADSET |
2948 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
2949 ((stream_strategy == STRATEGY_SONIFICATION)
2950 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2951 || (stream == AudioSystem::SYSTEM)
2952 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
2953 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
2954 streamDesc.mCanBeMuted) {
2955 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2956 // when the phone is ringing we must consider that music could have been paused just before
2957 // by the music application and behave as if music was active if the last music track was
2959 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2960 mLimitRingtoneVolume) {
2961 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
2962 float musicVol = computeVolume(AudioSystem::MUSIC,
2963 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
2966 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2967 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2968 if (volume > minVol) {
2970 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2978 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2980 audio_io_handle_t output,
2981 audio_devices_t device,
2986 // do not change actual stream volume if the stream is muted
2987 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2988 ALOGVV("checkAndSetVolume() stream %d muted count %d",
2989 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2993 // do not change in call volume if bluetooth is connected and vice versa
2994 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2995 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2996 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2997 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2998 return INVALID_OPERATION;
3001 float volume = computeVolume(stream, index, output, device);
3002 // We actually change the volume if:
3003 // - the float value returned by computeVolume() changed
3004 // - the force flag is set
3005 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3007 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3008 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3009 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3011 if (stream == AudioSystem::BLUETOOTH_SCO) {
3012 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
3014 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
3017 if (stream == AudioSystem::VOICE_CALL ||
3018 stream == AudioSystem::BLUETOOTH_SCO) {
3020 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3021 if (stream == AudioSystem::VOICE_CALL) {
3022 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3027 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3028 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3029 mLastVoiceVolume = voiceVolume;
3036 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
3037 audio_devices_t device,
3041 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3043 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3044 checkAndSetVolume(stream,
3045 mStreams[stream].getVolumeIndex(device),
3053 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
3055 audio_io_handle_t output,
3057 audio_devices_t device)
3059 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3060 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3061 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3062 setStreamMute(stream, on, output, delayMs, device);
3067 void AudioPolicyManagerBase::setStreamMute(int stream,
3069 audio_io_handle_t output,
3071 audio_devices_t device)
3073 StreamDescriptor &streamDesc = mStreams[stream];
3074 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3075 if (device == AUDIO_DEVICE_NONE) {
3076 device = outputDesc->device();
3079 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3080 stream, on, output, outputDesc->mMuteCount[stream], device);
3083 if (outputDesc->mMuteCount[stream] == 0) {
3084 if (streamDesc.mCanBeMuted &&
3085 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3086 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3087 checkAndSetVolume(stream, 0, output, device, delayMs);
3090 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3091 outputDesc->mMuteCount[stream]++;
3093 if (outputDesc->mMuteCount[stream] == 0) {
3094 ALOGV("setStreamMute() unmuting non muted stream!");
3097 if (--outputDesc->mMuteCount[stream] == 0) {
3098 checkAndSetVolume(stream,
3099 streamDesc.getVolumeIndex(device),
3107 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3109 // if the stream pertains to sonification strategy and we are in call we must
3110 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3111 // in the device used for phone strategy and play the tone if the selected device does not
3112 // interfere with the device used for phone strategy
3113 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3114 // many times as there are active tracks on the output
3115 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3116 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3117 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3118 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3119 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3120 stream, starting, outputDesc->mDevice, stateChange);
3121 if (outputDesc->mRefCount[stream]) {
3124 muteCount = outputDesc->mRefCount[stream];
3126 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3127 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3128 for (int i = 0; i < muteCount; i++) {
3129 setStreamMute(stream, starting, mPrimaryOutput);
3132 ALOGV("handleIncallSonification() high visibility");
3133 if (outputDesc->device() &
3134 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3135 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3136 for (int i = 0; i < muteCount; i++) {
3137 setStreamMute(stream, starting, mPrimaryOutput);
3141 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3143 mpClientInterface->stopTone();
3150 bool AudioPolicyManagerBase::isInCall()
3152 return isStateInCall(mPhoneState);
3155 bool AudioPolicyManagerBase::isStateInCall(int state) {
3156 return ((state == AudioSystem::MODE_IN_CALL) ||
3157 (state == AudioSystem::MODE_IN_COMMUNICATION));
3160 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3162 return MAX_EFFECTS_CPU_LOAD;
3165 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3167 return MAX_EFFECTS_MEMORY;
3170 // --- AudioOutputDescriptor class implementation
3172 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3173 const IOProfile *profile)
3174 : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
3175 mChannelMask((audio_channel_mask_t)0), mLatency(0),
3176 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3177 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3179 // clear usage count for all stream types
3180 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3182 mCurVolume[i] = -1.0;
3186 for (int i = 0; i < NUM_STRATEGIES; i++) {
3187 mStrategyMutedByDevice[i] = false;
3189 if (profile != NULL) {
3190 mSamplingRate = profile->mSamplingRates[0];
3191 mFormat = profile->mFormats[0];
3192 mChannelMask = profile->mChannelMasks[0];
3193 mFlags = profile->mFlags;
3197 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3199 if (isDuplicated()) {
3200 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3206 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3208 if (isDuplicated()) {
3209 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3215 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3216 const AudioOutputDescriptor *outputDesc)
3218 if (isDuplicated()) {
3219 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3220 } else if (outputDesc->isDuplicated()){
3221 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3223 return (mProfile->mModule == outputDesc->mProfile->mModule);
3227 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3229 // forward usage count change to attached outputs
3230 if (isDuplicated()) {
3231 mOutput1->changeRefCount(stream, delta);
3232 mOutput2->changeRefCount(stream, delta);
3234 if ((delta + (int)mRefCount[stream]) < 0) {
3235 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3236 mRefCount[stream] = 0;
3239 mRefCount[stream] += delta;
3240 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3243 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3245 if (isDuplicated()) {
3246 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3248 return mProfile->mSupportedDevices ;
3252 bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3254 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3257 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3259 nsecs_t sysTime) const
3261 if ((sysTime == 0) && (inPastMs != 0)) {
3262 sysTime = systemTime();
3264 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3265 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3266 (NUM_STRATEGIES == strategy)) &&
3267 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3274 bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3276 nsecs_t sysTime) const
3278 if (mRefCount[stream] != 0) {
3281 if (inPastMs == 0) {
3285 sysTime = systemTime();
3287 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3294 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3296 const size_t SIZE = 256;
3300 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3301 result.append(buffer);
3302 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3303 result.append(buffer);
3304 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3305 result.append(buffer);
3306 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3307 result.append(buffer);
3308 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3309 result.append(buffer);
3310 snprintf(buffer, SIZE, " Devices %08x\n", device());
3311 result.append(buffer);
3312 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3313 result.append(buffer);
3314 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3315 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3316 result.append(buffer);
3318 write(fd, result.string(), result.size());
3323 // --- AudioInputDescriptor class implementation
3325 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3326 : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3327 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3328 mInputSource(0), mProfile(profile)
3332 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3334 const size_t SIZE = 256;
3338 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3339 result.append(buffer);
3340 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3341 result.append(buffer);
3342 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3343 result.append(buffer);
3344 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3345 result.append(buffer);
3346 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3347 result.append(buffer);
3348 write(fd, result.string(), result.size());
3353 // --- StreamDescriptor class implementation
3355 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3356 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3358 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3361 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3363 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3364 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3365 if (mIndexCur.indexOfKey(device) < 0) {
3366 device = AUDIO_DEVICE_OUT_DEFAULT;
3368 return mIndexCur.valueFor(device);
3371 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3373 const size_t SIZE = 256;
3377 snprintf(buffer, SIZE, "%s %02d %02d ",
3378 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3379 result.append(buffer);
3380 for (size_t i = 0; i < mIndexCur.size(); i++) {
3381 snprintf(buffer, SIZE, "%04x : %02d, ",
3383 mIndexCur.valueAt(i));
3384 result.append(buffer);
3386 result.append("\n");
3388 write(fd, result.string(), result.size());
3391 // --- EffectDescriptor class implementation
3393 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3395 const size_t SIZE = 256;
3399 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3400 result.append(buffer);
3401 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3402 result.append(buffer);
3403 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3404 result.append(buffer);
3405 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3406 result.append(buffer);
3407 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3408 result.append(buffer);
3409 write(fd, result.string(), result.size());
3414 // --- IOProfile class implementation
3416 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3417 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3421 AudioPolicyManagerBase::HwModule::~HwModule()
3423 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3424 delete mOutputProfiles[i];
3426 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3427 delete mInputProfiles[i];
3429 free((void *)mName);
3432 void AudioPolicyManagerBase::HwModule::dump(int fd)
3434 const size_t SIZE = 256;
3438 snprintf(buffer, SIZE, " - name: %s\n", mName);
3439 result.append(buffer);
3440 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3441 result.append(buffer);
3442 write(fd, result.string(), result.size());
3443 if (mOutputProfiles.size()) {
3444 write(fd, " - outputs:\n", sizeof(" - outputs:\n"));
3445 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3446 snprintf(buffer, SIZE, " output %d:\n", i);
3447 write(fd, buffer, strlen(buffer));
3448 mOutputProfiles[i]->dump(fd);
3451 if (mInputProfiles.size()) {
3452 write(fd, " - inputs:\n", sizeof(" - inputs:\n"));
3453 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3454 snprintf(buffer, SIZE, " input %d:\n", i);
3455 write(fd, buffer, strlen(buffer));
3456 mInputProfiles[i]->dump(fd);
3461 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3462 : mFlags((audio_output_flags_t)0), mModule(module)
3466 AudioPolicyManagerBase::IOProfile::~IOProfile()
3470 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3471 // means a parameter is don't care
3472 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3473 uint32_t samplingRate,
3475 uint32_t channelMask,
3476 audio_output_flags_t flags) const
3478 if ((mSupportedDevices & device) != device) {
3481 if ((mFlags & flags) != flags) {
3484 if (samplingRate != 0) {
3486 for (i = 0; i < mSamplingRates.size(); i++)
3488 if (mSamplingRates[i] == samplingRate) {
3492 if (i == mSamplingRates.size()) {
3498 for (i = 0; i < mFormats.size(); i++)
3500 if (mFormats[i] == format) {
3504 if (i == mFormats.size()) {
3508 if (channelMask != 0) {
3510 for (i = 0; i < mChannelMasks.size(); i++)
3512 if (mChannelMasks[i] == channelMask) {
3516 if (i == mChannelMasks.size()) {
3523 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3525 const size_t SIZE = 256;
3529 snprintf(buffer, SIZE, " - sampling rates: ");
3530 result.append(buffer);
3531 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3532 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3533 result.append(buffer);
3534 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3537 snprintf(buffer, SIZE, " - channel masks: ");
3538 result.append(buffer);
3539 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3540 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3541 result.append(buffer);
3542 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3545 snprintf(buffer, SIZE, " - formats: ");
3546 result.append(buffer);
3547 for (size_t i = 0; i < mFormats.size(); i++) {
3548 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3549 result.append(buffer);
3550 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3553 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
3554 result.append(buffer);
3555 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3556 result.append(buffer);
3558 write(fd, result.string(), result.size());
3561 // --- audio_policy.conf file parsing
3563 struct StringToEnum {
3568 #define STRING_TO_ENUM(string) { #string, string }
3569 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3571 const struct StringToEnum sDeviceNameToEnumTable[] = {
3572 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3573 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3574 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3575 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3576 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3577 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3578 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3579 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3580 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3581 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3582 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3583 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3584 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3585 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3586 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3587 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3588 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3589 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3590 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3591 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3592 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3593 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3594 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3597 const struct StringToEnum sFlagNameToEnumTable[] = {
3598 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3599 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3600 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3601 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3602 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3603 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3606 const struct StringToEnum sFormatNameToEnumTable[] = {
3607 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3608 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3609 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3610 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3611 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3614 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3615 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3616 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3617 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3618 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3621 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3622 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3623 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3624 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3628 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3632 for (size_t i = 0; i < size; i++) {
3633 if (strcmp(table[i].name, name) == 0) {
3634 ALOGV("stringToEnum() found %s", table[i].name);
3635 return table[i].value;
3641 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3645 // it is OK to cast name to non const here as we are not going to use it after
3646 // strtok() modifies it
3647 char *flagName = strtok(name, "|");
3648 while (flagName != NULL) {
3649 if (strlen(flagName) != 0) {
3650 flag |= stringToEnum(sFlagNameToEnumTable,
3651 ARRAY_SIZE(sFlagNameToEnumTable),
3654 flagName = strtok(NULL, "|");
3656 //force direct flag if offload flag is set: offloading implies a direct output stream
3657 // and all common behaviors are driven by checking only the direct flag
3658 // this should normally be set appropriately in the policy configuration file
3659 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3660 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
3663 return (audio_output_flags_t)flag;
3666 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3668 uint32_t device = 0;
3670 char *devName = strtok(name, "|");
3671 while (devName != NULL) {
3672 if (strlen(devName) != 0) {
3673 device |= stringToEnum(sDeviceNameToEnumTable,
3674 ARRAY_SIZE(sDeviceNameToEnumTable),
3677 devName = strtok(NULL, "|");
3682 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3684 char *str = strtok(name, "|");
3686 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3687 // rates should be read from the output stream after it is opened for the first time
3688 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3689 profile->mSamplingRates.add(0);
3693 while (str != NULL) {
3694 uint32_t rate = atoi(str);
3696 ALOGV("loadSamplingRates() adding rate %d", rate);
3697 profile->mSamplingRates.add(rate);
3699 str = strtok(NULL, "|");
3704 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3706 char *str = strtok(name, "|");
3708 // by convention, "0' in the first entry in mFormats indicates the supported formats
3709 // should be read from the output stream after it is opened for the first time
3710 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3711 profile->mFormats.add((audio_format_t)0);
3715 while (str != NULL) {
3716 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3717 ARRAY_SIZE(sFormatNameToEnumTable),
3720 profile->mFormats.add(format);
3722 str = strtok(NULL, "|");
3727 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3729 const char *str = strtok(name, "|");
3731 ALOGV("loadInChannels() %s", name);
3733 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3734 profile->mChannelMasks.add((audio_channel_mask_t)0);
3738 while (str != NULL) {
3739 audio_channel_mask_t channelMask =
3740 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3741 ARRAY_SIZE(sInChannelsNameToEnumTable),
3743 if (channelMask != 0) {
3744 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3745 profile->mChannelMasks.add(channelMask);
3747 str = strtok(NULL, "|");
3752 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3754 const char *str = strtok(name, "|");
3756 ALOGV("loadOutChannels() %s", name);
3758 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3759 // masks should be read from the output stream after it is opened for the first time
3760 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3761 profile->mChannelMasks.add((audio_channel_mask_t)0);
3765 while (str != NULL) {
3766 audio_channel_mask_t channelMask =
3767 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3768 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3770 if (channelMask != 0) {
3771 profile->mChannelMasks.add(channelMask);
3773 str = strtok(NULL, "|");
3778 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3780 cnode *node = root->first_child;
3782 IOProfile *profile = new IOProfile(module);
3785 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3786 loadSamplingRates((char *)node->value, profile);
3787 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3788 loadFormats((char *)node->value, profile);
3789 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3790 loadInChannels((char *)node->value, profile);
3791 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3792 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3796 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3797 "loadInput() invalid supported devices");
3798 ALOGW_IF(profile->mChannelMasks.size() == 0,
3799 "loadInput() invalid supported channel masks");
3800 ALOGW_IF(profile->mSamplingRates.size() == 0,
3801 "loadInput() invalid supported sampling rates");
3802 ALOGW_IF(profile->mFormats.size() == 0,
3803 "loadInput() invalid supported formats");
3804 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3805 (profile->mChannelMasks.size() != 0) &&
3806 (profile->mSamplingRates.size() != 0) &&
3807 (profile->mFormats.size() != 0)) {
3809 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3811 module->mInputProfiles.add(profile);
3819 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3821 cnode *node = root->first_child;
3823 IOProfile *profile = new IOProfile(module);
3826 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3827 loadSamplingRates((char *)node->value, profile);
3828 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3829 loadFormats((char *)node->value, profile);
3830 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3831 loadOutChannels((char *)node->value, profile);
3832 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3833 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3834 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3835 profile->mFlags = parseFlagNames((char *)node->value);
3839 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3840 "loadOutput() invalid supported devices");
3841 ALOGW_IF(profile->mChannelMasks.size() == 0,
3842 "loadOutput() invalid supported channel masks");
3843 ALOGW_IF(profile->mSamplingRates.size() == 0,
3844 "loadOutput() invalid supported sampling rates");
3845 ALOGW_IF(profile->mFormats.size() == 0,
3846 "loadOutput() invalid supported formats");
3847 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3848 (profile->mChannelMasks.size() != 0) &&
3849 (profile->mSamplingRates.size() != 0) &&
3850 (profile->mFormats.size() != 0)) {
3852 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3853 profile->mSupportedDevices, profile->mFlags);
3855 module->mOutputProfiles.add(profile);
3863 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3865 cnode *node = config_find(root, OUTPUTS_TAG);
3866 status_t status = NAME_NOT_FOUND;
3868 HwModule *module = new HwModule(root->name);
3871 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3873 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3875 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
3876 mHasRemoteSubmix = true;
3879 node = node->first_child;
3881 ALOGV("loadHwModule() loading output %s", node->name);
3882 status_t tmpStatus = loadOutput(node, module);
3883 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3889 node = config_find(root, INPUTS_TAG);
3891 node = node->first_child;
3893 ALOGV("loadHwModule() loading input %s", node->name);
3894 status_t tmpStatus = loadInput(node, module);
3895 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3901 if (status == NO_ERROR) {
3902 mHwModules.add(module);
3908 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3910 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3915 node = node->first_child;
3917 ALOGV("loadHwModules() loading module %s", node->name);
3923 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3925 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3929 node = node->first_child;
3931 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3932 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3933 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
3934 "loadGlobalConfig() no attached output devices");
3935 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3936 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3937 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3938 ARRAY_SIZE(sDeviceNameToEnumTable),
3939 (char *)node->value);
3940 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
3941 "loadGlobalConfig() default device not specified");
3942 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3943 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3944 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
3945 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3951 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3956 data = (char *)load_file(path, NULL);
3960 root = config_node("", "");
3961 config_load(root, data);
3963 loadGlobalConfig(root);
3964 loadHwModules(root);
3970 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3975 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3980 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3981 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3982 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
3984 module = new HwModule("primary");
3986 profile = new IOProfile(module);
3987 profile->mSamplingRates.add(44100);
3988 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3989 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3990 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3991 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3992 module->mOutputProfiles.add(profile);
3994 profile = new IOProfile(module);
3995 profile->mSamplingRates.add(8000);
3996 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3997 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3998 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3999 module->mInputProfiles.add(profile);
4001 mHwModules.add(module);
4004 }; // namespace android