blob: 6f58cf75a2c737c65b331440b08cbb6a0adafd68 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#define LOG_TAG "AudioPolicyManagerBase"
18//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
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
33
34#include <utils/Log.h>
35#include <hardware_legacy/AudioPolicyManagerBase.h>
36#include <hardware/audio_effect.h>
37#include <hardware/audio.h>
38#include <math.h>
39#include <hardware_legacy/audio_policy_conf.h>
40#include <cutils/properties.h>
41
42namespace android_audio_legacy {
43
44// ----------------------------------------------------------------------------
45// AudioPolicyInterface implementation
46// ----------------------------------------------------------------------------
47
48
49status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
50 AudioSystem::device_connection_state state,
51 const char *device_address)
52{
53 SortedVector <audio_io_handle_t> outputs;
54
55 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
56
57 // connect/disconnect only 1 device at a time
58 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
59
60 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
61 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
62 return BAD_VALUE;
63 }
64
65 // handle output devices
66 if (audio_is_output_device(device)) {
67
68 if (!mHasA2dp && audio_is_a2dp_device(device)) {
69 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
70 return BAD_VALUE;
71 }
72 if (!mHasUsb && audio_is_usb_device(device)) {
73 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
74 return BAD_VALUE;
75 }
76 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
77 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
78 return BAD_VALUE;
79 }
80
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;
84 String8 paramStr;
85 switch (state)
86 {
87 // handle output device connection
88 case AudioSystem::DEVICE_STATE_AVAILABLE:
89 if (mAvailableOutputDevices & device) {
90 ALOGW("setDeviceConnectionState() device already connected: %x", device);
91 return INVALID_OPERATION;
92 }
93 ALOGV("setDeviceConnectionState() connecting device %x", device);
94
95 if (mHasA2dp && audio_is_a2dp_device(device)) {
96 // handle A2DP device connection
97 AudioParameter param;
98 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
99 paramStr = param.toString();
100 } else if (mHasUsb && audio_is_usb_device(device)) {
101 // handle USB device connection
102 paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
103 }
104
105 if (checkOutputsForDevice(device, state, outputs, paramStr) != NO_ERROR) {
106 return INVALID_OPERATION;
107 }
108 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
109 outputs.size());
110 // register new device as available
111 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
112
113 if (mHasA2dp && audio_is_a2dp_device(device)) {
114 // handle A2DP device connection
115 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
116 mA2dpSuspended = false;
117 } else if (audio_is_bluetooth_sco_device(device)) {
118 // handle SCO device connection
119 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
120 } else if (mHasUsb && audio_is_usb_device(device)) {
121 // handle USB device connection
122 mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
123 }
124
125 break;
126 // handle output device disconnection
127 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
128 if (!(mAvailableOutputDevices & device)) {
129 ALOGW("setDeviceConnectionState() device not connected: %x", device);
130 return INVALID_OPERATION;
131 }
132
133 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
134 // remove device from available output devices
135 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
136
137 checkOutputsForDevice(device, state, outputs, paramStr);
138 if (mHasA2dp && audio_is_a2dp_device(device)) {
139 // handle A2DP device disconnection
140 mA2dpDeviceAddress = "";
141 mA2dpSuspended = false;
142 } else if (audio_is_bluetooth_sco_device(device)) {
143 // handle SCO device disconnection
144 mScoDeviceAddress = "";
145 } else if (mHasUsb && audio_is_usb_device(device)) {
146 // handle USB device disconnection
147 mUsbCardAndDevice = "";
148 }
149 // not currently handling multiple simultaneous submixes: ignoring remote submix
150 // case and address
151 } break;
152
153 default:
154 ALOGE("setDeviceConnectionState() invalid state: %x", state);
155 return BAD_VALUE;
156 }
157
158 checkA2dpSuspend();
159 checkOutputForAllStrategies();
160 // outputs must be closed after checkOutputForAllStrategies() is executed
161 if (!outputs.isEmpty()) {
162 for (size_t i = 0; i < outputs.size(); i++) {
163 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
164 // close unused outputs after device disconnection or direct outputs that have been
165 // opened by checkOutputsForDevice() to query dynamic parameters
166 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
167 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
168 (desc->mDirectOpenCount == 0))) {
169 closeOutput(outputs[i]);
170 }
171 }
172 }
173
174 updateDevicesAndOutputs();
175 for (size_t i = 0; i < mOutputs.size(); i++) {
176 // do not force device change on duplicated output because if device is 0, it will
177 // also force a device 0 for the two outputs it is duplicated to which may override
178 // a valid device selection on those outputs.
179 setOutputDevice(mOutputs.keyAt(i),
180 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
181 !mOutputs.valueAt(i)->isDuplicated(),
182 0);
183 }
184
185 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
186 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
187 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
188 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
189 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
190 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
191 } else {
192 return NO_ERROR;
193 }
194 }
195 // handle input devices
196 if (audio_is_input_device(device)) {
197
198 switch (state)
199 {
200 // handle input device connection
201 case AudioSystem::DEVICE_STATE_AVAILABLE: {
202 if (mAvailableInputDevices & device) {
203 ALOGW("setDeviceConnectionState() device already connected: %d", device);
204 return INVALID_OPERATION;
205 }
206 mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
207 }
208 break;
209
210 // handle input device disconnection
211 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
212 if (!(mAvailableInputDevices & device)) {
213 ALOGW("setDeviceConnectionState() device not connected: %d", device);
214 return INVALID_OPERATION;
215 }
216 mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
217 } break;
218
219 default:
220 ALOGE("setDeviceConnectionState() invalid state: %x", state);
221 return BAD_VALUE;
222 }
223
224 audio_io_handle_t activeInput = getActiveInput();
225 if (activeInput != 0) {
226 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
227 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
228 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
229 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
230 inputDesc->mDevice, newDevice, activeInput);
231 inputDesc->mDevice = newDevice;
232 AudioParameter param = AudioParameter();
233 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
234 mpClientInterface->setParameters(activeInput, param.toString());
235 }
236 }
237
238 return NO_ERROR;
239 }
240
241 ALOGW("setDeviceConnectionState() invalid device: %x", device);
242 return BAD_VALUE;
243}
244
245AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
246 const char *device_address)
247{
248 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
249 String8 address = String8(device_address);
250 if (audio_is_output_device(device)) {
251 if (device & mAvailableOutputDevices) {
252 if (audio_is_a2dp_device(device) &&
253 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
254 return state;
255 }
256 if (audio_is_bluetooth_sco_device(device) &&
257 address != "" && mScoDeviceAddress != address) {
258 return state;
259 }
260 if (audio_is_usb_device(device) &&
261 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
262 ALOGE("getDeviceConnectionState() invalid device: %x", device);
263 return state;
264 }
265 if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
266 return state;
267 }
268 state = AudioSystem::DEVICE_STATE_AVAILABLE;
269 }
270 } else if (audio_is_input_device(device)) {
271 if (device & mAvailableInputDevices) {
272 state = AudioSystem::DEVICE_STATE_AVAILABLE;
273 }
274 }
275
276 return state;
277}
278
279void AudioPolicyManagerBase::setPhoneState(int state)
280{
281 ALOGV("setPhoneState() state %d", state);
282 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
283 if (state < 0 || state >= AudioSystem::NUM_MODES) {
284 ALOGW("setPhoneState() invalid state %d", state);
285 return;
286 }
287
288 if (state == mPhoneState ) {
289 ALOGW("setPhoneState() setting same state %d", state);
290 return;
291 }
292
293 // if leaving call state, handle special case of active streams
294 // pertaining to sonification strategy see handleIncallSonification()
295 if (isInCall()) {
296 ALOGV("setPhoneState() in call state management: new state is %d", state);
297 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
298 handleIncallSonification(stream, false, true);
299 }
300 }
301
302 // store previous phone state for management of sonification strategy below
303 int oldState = mPhoneState;
304 mPhoneState = state;
305 bool force = false;
306
307 // are we entering or starting a call
308 if (!isStateInCall(oldState) && isStateInCall(state)) {
309 ALOGV(" Entering call in setPhoneState()");
310 // force routing command to audio hardware when starting a call
311 // even if no device change is needed
312 force = true;
313 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
314 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
315 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
316 }
317 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
318 ALOGV(" Exiting call in setPhoneState()");
319 // force routing command to audio hardware when exiting a call
320 // even if no device change is needed
321 force = true;
322 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
323 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
324 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
325 }
326 } else if (isStateInCall(state) && (state != oldState)) {
327 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
328 // force routing command to audio hardware when switching between telephony and VoIP
329 // even if no device change is needed
330 force = true;
331 }
332
333 // check for device and output changes triggered by new phone state
334 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
335 checkA2dpSuspend();
336 checkOutputForAllStrategies();
337 updateDevicesAndOutputs();
338
339 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
340
341 // force routing command to audio hardware when ending call
342 // even if no device change is needed
343 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
344 newDevice = hwOutputDesc->device();
345 }
346
347 int delayMs = 0;
348 if (isStateInCall(state)) {
349 nsecs_t sysTime = systemTime();
350 for (size_t i = 0; i < mOutputs.size(); i++) {
351 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
352 // mute media and sonification strategies and delay device switch by the largest
353 // latency of any output where either strategy is active.
354 // This avoid sending the ring tone or music tail into the earpiece or headset.
355 if ((desc->isStrategyActive(STRATEGY_MEDIA,
356 SONIFICATION_HEADSET_MUSIC_DELAY,
357 sysTime) ||
358 desc->isStrategyActive(STRATEGY_SONIFICATION,
359 SONIFICATION_HEADSET_MUSIC_DELAY,
360 sysTime)) &&
361 (delayMs < (int)desc->mLatency*2)) {
362 delayMs = desc->mLatency*2;
363 }
364 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
365 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
366 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
367 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
368 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
369 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
370 }
371 }
372
373 // change routing is necessary
374 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
375
376 // if entering in call state, handle special case of active streams
377 // pertaining to sonification strategy see handleIncallSonification()
378 if (isStateInCall(state)) {
379 ALOGV("setPhoneState() in call state management: new state is %d", state);
380 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
381 handleIncallSonification(stream, true, true);
382 }
383 }
384
385 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
386 if (state == AudioSystem::MODE_RINGTONE &&
387 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
388 mLimitRingtoneVolume = true;
389 } else {
390 mLimitRingtoneVolume = false;
391 }
392}
393
394void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
395{
396 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
397
398 bool forceVolumeReeval = false;
399 switch(usage) {
400 case AudioSystem::FOR_COMMUNICATION:
401 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
402 config != AudioSystem::FORCE_NONE) {
403 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
404 return;
405 }
406 forceVolumeReeval = true;
407 mForceUse[usage] = config;
408 break;
409 case AudioSystem::FOR_MEDIA:
410 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
411 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
412 config != AudioSystem::FORCE_ANALOG_DOCK &&
413 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
414 config != AudioSystem::FORCE_NO_BT_A2DP) {
415 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
416 return;
417 }
418 mForceUse[usage] = config;
419 break;
420 case AudioSystem::FOR_RECORD:
421 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
422 config != AudioSystem::FORCE_NONE) {
423 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
424 return;
425 }
426 mForceUse[usage] = config;
427 break;
428 case AudioSystem::FOR_DOCK:
429 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
430 config != AudioSystem::FORCE_BT_DESK_DOCK &&
431 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
432 config != AudioSystem::FORCE_ANALOG_DOCK &&
433 config != AudioSystem::FORCE_DIGITAL_DOCK) {
434 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
435 }
436 forceVolumeReeval = true;
437 mForceUse[usage] = config;
438 break;
439 case AudioSystem::FOR_SYSTEM:
440 if (config != AudioSystem::FORCE_NONE &&
441 config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
442 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
443 }
444 forceVolumeReeval = true;
445 mForceUse[usage] = config;
446 break;
447 default:
448 ALOGW("setForceUse() invalid usage %d", usage);
449 break;
450 }
451
452 // check for device and output changes triggered by new force usage
453 checkA2dpSuspend();
454 checkOutputForAllStrategies();
455 updateDevicesAndOutputs();
456 for (size_t i = 0; i < mOutputs.size(); i++) {
457 audio_io_handle_t output = mOutputs.keyAt(i);
458 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
459 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
460 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
461 applyStreamVolumes(output, newDevice, 0, true);
462 }
463 }
464
465 audio_io_handle_t activeInput = getActiveInput();
466 if (activeInput != 0) {
467 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
468 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
469 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
470 ALOGV("setForceUse() changing device from %x to %x for input %d",
471 inputDesc->mDevice, newDevice, activeInput);
472 inputDesc->mDevice = newDevice;
473 AudioParameter param = AudioParameter();
474 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
475 mpClientInterface->setParameters(activeInput, param.toString());
476 }
477 }
478
479}
480
481AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
482{
483 return mForceUse[usage];
484}
485
486void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
487{
488 ALOGV("setSystemProperty() property %s, value %s", property, value);
489}
490
491// Find a direct output profile compatible with the parameters passed, even if the input flags do
492// not explicitly request a direct output
493AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
494 audio_devices_t device,
495 uint32_t samplingRate,
496 audio_format_t format,
497 audio_channel_mask_t channelMask,
498 audio_output_flags_t flags)
499{
500 for (size_t i = 0; i < mHwModules.size(); i++) {
501 if (mHwModules[i]->mHandle == 0) {
502 continue;
503 }
504 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
505 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
506 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
507 if (profile->isCompatibleProfile(device, samplingRate, format,
508 channelMask,
509 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
510 if (mAvailableOutputDevices & profile->mSupportedDevices) {
511 return mHwModules[i]->mOutputProfiles[j];
512 }
513 }
514 } else {
515 if (profile->isCompatibleProfile(device, samplingRate, format,
516 channelMask,
517 AUDIO_OUTPUT_FLAG_DIRECT)) {
518 if (mAvailableOutputDevices & profile->mSupportedDevices) {
519 return mHwModules[i]->mOutputProfiles[j];
520 }
521 }
522 }
523 }
524 }
525 return 0;
526}
527
528audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
529 uint32_t samplingRate,
530 audio_format_t format,
531 audio_channel_mask_t channelMask,
532 AudioSystem::output_flags flags,
533 const audio_offload_info_t *offloadInfo)
534{
535 audio_io_handle_t output = 0;
536 uint32_t latency = 0;
537 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
538 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
539 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
540 device, stream, samplingRate, format, channelMask, flags);
541
542#ifdef AUDIO_POLICY_TEST
543 if (mCurOutput != 0) {
544 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
545 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
546
547 if (mTestOutputs[mCurOutput] == 0) {
548 ALOGV("getOutput() opening test output");
549 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
550 outputDesc->mDevice = mTestDevice;
551 outputDesc->mSamplingRate = mTestSamplingRate;
552 outputDesc->mFormat = mTestFormat;
553 outputDesc->mChannelMask = mTestChannels;
554 outputDesc->mLatency = mTestLatencyMs;
555 outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
556 outputDesc->mRefCount[stream] = 0;
557 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
558 &outputDesc->mSamplingRate,
559 &outputDesc->mFormat,
560 &outputDesc->mChannelMask,
561 &outputDesc->mLatency,
562 outputDesc->mFlags,
563 offloadInfo);
564 if (mTestOutputs[mCurOutput]) {
565 AudioParameter outputCmd = AudioParameter();
566 outputCmd.addInt(String8("set_id"),mCurOutput);
567 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
568 addOutput(mTestOutputs[mCurOutput], outputDesc);
569 }
570 }
571 return mTestOutputs[mCurOutput];
572 }
573#endif //AUDIO_POLICY_TEST
574
575 // open a direct output if required by specified parameters
576 //force direct flag if offload flag is set: offloading implies a direct output stream
577 // and all common behaviors are driven by checking only the direct flag
578 // this should normally be set appropriately in the policy configuration file
579 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
580 flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
581 }
582
583 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
584 // creating an offloaded track and tearing it down immediately after start when audioflinger
585 // detects there is an active non offloadable effect.
586 // FIXME: We should check the audio session here but we do not have it in this context.
587 // This may prevent offloading in rare situations where effects are left active by apps
588 // in the background.
589 IOProfile *profile = NULL;
590 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
591 !isNonOffloadableEffectEnabled()) {
592 profile = getProfileForDirectOutput(device,
593 samplingRate,
594 format,
595 channelMask,
596 (audio_output_flags_t)flags);
597 }
598
599 if (profile != NULL) {
600 AudioOutputDescriptor *outputDesc = NULL;
601
602 for (size_t i = 0; i < mOutputs.size(); i++) {
603 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
604 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
605 outputDesc = desc;
606 // reuse direct output if currently open and configured with same parameters
607 if ((samplingRate == outputDesc->mSamplingRate) &&
608 (format == outputDesc->mFormat) &&
609 (channelMask == outputDesc->mChannelMask)) {
610 outputDesc->mDirectOpenCount++;
611 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
612 return mOutputs.keyAt(i);
613 }
614 }
615 }
616 // close direct output if currently open and configured with different parameters
617 if (outputDesc != NULL) {
618 closeOutput(outputDesc->mId);
619 }
620 outputDesc = new AudioOutputDescriptor(profile);
621 outputDesc->mDevice = device;
622 outputDesc->mSamplingRate = samplingRate;
623 outputDesc->mFormat = format;
624 outputDesc->mChannelMask = channelMask;
625 outputDesc->mLatency = 0;
626 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
627 outputDesc->mRefCount[stream] = 0;
628 outputDesc->mStopTime[stream] = 0;
629 outputDesc->mDirectOpenCount = 1;
630 output = mpClientInterface->openOutput(profile->mModule->mHandle,
631 &outputDesc->mDevice,
632 &outputDesc->mSamplingRate,
633 &outputDesc->mFormat,
634 &outputDesc->mChannelMask,
635 &outputDesc->mLatency,
636 outputDesc->mFlags,
637 offloadInfo);
638
639 // only accept an output with the requested parameters
640 if (output == 0 ||
641 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
642 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
643 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
644 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
645 "format %d %d, channelMask %04x %04x", output, samplingRate,
646 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
647 outputDesc->mChannelMask);
648 if (output != 0) {
649 mpClientInterface->closeOutput(output);
650 }
651 delete outputDesc;
652 return 0;
653 }
654 audio_io_handle_t srcOutput = getOutputForEffect();
655 addOutput(output, outputDesc);
656 audio_io_handle_t dstOutput = getOutputForEffect();
657 if (dstOutput == output) {
658 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
659 }
660 mPreviousOutputs = mOutputs;
661 ALOGV("getOutput() returns new direct output %d", output);
662 return output;
663 }
664
665 // ignoring channel mask due to downmix capability in mixer
666
667 // open a non direct output
668
669 // for non direct outputs, only PCM is supported
670 if (audio_is_linear_pcm(format)) {
671 // get which output is suitable for the specified stream. The actual
672 // routing change will happen when startOutput() will be called
673 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
674
675 output = selectOutput(outputs, flags);
676 }
677 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
678 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
679
680 ALOGV("getOutput() returns output %d", output);
681
682 return output;
683}
684
685audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
686 AudioSystem::output_flags flags)
687{
688 // select one output among several that provide a path to a particular device or set of
689 // devices (the list was previously build by getOutputsForDevice()).
690 // The priority is as follows:
691 // 1: the output with the highest number of requested policy flags
692 // 2: the primary output
693 // 3: the first output in the list
694
695 if (outputs.size() == 0) {
696 return 0;
697 }
698 if (outputs.size() == 1) {
699 return outputs[0];
700 }
701
702 int maxCommonFlags = 0;
703 audio_io_handle_t outputFlags = 0;
704 audio_io_handle_t outputPrimary = 0;
705
706 for (size_t i = 0; i < outputs.size(); i++) {
707 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
708 if (!outputDesc->isDuplicated()) {
709 int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
710 if (commonFlags > maxCommonFlags) {
711 outputFlags = outputs[i];
712 maxCommonFlags = commonFlags;
713 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
714 }
715 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
716 outputPrimary = outputs[i];
717 }
718 }
719 }
720
721 if (outputFlags != 0) {
722 return outputFlags;
723 }
724 if (outputPrimary != 0) {
725 return outputPrimary;
726 }
727
728 return outputs[0];
729}
730
731status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
732 AudioSystem::stream_type stream,
733 int session)
734{
735 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
736 ssize_t index = mOutputs.indexOfKey(output);
737 if (index < 0) {
738 ALOGW("startOutput() unknown output %d", output);
739 return BAD_VALUE;
740 }
741
742 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
743
744 // increment usage count for this stream on the requested output:
745 // NOTE that the usage count is the same for duplicated output and hardware output which is
746 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
747 outputDesc->changeRefCount(stream, 1);
748
749 if (outputDesc->mRefCount[stream] == 1) {
750 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
751 routing_strategy strategy = getStrategy(stream);
752 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
753 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
754 uint32_t waitMs = 0;
755 bool force = false;
756 for (size_t i = 0; i < mOutputs.size(); i++) {
757 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
758 if (desc != outputDesc) {
759 // force a device change if any other output is managed by the same hw
760 // module and has a current device selection that differs from selected device.
761 // In this case, the audio HAL must receive the new device selection so that it can
762 // change the device currently selected by the other active output.
763 if (outputDesc->sharesHwModuleWith(desc) &&
764 desc->device() != newDevice) {
765 force = true;
766 }
767 // wait for audio on other active outputs to be presented when starting
768 // a notification so that audio focus effect can propagate.
769 uint32_t latency = desc->latency();
770 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
771 waitMs = latency;
772 }
773 }
774 }
775 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
776
777 // handle special case for sonification while in call
778 if (isInCall()) {
779 handleIncallSonification(stream, true, false);
780 }
781
782 // apply volume rules for current stream and device if necessary
783 checkAndSetVolume(stream,
784 mStreams[stream].getVolumeIndex(newDevice),
785 output,
786 newDevice);
787
788 // update the outputs if starting an output with a stream that can affect notification
789 // routing
790 handleNotificationRoutingForStream(stream);
791 if (waitMs > muteWaitMs) {
792 usleep((waitMs - muteWaitMs) * 2 * 1000);
793 }
794 }
795 return NO_ERROR;
796}
797
798
799status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
800 AudioSystem::stream_type stream,
801 int session)
802{
803 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
804 ssize_t index = mOutputs.indexOfKey(output);
805 if (index < 0) {
806 ALOGW("stopOutput() unknown output %d", output);
807 return BAD_VALUE;
808 }
809
810 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
811
812 // handle special case for sonification while in call
813 if (isInCall()) {
814 handleIncallSonification(stream, false, false);
815 }
816
817 if (outputDesc->mRefCount[stream] > 0) {
818 // decrement usage count of this stream on the output
819 outputDesc->changeRefCount(stream, -1);
820 // store time at which the stream was stopped - see isStreamActive()
821 if (outputDesc->mRefCount[stream] == 0) {
822 outputDesc->mStopTime[stream] = systemTime();
823 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
824 // delay the device switch by twice the latency because stopOutput() is executed when
825 // the track stop() command is received and at that time the audio track buffer can
826 // still contain data that needs to be drained. The latency only covers the audio HAL
827 // and kernel buffers. Also the latency does not always include additional delay in the
828 // audio path (audio DSP, CODEC ...)
829 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
830
831 // force restoring the device selection on other active outputs if it differs from the
832 // one being selected for this output
833 for (size_t i = 0; i < mOutputs.size(); i++) {
834 audio_io_handle_t curOutput = mOutputs.keyAt(i);
835 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
836 if (curOutput != output &&
837 desc->isActive() &&
838 outputDesc->sharesHwModuleWith(desc) &&
839 (newDevice != desc->device())) {
840 setOutputDevice(curOutput,
841 getNewDevice(curOutput, false /*fromCache*/),
842 true,
843 outputDesc->mLatency*2);
844 }
845 }
846 // update the outputs if stopping one with a stream that can affect notification routing
847 handleNotificationRoutingForStream(stream);
848 }
849 return NO_ERROR;
850 } else {
851 ALOGW("stopOutput() refcount is already 0 for output %d", output);
852 return INVALID_OPERATION;
853 }
854}
855
856void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
857{
858 ALOGV("releaseOutput() %d", output);
859 ssize_t index = mOutputs.indexOfKey(output);
860 if (index < 0) {
861 ALOGW("releaseOutput() releasing unknown output %d", output);
862 return;
863 }
864
865#ifdef AUDIO_POLICY_TEST
866 int testIndex = testOutputIndex(output);
867 if (testIndex != 0) {
868 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
869 if (outputDesc->isActive()) {
870 mpClientInterface->closeOutput(output);
871 delete mOutputs.valueAt(index);
872 mOutputs.removeItem(output);
873 mTestOutputs[testIndex] = 0;
874 }
875 return;
876 }
877#endif //AUDIO_POLICY_TEST
878
879 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
880 if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
881 if (desc->mDirectOpenCount <= 0) {
882 ALOGW("releaseOutput() invalid open count %d for output %d",
883 desc->mDirectOpenCount, output);
884 return;
885 }
886 if (--desc->mDirectOpenCount == 0) {
887 closeOutput(output);
888 // If effects where present on the output, audioflinger moved them to the primary
889 // output by default: move them back to the appropriate output.
890 audio_io_handle_t dstOutput = getOutputForEffect();
891 if (dstOutput != mPrimaryOutput) {
892 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
893 }
894 }
895 }
896}
897
898
899audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
900 uint32_t samplingRate,
901 audio_format_t format,
902 audio_channel_mask_t channelMask,
903 AudioSystem::audio_in_acoustics acoustics)
904{
905 audio_io_handle_t input = 0;
906 audio_devices_t device = getDeviceForInputSource(inputSource);
907
908 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
909 inputSource, samplingRate, format, channelMask, acoustics);
910
911 if (device == AUDIO_DEVICE_NONE) {
912 ALOGW("getInput() could not find device for inputSource %d", inputSource);
913 return 0;
914 }
915
916 // adapt channel selection to input source
917 switch(inputSource) {
918 case AUDIO_SOURCE_VOICE_UPLINK:
919 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
920 break;
921 case AUDIO_SOURCE_VOICE_DOWNLINK:
922 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
923 break;
924 case AUDIO_SOURCE_VOICE_CALL:
925 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
926 break;
927 default:
928 break;
929 }
930
931 IOProfile *profile = getInputProfile(device,
932 samplingRate,
933 format,
934 channelMask);
935 if (profile == NULL) {
936 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
937 "channelMask %04x",
938 device, samplingRate, format, channelMask);
939 return 0;
940 }
941
942 if (profile->mModule->mHandle == 0) {
943 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
944 return 0;
945 }
946
947 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
948
949 inputDesc->mInputSource = inputSource;
950 inputDesc->mDevice = device;
951 inputDesc->mSamplingRate = samplingRate;
952 inputDesc->mFormat = format;
953 inputDesc->mChannelMask = channelMask;
954 inputDesc->mRefCount = 0;
955 input = mpClientInterface->openInput(profile->mModule->mHandle,
956 &inputDesc->mDevice,
957 &inputDesc->mSamplingRate,
958 &inputDesc->mFormat,
959 &inputDesc->mChannelMask);
960
961 // only accept input with the exact requested set of parameters
962 if (input == 0 ||
963 (samplingRate != inputDesc->mSamplingRate) ||
964 (format != inputDesc->mFormat) ||
965 (channelMask != inputDesc->mChannelMask)) {
966 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
967 samplingRate, format, channelMask);
968 if (input != 0) {
969 mpClientInterface->closeInput(input);
970 }
971 delete inputDesc;
972 return 0;
973 }
974 mInputs.add(input, inputDesc);
975 return input;
976}
977
978status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
979{
980 ALOGV("startInput() input %d", input);
981 ssize_t index = mInputs.indexOfKey(input);
982 if (index < 0) {
983 ALOGW("startInput() unknown input %d", input);
984 return BAD_VALUE;
985 }
986 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
987
988#ifdef AUDIO_POLICY_TEST
989 if (mTestInput == 0)
990#endif //AUDIO_POLICY_TEST
991 {
992 // refuse 2 active AudioRecord clients at the same time except if the active input
993 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
994 audio_io_handle_t activeInput = getActiveInput();
995 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
996 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
997 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
998 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
999 stopInput(activeInput);
1000 releaseInput(activeInput);
1001 } else {
1002 ALOGW("startInput() input %d failed: other input already started", input);
1003 return INVALID_OPERATION;
1004 }
1005 }
1006 }
1007
1008 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1009 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1010 inputDesc->mDevice = newDevice;
1011 }
1012
1013 // automatically enable the remote submix output when input is started
1014 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1015 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1016 AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1017 }
1018
1019 AudioParameter param = AudioParameter();
1020 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1021
1022 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1023 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1024
1025 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1026 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1027
1028 mpClientInterface->setParameters(input, param.toString());
1029
1030 inputDesc->mRefCount = 1;
1031 return NO_ERROR;
1032}
1033
1034status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
1035{
1036 ALOGV("stopInput() input %d", input);
1037 ssize_t index = mInputs.indexOfKey(input);
1038 if (index < 0) {
1039 ALOGW("stopInput() unknown input %d", input);
1040 return BAD_VALUE;
1041 }
1042 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1043
1044 if (inputDesc->mRefCount == 0) {
1045 ALOGW("stopInput() input %d already stopped", input);
1046 return INVALID_OPERATION;
1047 } else {
1048 // automatically disable the remote submix output when input is stopped
1049 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1050 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1051 AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1052 }
1053
1054 AudioParameter param = AudioParameter();
1055 param.addInt(String8(AudioParameter::keyRouting), 0);
1056 mpClientInterface->setParameters(input, param.toString());
1057 inputDesc->mRefCount = 0;
1058 return NO_ERROR;
1059 }
1060}
1061
1062void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1063{
1064 ALOGV("releaseInput() %d", input);
1065 ssize_t index = mInputs.indexOfKey(input);
1066 if (index < 0) {
1067 ALOGW("releaseInput() releasing unknown input %d", input);
1068 return;
1069 }
1070 mpClientInterface->closeInput(input);
1071 delete mInputs.valueAt(index);
1072 mInputs.removeItem(input);
1073 ALOGV("releaseInput() exit");
1074}
1075
1076void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1077 int indexMin,
1078 int indexMax)
1079{
1080 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1081 if (indexMin < 0 || indexMin >= indexMax) {
1082 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1083 return;
1084 }
1085 mStreams[stream].mIndexMin = indexMin;
1086 mStreams[stream].mIndexMax = indexMax;
1087}
1088
1089status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1090 int index,
1091 audio_devices_t device)
1092{
1093
1094 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1095 return BAD_VALUE;
1096 }
1097 if (!audio_is_output_device(device)) {
1098 return BAD_VALUE;
1099 }
1100
1101 // Force max volume if stream cannot be muted
1102 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1103
1104 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1105 stream, device, index);
1106
1107 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1108 // clear all device specific values
1109 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1110 mStreams[stream].mIndexCur.clear();
1111 }
1112 mStreams[stream].mIndexCur.add(device, index);
1113
1114 // compute and apply stream volume on all outputs according to connected device
1115 status_t status = NO_ERROR;
1116 for (size_t i = 0; i < mOutputs.size(); i++) {
1117 audio_devices_t curDevice =
1118 getDeviceForVolume(mOutputs.valueAt(i)->device());
1119 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1120 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1121 if (volStatus != NO_ERROR) {
1122 status = volStatus;
1123 }
1124 }
1125 }
1126 return status;
1127}
1128
1129status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1130 int *index,
1131 audio_devices_t device)
1132{
1133 if (index == NULL) {
1134 return BAD_VALUE;
1135 }
1136 if (!audio_is_output_device(device)) {
1137 return BAD_VALUE;
1138 }
1139 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1140 // the strategy the stream belongs to.
1141 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1142 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1143 }
1144 device = getDeviceForVolume(device);
1145
1146 *index = mStreams[stream].getVolumeIndex(device);
1147 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1148 return NO_ERROR;
1149}
1150
1151audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
1152 const SortedVector<audio_io_handle_t>& outputs)
1153{
1154 // select one output among several suitable for global effects.
1155 // The priority is as follows:
1156 // 1: An offloaded output. If the effect ends up not being offloadable,
1157 // AudioFlinger will invalidate the track and the offloaded output
1158 // will be closed causing the effect to be moved to a PCM output.
1159 // 2: A deep buffer output
1160 // 3: the first output in the list
1161
1162 if (outputs.size() == 0) {
1163 return 0;
1164 }
1165
1166 audio_io_handle_t outputOffloaded = 0;
1167 audio_io_handle_t outputDeepBuffer = 0;
1168
1169 for (size_t i = 0; i < outputs.size(); i++) {
1170 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1171 ALOGV("selectOutputForEffects outputs[%d] flags %x", i, desc->mFlags);
1172 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1173 outputOffloaded = outputs[i];
1174 }
1175 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1176 outputDeepBuffer = outputs[i];
1177 }
1178 }
1179
1180 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1181 outputOffloaded, outputDeepBuffer);
1182 if (outputOffloaded != 0) {
1183 return outputOffloaded;
1184 }
1185 if (outputDeepBuffer != 0) {
1186 return outputDeepBuffer;
1187 }
1188
1189 return outputs[0];
1190}
1191
1192audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1193{
1194 // apply simple rule where global effects are attached to the same output as MUSIC streams
1195
1196 routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1197 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1198 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1199
1200 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1201 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1202 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1203
1204 return output;
1205}
1206
1207status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1208 audio_io_handle_t io,
1209 uint32_t strategy,
1210 int session,
1211 int id)
1212{
1213 ssize_t index = mOutputs.indexOfKey(io);
1214 if (index < 0) {
1215 index = mInputs.indexOfKey(io);
1216 if (index < 0) {
1217 ALOGW("registerEffect() unknown io %d", io);
1218 return INVALID_OPERATION;
1219 }
1220 }
1221
1222 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1223 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1224 desc->name, desc->memoryUsage);
1225 return INVALID_OPERATION;
1226 }
1227 mTotalEffectsMemory += desc->memoryUsage;
1228 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1229 desc->name, io, strategy, session, id);
1230 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1231
1232 EffectDescriptor *pDesc = new EffectDescriptor();
1233 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1234 pDesc->mIo = io;
1235 pDesc->mStrategy = (routing_strategy)strategy;
1236 pDesc->mSession = session;
1237 pDesc->mEnabled = false;
1238
1239 mEffects.add(id, pDesc);
1240
1241 return NO_ERROR;
1242}
1243
1244status_t AudioPolicyManagerBase::unregisterEffect(int id)
1245{
1246 ssize_t index = mEffects.indexOfKey(id);
1247 if (index < 0) {
1248 ALOGW("unregisterEffect() unknown effect ID %d", id);
1249 return INVALID_OPERATION;
1250 }
1251
1252 EffectDescriptor *pDesc = mEffects.valueAt(index);
1253
1254 setEffectEnabled(pDesc, false);
1255
1256 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1257 ALOGW("unregisterEffect() memory %d too big for total %d",
1258 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1259 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1260 }
1261 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1262 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1263 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1264
1265 mEffects.removeItem(id);
1266 delete pDesc;
1267
1268 return NO_ERROR;
1269}
1270
1271status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1272{
1273 ssize_t index = mEffects.indexOfKey(id);
1274 if (index < 0) {
1275 ALOGW("unregisterEffect() unknown effect ID %d", id);
1276 return INVALID_OPERATION;
1277 }
1278
1279 return setEffectEnabled(mEffects.valueAt(index), enabled);
1280}
1281
1282status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1283{
1284 if (enabled == pDesc->mEnabled) {
1285 ALOGV("setEffectEnabled(%s) effect already %s",
1286 enabled?"true":"false", enabled?"enabled":"disabled");
1287 return INVALID_OPERATION;
1288 }
1289
1290 if (enabled) {
1291 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1292 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1293 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1294 return INVALID_OPERATION;
1295 }
1296 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1297 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1298 } else {
1299 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1300 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1301 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1302 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1303 }
1304 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1305 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1306 }
1307 pDesc->mEnabled = enabled;
1308 return NO_ERROR;
1309}
1310
1311bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled()
1312{
1313 for (size_t i = 0; i < mEffects.size(); i++) {
1314 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1315 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1316 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1317 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1318 pDesc->mDesc.name, pDesc->mSession);
1319 return true;
1320 }
1321 }
1322 return false;
1323}
1324
1325bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1326{
1327 nsecs_t sysTime = systemTime();
1328 for (size_t i = 0; i < mOutputs.size(); i++) {
1329 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1330 if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1331 return true;
1332 }
1333 }
1334 return false;
1335}
1336
1337bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1338{
1339 nsecs_t sysTime = systemTime();
1340 for (size_t i = 0; i < mOutputs.size(); i++) {
1341 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1342 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1343 outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1344 return true;
1345 }
1346 }
1347 return false;
1348}
1349
1350bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1351{
1352 for (size_t i = 0; i < mInputs.size(); i++) {
1353 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1354 if ((inputDescriptor->mInputSource == (int)source ||
1355 (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
1356 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1357 && (inputDescriptor->mRefCount > 0)) {
1358 return true;
1359 }
1360 }
1361 return false;
1362}
1363
1364
1365status_t AudioPolicyManagerBase::dump(int fd)
1366{
1367 const size_t SIZE = 256;
1368 char buffer[SIZE];
1369 String8 result;
1370
1371 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1372 result.append(buffer);
1373
1374 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1375 result.append(buffer);
1376 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1377 result.append(buffer);
1378 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1379 result.append(buffer);
1380 snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1381 result.append(buffer);
1382 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1383 result.append(buffer);
1384 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1385 result.append(buffer);
1386 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1387 result.append(buffer);
1388 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1389 result.append(buffer);
1390 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1391 result.append(buffer);
1392 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1393 result.append(buffer);
1394 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1395 result.append(buffer);
1396 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1397 result.append(buffer);
1398 write(fd, result.string(), result.size());
1399
1400
1401 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1402 write(fd, buffer, strlen(buffer));
1403 for (size_t i = 0; i < mHwModules.size(); i++) {
1404 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1405 write(fd, buffer, strlen(buffer));
1406 mHwModules[i]->dump(fd);
1407 }
1408
1409 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1410 write(fd, buffer, strlen(buffer));
1411 for (size_t i = 0; i < mOutputs.size(); i++) {
1412 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1413 write(fd, buffer, strlen(buffer));
1414 mOutputs.valueAt(i)->dump(fd);
1415 }
1416
1417 snprintf(buffer, SIZE, "\nInputs dump:\n");
1418 write(fd, buffer, strlen(buffer));
1419 for (size_t i = 0; i < mInputs.size(); i++) {
1420 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1421 write(fd, buffer, strlen(buffer));
1422 mInputs.valueAt(i)->dump(fd);
1423 }
1424
1425 snprintf(buffer, SIZE, "\nStreams dump:\n");
1426 write(fd, buffer, strlen(buffer));
1427 snprintf(buffer, SIZE,
1428 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1429 write(fd, buffer, strlen(buffer));
1430 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1431 snprintf(buffer, SIZE, " %02d ", i);
1432 write(fd, buffer, strlen(buffer));
1433 mStreams[i].dump(fd);
1434 }
1435
1436 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1437 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1438 write(fd, buffer, strlen(buffer));
1439
1440 snprintf(buffer, SIZE, "Registered effects:\n");
1441 write(fd, buffer, strlen(buffer));
1442 for (size_t i = 0; i < mEffects.size(); i++) {
1443 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1444 write(fd, buffer, strlen(buffer));
1445 mEffects.valueAt(i)->dump(fd);
1446 }
1447
1448
1449 return NO_ERROR;
1450}
1451
1452// This function checks for the parameters which can be offloaded.
1453// This can be enhanced depending on the capability of the DSP and policy
1454// of the system.
1455bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1456{
1457 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1458 " BitRate=%u, duration=%lld us, has_video=%d",
1459 offloadInfo.sample_rate, offloadInfo.channel_mask,
1460 offloadInfo.format,
1461 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1462 offloadInfo.has_video);
1463
1464 // Check if offload has been disabled
1465 char propValue[PROPERTY_VALUE_MAX];
1466 if (property_get("audio.offload.disable", propValue, "0")) {
1467 if (atoi(propValue) != 0) {
1468 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1469 return false;
1470 }
1471 }
1472
1473 // Check if stream type is music, then only allow offload as of now.
1474 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1475 {
1476 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1477 return false;
1478 }
1479
1480 //TODO: enable audio offloading with video when ready
1481 if (offloadInfo.has_video)
1482 {
1483 ALOGV("isOffloadSupported: has_video == true, returning false");
1484 return false;
1485 }
1486
1487 //If duration is less than minimum value defined in property, return false
1488 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1489 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1490 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1491 return false;
1492 }
1493 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1494 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1495 return false;
1496 }
1497
1498 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1499 // creating an offloaded track and tearing it down immediately after start when audioflinger
1500 // detects there is an active non offloadable effect.
1501 // FIXME: We should check the audio session here but we do not have it in this context.
1502 // This may prevent offloading in rare situations where effects are left active by apps
1503 // in the background.
1504 if (isNonOffloadableEffectEnabled()) {
1505 return false;
1506 }
1507
1508 // See if there is a profile to support this.
1509 // AUDIO_DEVICE_NONE
1510 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1511 offloadInfo.sample_rate,
1512 offloadInfo.format,
1513 offloadInfo.channel_mask,
1514 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1515 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1516 return (profile != NULL);
1517}
1518
1519// ----------------------------------------------------------------------------
1520// AudioPolicyManagerBase
1521// ----------------------------------------------------------------------------
1522
1523AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1524 :
1525#ifdef AUDIO_POLICY_TEST
1526 Thread(false),
1527#endif //AUDIO_POLICY_TEST
1528 mPrimaryOutput((audio_io_handle_t)0),
1529 mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1530 mPhoneState(AudioSystem::MODE_NORMAL),
1531 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1532 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1533 mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),
1534 mSpeakerDrcEnabled(false)
1535{
1536 mpClientInterface = clientInterface;
1537
1538 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1539 mForceUse[i] = AudioSystem::FORCE_NONE;
1540 }
1541
1542 mA2dpDeviceAddress = String8("");
1543 mScoDeviceAddress = String8("");
1544 mUsbCardAndDevice = String8("");
1545
1546 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1547 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1548 ALOGE("could not load audio policy configuration file, setting defaults");
1549 defaultAudioPolicyConfig();
1550 }
1551 }
1552
1553 // must be done after reading the policy
1554 initializeVolumeCurves();
1555
1556 // open all output streams needed to access attached devices
1557 for (size_t i = 0; i < mHwModules.size(); i++) {
1558 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1559 if (mHwModules[i]->mHandle == 0) {
1560 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1561 continue;
1562 }
1563 // open all output streams needed to access attached devices
1564 // except for direct output streams that are only opened when they are actually
1565 // required by an app.
1566 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1567 {
1568 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1569
1570 if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1571 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1572 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1573 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1574 outProfile->mSupportedDevices);
1575 audio_io_handle_t output = mpClientInterface->openOutput(
1576 outProfile->mModule->mHandle,
1577 &outputDesc->mDevice,
1578 &outputDesc->mSamplingRate,
1579 &outputDesc->mFormat,
1580 &outputDesc->mChannelMask,
1581 &outputDesc->mLatency,
1582 outputDesc->mFlags);
1583 if (output == 0) {
1584 delete outputDesc;
1585 } else {
1586 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1587 (outProfile->mSupportedDevices & mAttachedOutputDevices));
1588 if (mPrimaryOutput == 0 &&
1589 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1590 mPrimaryOutput = output;
1591 }
1592 addOutput(output, outputDesc);
1593 setOutputDevice(output,
1594 (audio_devices_t)(mDefaultOutputDevice &
1595 outProfile->mSupportedDevices),
1596 true);
1597 }
1598 }
1599 }
1600 }
1601
1602 ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1603 "Not output found for attached devices %08x",
1604 (mAttachedOutputDevices & ~mAvailableOutputDevices));
1605
1606 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1607
1608 updateDevicesAndOutputs();
1609
1610#ifdef AUDIO_POLICY_TEST
1611 if (mPrimaryOutput != 0) {
1612 AudioParameter outputCmd = AudioParameter();
1613 outputCmd.addInt(String8("set_id"), 0);
1614 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1615
1616 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1617 mTestSamplingRate = 44100;
1618 mTestFormat = AudioSystem::PCM_16_BIT;
1619 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1620 mTestLatencyMs = 0;
1621 mCurOutput = 0;
1622 mDirectOutput = false;
1623 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1624 mTestOutputs[i] = 0;
1625 }
1626
1627 const size_t SIZE = 256;
1628 char buffer[SIZE];
1629 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1630 run(buffer, ANDROID_PRIORITY_AUDIO);
1631 }
1632#endif //AUDIO_POLICY_TEST
1633}
1634
1635AudioPolicyManagerBase::~AudioPolicyManagerBase()
1636{
1637#ifdef AUDIO_POLICY_TEST
1638 exit();
1639#endif //AUDIO_POLICY_TEST
1640 for (size_t i = 0; i < mOutputs.size(); i++) {
1641 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1642 delete mOutputs.valueAt(i);
1643 }
1644 for (size_t i = 0; i < mInputs.size(); i++) {
1645 mpClientInterface->closeInput(mInputs.keyAt(i));
1646 delete mInputs.valueAt(i);
1647 }
1648 for (size_t i = 0; i < mHwModules.size(); i++) {
1649 delete mHwModules[i];
1650 }
1651}
1652
1653status_t AudioPolicyManagerBase::initCheck()
1654{
1655 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1656}
1657
1658#ifdef AUDIO_POLICY_TEST
1659bool AudioPolicyManagerBase::threadLoop()
1660{
1661 ALOGV("entering threadLoop()");
1662 while (!exitPending())
1663 {
1664 String8 command;
1665 int valueInt;
1666 String8 value;
1667
1668 Mutex::Autolock _l(mLock);
1669 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1670
1671 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1672 AudioParameter param = AudioParameter(command);
1673
1674 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1675 valueInt != 0) {
1676 ALOGV("Test command %s received", command.string());
1677 String8 target;
1678 if (param.get(String8("target"), target) != NO_ERROR) {
1679 target = "Manager";
1680 }
1681 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1682 param.remove(String8("test_cmd_policy_output"));
1683 mCurOutput = valueInt;
1684 }
1685 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1686 param.remove(String8("test_cmd_policy_direct"));
1687 if (value == "false") {
1688 mDirectOutput = false;
1689 } else if (value == "true") {
1690 mDirectOutput = true;
1691 }
1692 }
1693 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1694 param.remove(String8("test_cmd_policy_input"));
1695 mTestInput = valueInt;
1696 }
1697
1698 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1699 param.remove(String8("test_cmd_policy_format"));
1700 int format = AudioSystem::INVALID_FORMAT;
1701 if (value == "PCM 16 bits") {
1702 format = AudioSystem::PCM_16_BIT;
1703 } else if (value == "PCM 8 bits") {
1704 format = AudioSystem::PCM_8_BIT;
1705 } else if (value == "Compressed MP3") {
1706 format = AudioSystem::MP3;
1707 }
1708 if (format != AudioSystem::INVALID_FORMAT) {
1709 if (target == "Manager") {
1710 mTestFormat = format;
1711 } else if (mTestOutputs[mCurOutput] != 0) {
1712 AudioParameter outputParam = AudioParameter();
1713 outputParam.addInt(String8("format"), format);
1714 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1715 }
1716 }
1717 }
1718 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1719 param.remove(String8("test_cmd_policy_channels"));
1720 int channels = 0;
1721
1722 if (value == "Channels Stereo") {
1723 channels = AudioSystem::CHANNEL_OUT_STEREO;
1724 } else if (value == "Channels Mono") {
1725 channels = AudioSystem::CHANNEL_OUT_MONO;
1726 }
1727 if (channels != 0) {
1728 if (target == "Manager") {
1729 mTestChannels = channels;
1730 } else if (mTestOutputs[mCurOutput] != 0) {
1731 AudioParameter outputParam = AudioParameter();
1732 outputParam.addInt(String8("channels"), channels);
1733 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1734 }
1735 }
1736 }
1737 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1738 param.remove(String8("test_cmd_policy_sampleRate"));
1739 if (valueInt >= 0 && valueInt <= 96000) {
1740 int samplingRate = valueInt;
1741 if (target == "Manager") {
1742 mTestSamplingRate = samplingRate;
1743 } else if (mTestOutputs[mCurOutput] != 0) {
1744 AudioParameter outputParam = AudioParameter();
1745 outputParam.addInt(String8("sampling_rate"), samplingRate);
1746 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1747 }
1748 }
1749 }
1750
1751 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1752 param.remove(String8("test_cmd_policy_reopen"));
1753
1754 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1755 mpClientInterface->closeOutput(mPrimaryOutput);
1756
1757 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1758
1759 delete mOutputs.valueFor(mPrimaryOutput);
1760 mOutputs.removeItem(mPrimaryOutput);
1761
1762 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1763 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1764 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1765 &outputDesc->mDevice,
1766 &outputDesc->mSamplingRate,
1767 &outputDesc->mFormat,
1768 &outputDesc->mChannelMask,
1769 &outputDesc->mLatency,
1770 outputDesc->mFlags);
1771 if (mPrimaryOutput == 0) {
1772 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1773 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1774 } else {
1775 AudioParameter outputCmd = AudioParameter();
1776 outputCmd.addInt(String8("set_id"), 0);
1777 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1778 addOutput(mPrimaryOutput, outputDesc);
1779 }
1780 }
1781
1782
1783 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1784 }
1785 }
1786 return false;
1787}
1788
1789void AudioPolicyManagerBase::exit()
1790{
1791 {
1792 AutoMutex _l(mLock);
1793 requestExit();
1794 mWaitWorkCV.signal();
1795 }
1796 requestExitAndWait();
1797}
1798
1799int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1800{
1801 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1802 if (output == mTestOutputs[i]) return i;
1803 }
1804 return 0;
1805}
1806#endif //AUDIO_POLICY_TEST
1807
1808// ---
1809
1810void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1811{
1812 outputDesc->mId = id;
1813 mOutputs.add(id, outputDesc);
1814}
1815
1816
1817status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1818 AudioSystem::device_connection_state state,
1819 SortedVector<audio_io_handle_t>& outputs,
1820 const String8 paramStr)
1821{
1822 AudioOutputDescriptor *desc;
1823
1824 if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1825 // first list already open outputs that can be routed to this device
1826 for (size_t i = 0; i < mOutputs.size(); i++) {
1827 desc = mOutputs.valueAt(i);
1828 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1829 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1830 outputs.add(mOutputs.keyAt(i));
1831 }
1832 }
1833 // then look for output profiles that can be routed to this device
1834 SortedVector<IOProfile *> profiles;
1835 for (size_t i = 0; i < mHwModules.size(); i++)
1836 {
1837 if (mHwModules[i]->mHandle == 0) {
1838 continue;
1839 }
1840 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1841 {
1842 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1843 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1844 profiles.add(mHwModules[i]->mOutputProfiles[j]);
1845 }
1846 }
1847 }
1848
1849 if (profiles.isEmpty() && outputs.isEmpty()) {
1850 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1851 return BAD_VALUE;
1852 }
1853
1854 // open outputs for matching profiles if needed. Direct outputs are also opened to
1855 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1856 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1857 IOProfile *profile = profiles[profile_index];
1858
1859 // nothing to do if one output is already opened for this profile
1860 size_t j;
1861 for (j = 0; j < mOutputs.size(); j++) {
1862 desc = mOutputs.valueAt(j);
1863 if (!desc->isDuplicated() && desc->mProfile == profile) {
1864 break;
1865 }
1866 }
1867 if (j != mOutputs.size()) {
1868 continue;
1869 }
1870
1871 ALOGV("opening output for device %08x with params %s", device, paramStr.string());
1872 desc = new AudioOutputDescriptor(profile);
1873 desc->mDevice = device;
1874 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1875 offloadInfo.sample_rate = desc->mSamplingRate;
1876 offloadInfo.format = desc->mFormat;
1877 offloadInfo.channel_mask = desc->mChannelMask;
1878
1879 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1880 &desc->mDevice,
1881 &desc->mSamplingRate,
1882 &desc->mFormat,
1883 &desc->mChannelMask,
1884 &desc->mLatency,
1885 desc->mFlags,
1886 &offloadInfo);
1887 if (output != 0) {
1888 if (!paramStr.isEmpty()) {
1889 mpClientInterface->setParameters(output, paramStr);
1890 }
1891
1892 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1893 String8 reply;
1894 char *value;
1895 if (profile->mSamplingRates[0] == 0) {
1896 reply = mpClientInterface->getParameters(output,
1897 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1898 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1899 reply.string());
1900 value = strpbrk((char *)reply.string(), "=");
1901 if (value != NULL) {
1902 loadSamplingRates(value + 1, profile);
1903 }
1904 }
1905 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
1906 reply = mpClientInterface->getParameters(output,
1907 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1908 ALOGV("checkOutputsForDevice() direct output sup formats %s",
1909 reply.string());
1910 value = strpbrk((char *)reply.string(), "=");
1911 if (value != NULL) {
1912 loadFormats(value + 1, profile);
1913 }
1914 }
1915 if (profile->mChannelMasks[0] == 0) {
1916 reply = mpClientInterface->getParameters(output,
1917 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1918 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1919 reply.string());
1920 value = strpbrk((char *)reply.string(), "=");
1921 if (value != NULL) {
1922 loadOutChannels(value + 1, profile);
1923 }
1924 }
1925 if (((profile->mSamplingRates[0] == 0) &&
1926 (profile->mSamplingRates.size() < 2)) ||
1927 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
1928 (profile->mFormats.size() < 2)) ||
1929 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
1930 (profile->mChannelMasks.size() < 2))) {
1931 ALOGW("checkOutputsForDevice() direct output missing param");
1932 mpClientInterface->closeOutput(output);
1933 output = 0;
1934 } else {
1935 addOutput(output, desc);
1936 }
1937 } else {
1938 audio_io_handle_t duplicatedOutput = 0;
1939 // add output descriptor
1940 addOutput(output, desc);
1941 // set initial stream volume for device
1942 applyStreamVolumes(output, device, 0, true);
1943
1944 //TODO: configure audio effect output stage here
1945
1946 // open a duplicating output thread for the new output and the primary output
1947 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1948 mPrimaryOutput);
1949 if (duplicatedOutput != 0) {
1950 // add duplicated output descriptor
1951 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1952 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1953 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1954 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1955 dupOutputDesc->mFormat = desc->mFormat;
1956 dupOutputDesc->mChannelMask = desc->mChannelMask;
1957 dupOutputDesc->mLatency = desc->mLatency;
1958 addOutput(duplicatedOutput, dupOutputDesc);
1959 applyStreamVolumes(duplicatedOutput, device, 0, true);
1960 } else {
1961 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1962 mPrimaryOutput, output);
1963 mpClientInterface->closeOutput(output);
1964 mOutputs.removeItem(output);
1965 output = 0;
1966 }
1967 }
1968 }
1969 if (output == 0) {
1970 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1971 delete desc;
1972 profiles.removeAt(profile_index);
1973 profile_index--;
1974 } else {
1975 outputs.add(output);
1976 ALOGV("checkOutputsForDevice(): adding output %d", output);
1977 }
1978 }
1979
1980 if (profiles.isEmpty()) {
1981 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1982 return BAD_VALUE;
1983 }
1984 } else {
1985 // check if one opened output is not needed any more after disconnecting one device
1986 for (size_t i = 0; i < mOutputs.size(); i++) {
1987 desc = mOutputs.valueAt(i);
1988 if (!desc->isDuplicated() &&
1989 !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1990 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1991 outputs.add(mOutputs.keyAt(i));
1992 }
1993 }
1994 for (size_t i = 0; i < mHwModules.size(); i++)
1995 {
1996 if (mHwModules[i]->mHandle == 0) {
1997 continue;
1998 }
1999 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2000 {
2001 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
2002 if ((profile->mSupportedDevices & device) &&
2003 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
2004 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
2005 j, i);
2006 if (profile->mSamplingRates[0] == 0) {
2007 profile->mSamplingRates.clear();
2008 profile->mSamplingRates.add(0);
2009 }
2010 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2011 profile->mFormats.clear();
2012 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2013 }
2014 if (profile->mChannelMasks[0] == 0) {
2015 profile->mChannelMasks.clear();
2016 profile->mChannelMasks.add(0);
2017 }
2018 }
2019 }
2020 }
2021 }
2022 return NO_ERROR;
2023}
2024
2025void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
2026{
2027 ALOGV("closeOutput(%d)", output);
2028
2029 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2030 if (outputDesc == NULL) {
2031 ALOGW("closeOutput() unknown output %d", output);
2032 return;
2033 }
2034
2035 // look for duplicated outputs connected to the output being removed.
2036 for (size_t i = 0; i < mOutputs.size(); i++) {
2037 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2038 if (dupOutputDesc->isDuplicated() &&
2039 (dupOutputDesc->mOutput1 == outputDesc ||
2040 dupOutputDesc->mOutput2 == outputDesc)) {
2041 AudioOutputDescriptor *outputDesc2;
2042 if (dupOutputDesc->mOutput1 == outputDesc) {
2043 outputDesc2 = dupOutputDesc->mOutput2;
2044 } else {
2045 outputDesc2 = dupOutputDesc->mOutput1;
2046 }
2047 // As all active tracks on duplicated output will be deleted,
2048 // and as they were also referenced on the other output, the reference
2049 // count for their stream type must be adjusted accordingly on
2050 // the other output.
2051 for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
2052 int refCount = dupOutputDesc->mRefCount[j];
2053 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
2054 }
2055 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2056 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2057
2058 mpClientInterface->closeOutput(duplicatedOutput);
2059 delete mOutputs.valueFor(duplicatedOutput);
2060 mOutputs.removeItem(duplicatedOutput);
2061 }
2062 }
2063
2064 AudioParameter param;
2065 param.add(String8("closing"), String8("true"));
2066 mpClientInterface->setParameters(output, param.toString());
2067
2068 mpClientInterface->closeOutput(output);
2069 delete outputDesc;
2070 mOutputs.removeItem(output);
2071 mPreviousOutputs = mOutputs;
2072}
2073
2074SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
2075 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2076{
2077 SortedVector<audio_io_handle_t> outputs;
2078
2079 ALOGVV("getOutputsForDevice() device %04x", device);
2080 for (size_t i = 0; i < openOutputs.size(); i++) {
2081 ALOGVV("output %d isDuplicated=%d device=%04x",
2082 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2083 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2084 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2085 outputs.add(openOutputs.keyAt(i));
2086 }
2087 }
2088 return outputs;
2089}
2090
2091bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2092 SortedVector<audio_io_handle_t>& outputs2)
2093{
2094 if (outputs1.size() != outputs2.size()) {
2095 return false;
2096 }
2097 for (size_t i = 0; i < outputs1.size(); i++) {
2098 if (outputs1[i] != outputs2[i]) {
2099 return false;
2100 }
2101 }
2102 return true;
2103}
2104
2105void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
2106{
2107 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2108 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2109 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2110 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2111
2112 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2113 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2114 strategy, srcOutputs[0], dstOutputs[0]);
2115 // mute strategy while moving tracks from one output to another
2116 for (size_t i = 0; i < srcOutputs.size(); i++) {
2117 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2118 if (desc->isStrategyActive(strategy)) {
2119 setStrategyMute(strategy, true, srcOutputs[i]);
2120 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2121 }
2122 }
2123
2124 // Move effects associated to this strategy from previous output to new output
2125 if (strategy == STRATEGY_MEDIA) {
2126 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2127 SortedVector<audio_io_handle_t> moved;
2128 for (size_t i = 0; i < mEffects.size(); i++) {
2129 EffectDescriptor *desc = mEffects.valueAt(i);
2130 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2131 desc->mIo != fxOutput) {
2132 if (moved.indexOf(desc->mIo) < 0) {
2133 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2134 mEffects.keyAt(i), fxOutput);
2135 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2136 fxOutput);
2137 moved.add(desc->mIo);
2138 }
2139 desc->mIo = fxOutput;
2140 }
2141 }
2142 }
2143 // Move tracks associated to this strategy from previous output to new output
2144 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2145 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2146 mpClientInterface->invalidateStream((AudioSystem::stream_type)i);
2147 }
2148 }
2149 }
2150}
2151
2152void AudioPolicyManagerBase::checkOutputForAllStrategies()
2153{
2154 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2155 checkOutputForStrategy(STRATEGY_PHONE);
2156 checkOutputForStrategy(STRATEGY_SONIFICATION);
2157 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2158 checkOutputForStrategy(STRATEGY_MEDIA);
2159 checkOutputForStrategy(STRATEGY_DTMF);
2160}
2161
2162audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2163{
2164 if (!mHasA2dp) {
2165 return 0;
2166 }
2167
2168 for (size_t i = 0; i < mOutputs.size(); i++) {
2169 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2170 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2171 return mOutputs.keyAt(i);
2172 }
2173 }
2174
2175 return 0;
2176}
2177
2178void AudioPolicyManagerBase::checkA2dpSuspend()
2179{
2180 if (!mHasA2dp) {
2181 return;
2182 }
2183 audio_io_handle_t a2dpOutput = getA2dpOutput();
2184 if (a2dpOutput == 0) {
2185 return;
2186 }
2187
2188 // suspend A2DP output if:
2189 // (NOT already suspended) &&
2190 // ((SCO device is connected &&
2191 // (forced usage for communication || for record is SCO))) ||
2192 // (phone state is ringing || in call)
2193 //
2194 // restore A2DP output if:
2195 // (Already suspended) &&
2196 // ((SCO device is NOT connected ||
2197 // (forced usage NOT for communication && NOT for record is SCO))) &&
2198 // (phone state is NOT ringing && NOT in call)
2199 //
2200 if (mA2dpSuspended) {
2201 if (((mScoDeviceAddress == "") ||
2202 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2203 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2204 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2205 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2206
2207 mpClientInterface->restoreOutput(a2dpOutput);
2208 mA2dpSuspended = false;
2209 }
2210 } else {
2211 if (((mScoDeviceAddress != "") &&
2212 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2213 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2214 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2215 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2216
2217 mpClientInterface->suspendOutput(a2dpOutput);
2218 mA2dpSuspended = true;
2219 }
2220 }
2221}
2222
2223audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2224{
2225 audio_devices_t device = AUDIO_DEVICE_NONE;
2226
2227 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2228 // check the following by order of priority to request a routing change if necessary:
2229 // 1: the strategy enforced audible is active on the output:
2230 // use device for strategy enforced audible
2231 // 2: we are in call or the strategy phone is active on the output:
2232 // use device for strategy phone
2233 // 3: the strategy sonification is active on the output:
2234 // use device for strategy sonification
2235 // 4: the strategy "respectful" sonification is active on the output:
2236 // use device for strategy "respectful" sonification
2237 // 5: the strategy media is active on the output:
2238 // use device for strategy media
2239 // 6: the strategy DTMF is active on the output:
2240 // use device for strategy DTMF
2241 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2242 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2243 } else if (isInCall() ||
2244 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2245 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2246 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2247 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2248 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2249 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2250 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2251 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2252 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2253 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2254 }
2255
2256 ALOGV("getNewDevice() selected device %x", device);
2257 return device;
2258}
2259
2260uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2261 return (uint32_t)getStrategy(stream);
2262}
2263
2264audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2265 audio_devices_t devices;
2266 // By checking the range of stream before calling getStrategy, we avoid
2267 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2268 // and then return STRATEGY_MEDIA, but we want to return the empty set.
2269 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2270 devices = AUDIO_DEVICE_NONE;
2271 } else {
2272 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2273 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2274 }
2275 return devices;
2276}
2277
2278AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2279 AudioSystem::stream_type stream) {
2280 // stream to strategy mapping
2281 switch (stream) {
2282 case AudioSystem::VOICE_CALL:
2283 case AudioSystem::BLUETOOTH_SCO:
2284 return STRATEGY_PHONE;
2285 case AudioSystem::RING:
2286 case AudioSystem::ALARM:
2287 return STRATEGY_SONIFICATION;
2288 case AudioSystem::NOTIFICATION:
2289 return STRATEGY_SONIFICATION_RESPECTFUL;
2290 case AudioSystem::DTMF:
2291 return STRATEGY_DTMF;
2292 default:
2293 ALOGE("unknown stream type");
2294 case AudioSystem::SYSTEM:
2295 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2296 // while key clicks are played produces a poor result
2297 case AudioSystem::TTS:
2298 case AudioSystem::MUSIC:
2299 return STRATEGY_MEDIA;
2300 case AudioSystem::ENFORCED_AUDIBLE:
2301 return STRATEGY_ENFORCED_AUDIBLE;
2302 }
2303}
2304
2305void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2306 switch(stream) {
2307 case AudioSystem::MUSIC:
2308 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2309 updateDevicesAndOutputs();
2310 break;
2311 default:
2312 break;
2313 }
2314}
2315
2316audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2317 bool fromCache)
2318{
2319 uint32_t device = AUDIO_DEVICE_NONE;
2320
2321 if (fromCache) {
2322 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2323 strategy, mDeviceForStrategy[strategy]);
2324 return mDeviceForStrategy[strategy];
2325 }
2326
2327 switch (strategy) {
2328
2329 case STRATEGY_SONIFICATION_RESPECTFUL:
2330 if (isInCall()) {
2331 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2332 } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2333 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2334 // while media is playing on a remote device, use the the sonification behavior.
2335 // Note that we test this usecase before testing if media is playing because
2336 // the isStreamActive() method only informs about the activity of a stream, not
2337 // if it's for local playback. Note also that we use the same delay between both tests
2338 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2339 } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2340 // while media is playing (or has recently played), use the same device
2341 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2342 } else {
2343 // when media is not playing anymore, fall back on the sonification behavior
2344 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2345 }
2346
2347 break;
2348
2349 case STRATEGY_DTMF:
2350 if (!isInCall()) {
2351 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2352 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2353 break;
2354 }
2355 // when in call, DTMF and PHONE strategies follow the same rules
2356 // FALL THROUGH
2357
2358 case STRATEGY_PHONE:
2359 // for phone strategy, we first consider the forced use and then the available devices by order
2360 // of priority
2361 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2362 case AudioSystem::FORCE_BT_SCO:
2363 if (!isInCall() || strategy != STRATEGY_DTMF) {
2364 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2365 if (device) break;
2366 }
2367 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2368 if (device) break;
2369 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2370 if (device) break;
2371 // if SCO device is requested but no SCO device is available, fall back to default case
2372 // FALL THROUGH
2373
2374 default: // FORCE_NONE
2375 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2376 if (mHasA2dp && !isInCall() &&
2377 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2378 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2379 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2380 if (device) break;
2381 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2382 if (device) break;
2383 }
2384 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2385 if (device) break;
2386 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2387 if (device) break;
2388 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2389 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2390 if (device) break;
2391 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2392 if (device) break;
2393 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2394 if (device) break;
2395 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2396 if (device) break;
2397 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2398 if (device) break;
2399 }
2400 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2401 if (device) break;
2402 device = mDefaultOutputDevice;
2403 if (device == AUDIO_DEVICE_NONE) {
2404 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2405 }
2406 break;
2407
2408 case AudioSystem::FORCE_SPEAKER:
2409 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2410 // A2DP speaker when forcing to speaker output
2411 if (mHasA2dp && !isInCall() &&
2412 (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2413 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2414 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2415 if (device) break;
2416 }
2417 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2418 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2419 if (device) break;
2420 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2421 if (device) break;
2422 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2423 if (device) break;
2424 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2425 if (device) break;
2426 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2427 if (device) break;
2428 }
2429 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2430 if (device) break;
2431 device = mDefaultOutputDevice;
2432 if (device == AUDIO_DEVICE_NONE) {
2433 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2434 }
2435 break;
2436 }
2437 break;
2438
2439 case STRATEGY_SONIFICATION:
2440
2441 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2442 // handleIncallSonification().
2443 if (isInCall()) {
2444 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2445 break;
2446 }
2447 // FALL THROUGH
2448
2449 case STRATEGY_ENFORCED_AUDIBLE:
2450 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2451 // except:
2452 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2453 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2454
2455 if ((strategy == STRATEGY_SONIFICATION) ||
2456 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2457 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2458 if (device == AUDIO_DEVICE_NONE) {
2459 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2460 }
2461 }
2462 // The second device used for sonification is the same as the device used by media strategy
2463 // FALL THROUGH
2464
2465 case STRATEGY_MEDIA: {
2466 uint32_t device2 = AUDIO_DEVICE_NONE;
2467 if (strategy != STRATEGY_SONIFICATION) {
2468 // no sonification on remote submix (e.g. WFD)
2469 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2470 }
2471 if ((device2 == AUDIO_DEVICE_NONE) &&
2472 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2473 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2474 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2475 if (device2 == AUDIO_DEVICE_NONE) {
2476 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2477 }
2478 if (device2 == AUDIO_DEVICE_NONE) {
2479 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2480 }
2481 }
2482 if (device2 == AUDIO_DEVICE_NONE) {
2483 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2484 }
2485 if (device2 == AUDIO_DEVICE_NONE) {
2486 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2487 }
2488 if (device2 == AUDIO_DEVICE_NONE) {
2489 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2490 }
2491 if (device2 == AUDIO_DEVICE_NONE) {
2492 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2493 }
2494 if (device2 == AUDIO_DEVICE_NONE) {
2495 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2496 }
2497 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2498 // no sonification on aux digital (e.g. HDMI)
2499 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2500 }
2501 if ((device2 == AUDIO_DEVICE_NONE) &&
2502 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2503 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2504 }
2505 if (device2 == AUDIO_DEVICE_NONE) {
2506 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2507 }
2508
2509 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2510 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2511 device |= device2;
2512 if (device) break;
2513 device = mDefaultOutputDevice;
2514 if (device == AUDIO_DEVICE_NONE) {
2515 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2516 }
2517 } break;
2518
2519 default:
2520 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2521 break;
2522 }
2523
2524 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2525 return device;
2526}
2527
2528void AudioPolicyManagerBase::updateDevicesAndOutputs()
2529{
2530 for (int i = 0; i < NUM_STRATEGIES; i++) {
2531 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2532 }
2533 mPreviousOutputs = mOutputs;
2534}
2535
2536uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2537 audio_devices_t prevDevice,
2538 uint32_t delayMs)
2539{
2540 // mute/unmute strategies using an incompatible device combination
2541 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2542 // if unmuting, unmute only after the specified delay
2543 if (outputDesc->isDuplicated()) {
2544 return 0;
2545 }
2546
2547 uint32_t muteWaitMs = 0;
2548 audio_devices_t device = outputDesc->device();
2549 bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2550 // temporary mute output if device selection changes to avoid volume bursts due to
2551 // different per device volumes
2552 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2553
2554 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2555 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2556 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2557 bool doMute = false;
2558
2559 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2560 doMute = true;
2561 outputDesc->mStrategyMutedByDevice[i] = true;
2562 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2563 doMute = true;
2564 outputDesc->mStrategyMutedByDevice[i] = false;
2565 }
2566 if (doMute || tempMute) {
2567 for (size_t j = 0; j < mOutputs.size(); j++) {
2568 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2569 // skip output if it does not share any device with current output
2570 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2571 == AUDIO_DEVICE_NONE) {
2572 continue;
2573 }
2574 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2575 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2576 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2577 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2578 if (desc->isStrategyActive((routing_strategy)i)) {
2579 // do tempMute only for current output
2580 if (tempMute && (desc == outputDesc)) {
2581 setStrategyMute((routing_strategy)i, true, curOutput);
2582 setStrategyMute((routing_strategy)i, false, curOutput,
2583 desc->latency() * 2, device);
2584 }
2585 if ((tempMute && (desc == outputDesc)) || mute) {
2586 if (muteWaitMs < desc->latency()) {
2587 muteWaitMs = desc->latency();
2588 }
2589 }
2590 }
2591 }
2592 }
2593 }
2594
2595 // FIXME: should not need to double latency if volume could be applied immediately by the
2596 // audioflinger mixer. We must account for the delay between now and the next time
2597 // the audioflinger thread for this output will process a buffer (which corresponds to
2598 // one buffer size, usually 1/2 or 1/4 of the latency).
2599 muteWaitMs *= 2;
2600 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2601 if (muteWaitMs > delayMs) {
2602 muteWaitMs -= delayMs;
2603 usleep(muteWaitMs * 1000);
2604 return muteWaitMs;
2605 }
2606 return 0;
2607}
2608
2609uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2610 audio_devices_t device,
2611 bool force,
2612 int delayMs)
2613{
2614 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2615 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2616 AudioParameter param;
2617 uint32_t muteWaitMs;
2618
2619 if (outputDesc->isDuplicated()) {
2620 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2621 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2622 return muteWaitMs;
2623 }
2624 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2625 // output profile
2626 if ((device != AUDIO_DEVICE_NONE) &&
2627 ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2628 return 0;
2629 }
2630
2631 // filter devices according to output selected
2632 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2633
2634 audio_devices_t prevDevice = outputDesc->mDevice;
2635
2636 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2637
2638 if (device != AUDIO_DEVICE_NONE) {
2639 outputDesc->mDevice = device;
2640 }
2641 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2642
2643 // Do not change the routing if:
2644 // - the requested device is AUDIO_DEVICE_NONE
2645 // - the requested device is the same as current device and force is not specified.
2646 // Doing this check here allows the caller to call setOutputDevice() without conditions
2647 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2648 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2649 return muteWaitMs;
2650 }
2651
2652 ALOGV("setOutputDevice() changing device");
2653 // do the routing
2654 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2655 mpClientInterface->setParameters(output, param.toString(), delayMs);
2656
2657 // update stream volumes according to new device
2658 applyStreamVolumes(output, device, delayMs);
2659
2660 return muteWaitMs;
2661}
2662
2663AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2664 uint32_t samplingRate,
2665 audio_format_t format,
2666 audio_channel_mask_t channelMask)
2667{
2668 // Choose an input profile based on the requested capture parameters: select the first available
2669 // profile supporting all requested parameters.
2670
2671 for (size_t i = 0; i < mHwModules.size(); i++)
2672 {
2673 if (mHwModules[i]->mHandle == 0) {
2674 continue;
2675 }
2676 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2677 {
2678 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2679 if (profile->isCompatibleProfile(device, samplingRate, format,
2680 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
2681 return profile;
2682 }
2683 }
2684 }
2685 return NULL;
2686}
2687
2688audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2689{
2690 uint32_t device = AUDIO_DEVICE_NONE;
2691
2692 switch (inputSource) {
2693 case AUDIO_SOURCE_VOICE_UPLINK:
2694 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2695 device = AUDIO_DEVICE_IN_VOICE_CALL;
2696 break;
2697 }
2698 // FALL THROUGH
2699
2700 case AUDIO_SOURCE_DEFAULT:
2701 case AUDIO_SOURCE_MIC:
2702 case AUDIO_SOURCE_VOICE_RECOGNITION:
2703 case AUDIO_SOURCE_HOTWORD:
2704 case AUDIO_SOURCE_VOICE_COMMUNICATION:
2705 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2706 mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2707 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2708 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2709 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2710 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2711 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2712 }
2713 break;
2714 case AUDIO_SOURCE_CAMCORDER:
2715 if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2716 device = AUDIO_DEVICE_IN_BACK_MIC;
2717 } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2718 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2719 }
2720 break;
2721 case AUDIO_SOURCE_VOICE_DOWNLINK:
2722 case AUDIO_SOURCE_VOICE_CALL:
2723 if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2724 device = AUDIO_DEVICE_IN_VOICE_CALL;
2725 }
2726 break;
2727 case AUDIO_SOURCE_REMOTE_SUBMIX:
2728 if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2729 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2730 }
2731 break;
2732 default:
2733 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2734 break;
2735 }
2736 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2737 return device;
2738}
2739
2740bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2741{
2742 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2743 device &= ~AUDIO_DEVICE_BIT_IN;
2744 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2745 return true;
2746 }
2747 return false;
2748}
2749
2750audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2751{
2752 for (size_t i = 0; i < mInputs.size(); i++) {
2753 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2754 if ((input_descriptor->mRefCount > 0)
2755 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2756 return mInputs.keyAt(i);
2757 }
2758 }
2759 return 0;
2760}
2761
2762
2763audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2764{
2765 if (device == AUDIO_DEVICE_NONE) {
2766 // this happens when forcing a route update and no track is active on an output.
2767 // In this case the returned category is not important.
2768 device = AUDIO_DEVICE_OUT_SPEAKER;
2769 } else if (AudioSystem::popCount(device) > 1) {
2770 // Multiple device selection is either:
2771 // - speaker + one other device: give priority to speaker in this case.
2772 // - one A2DP device + another device: happens with duplicated output. In this case
2773 // retain the device on the A2DP output as the other must not correspond to an active
2774 // selection if not the speaker.
2775 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2776 device = AUDIO_DEVICE_OUT_SPEAKER;
2777 } else {
2778 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2779 }
2780 }
2781
2782 ALOGW_IF(AudioSystem::popCount(device) != 1,
2783 "getDeviceForVolume() invalid device combination: %08x",
2784 device);
2785
2786 return device;
2787}
2788
2789AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2790{
2791 switch(getDeviceForVolume(device)) {
2792 case AUDIO_DEVICE_OUT_EARPIECE:
2793 return DEVICE_CATEGORY_EARPIECE;
2794 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2795 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2796 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2797 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2798 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2799 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2800 return DEVICE_CATEGORY_HEADSET;
2801 case AUDIO_DEVICE_OUT_SPEAKER:
2802 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2803 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2804 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2805 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2806 case AUDIO_DEVICE_OUT_USB_DEVICE:
2807 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
2808 default:
2809 return DEVICE_CATEGORY_SPEAKER;
2810 }
2811}
2812
2813float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2814 int indexInUi)
2815{
2816 device_category deviceCategory = getDeviceCategory(device);
2817 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2818
2819 // the volume index in the UI is relative to the min and max volume indices for this stream type
2820 int nbSteps = 1 + curve[VOLMAX].mIndex -
2821 curve[VOLMIN].mIndex;
2822 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2823 (streamDesc.mIndexMax - streamDesc.mIndexMin);
2824
2825 // find what part of the curve this index volume belongs to, or if it's out of bounds
2826 int segment = 0;
2827 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
2828 return 0.0f;
2829 } else if (volIdx < curve[VOLKNEE1].mIndex) {
2830 segment = 0;
2831 } else if (volIdx < curve[VOLKNEE2].mIndex) {
2832 segment = 1;
2833 } else if (volIdx <= curve[VOLMAX].mIndex) {
2834 segment = 2;
2835 } else { // out of bounds
2836 return 1.0f;
2837 }
2838
2839 // linear interpolation in the attenuation table in dB
2840 float decibels = curve[segment].mDBAttenuation +
2841 ((float)(volIdx - curve[segment].mIndex)) *
2842 ( (curve[segment+1].mDBAttenuation -
2843 curve[segment].mDBAttenuation) /
2844 ((float)(curve[segment+1].mIndex -
2845 curve[segment].mIndex)) );
2846
2847 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2848
2849 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2850 curve[segment].mIndex, volIdx,
2851 curve[segment+1].mIndex,
2852 curve[segment].mDBAttenuation,
2853 decibels,
2854 curve[segment+1].mDBAttenuation,
2855 amplification);
2856
2857 return amplification;
2858}
2859
2860const AudioPolicyManagerBase::VolumeCurvePoint
2861 AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2862 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2863};
2864
2865const AudioPolicyManagerBase::VolumeCurvePoint
2866 AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2867 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2868};
2869
2870const AudioPolicyManagerBase::VolumeCurvePoint
2871 AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2872 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2873};
2874
2875const AudioPolicyManagerBase::VolumeCurvePoint
2876 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2877 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2878};
2879
2880const AudioPolicyManagerBase::VolumeCurvePoint
2881 AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
2882 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
2883};
2884
2885// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2886// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
2887// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
2888// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2889
2890const AudioPolicyManagerBase::VolumeCurvePoint
2891 AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2892 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2893};
2894
2895const AudioPolicyManagerBase::VolumeCurvePoint
2896 AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
2897 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
2898};
2899
2900const AudioPolicyManagerBase::VolumeCurvePoint
2901 AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2902 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2903};
2904
2905const AudioPolicyManagerBase::VolumeCurvePoint
2906 AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2907 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
2908};
2909
2910const AudioPolicyManagerBase::VolumeCurvePoint
2911 AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2912 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
2913};
2914
2915const AudioPolicyManagerBase::VolumeCurvePoint
2916 *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2917 [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2918 { // AUDIO_STREAM_VOICE_CALL
2919 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2920 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2921 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2922 },
2923 { // AUDIO_STREAM_SYSTEM
2924 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2925 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2926 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2927 },
2928 { // AUDIO_STREAM_RING
2929 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2930 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2931 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2932 },
2933 { // AUDIO_STREAM_MUSIC
2934 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2935 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2936 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2937 },
2938 { // AUDIO_STREAM_ALARM
2939 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2940 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2941 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2942 },
2943 { // AUDIO_STREAM_NOTIFICATION
2944 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2945 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2946 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
2947 },
2948 { // AUDIO_STREAM_BLUETOOTH_SCO
2949 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
2950 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2951 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
2952 },
2953 { // AUDIO_STREAM_ENFORCED_AUDIBLE
2954 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2955 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2956 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2957 },
2958 { // AUDIO_STREAM_DTMF
2959 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2960 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2961 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
2962 },
2963 { // AUDIO_STREAM_TTS
2964 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2965 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2966 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
2967 },
2968};
2969
2970void AudioPolicyManagerBase::initializeVolumeCurves()
2971{
2972 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2973 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2974 mStreams[i].mVolumeCurve[j] =
2975 sVolumeProfiles[i][j];
2976 }
2977 }
2978
2979 // Check availability of DRC on speaker path: if available, override some of the speaker curves
2980 if (mSpeakerDrcEnabled) {
2981 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2982 sDefaultSystemVolumeCurveDrc;
2983 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2984 sSpeakerSonificationVolumeCurveDrc;
2985 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2986 sSpeakerSonificationVolumeCurveDrc;
2987 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
2988 sSpeakerSonificationVolumeCurveDrc;
2989 }
2990}
2991
2992float AudioPolicyManagerBase::computeVolume(int stream,
2993 int index,
2994 audio_io_handle_t output,
2995 audio_devices_t device)
2996{
2997 float volume = 1.0;
2998 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2999 StreamDescriptor &streamDesc = mStreams[stream];
3000
3001 if (device == AUDIO_DEVICE_NONE) {
3002 device = outputDesc->device();
3003 }
3004
3005 // if volume is not 0 (not muted), force media volume to max on digital output
3006 if (stream == AudioSystem::MUSIC &&
3007 index != mStreams[stream].mIndexMin &&
3008 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3009 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
3010 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
3011 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
3012 return 1.0;
3013 }
3014
3015 volume = volIndexToAmpl(device, streamDesc, index);
3016
3017 // if a headset is connected, apply the following rules to ring tones and notifications
3018 // to avoid sound level bursts in user's ears:
3019 // - always attenuate ring tones and notifications volume by 6dB
3020 // - if music is playing, always limit the volume to current music volume,
3021 // with a minimum threshold at -36dB so that notification is always perceived.
3022 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3023 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3024 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3025 AUDIO_DEVICE_OUT_WIRED_HEADSET |
3026 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3027 ((stream_strategy == STRATEGY_SONIFICATION)
3028 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
3029 || (stream == AudioSystem::SYSTEM)
3030 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
3031 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
3032 streamDesc.mCanBeMuted) {
3033 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3034 // when the phone is ringing we must consider that music could have been paused just before
3035 // by the music application and behave as if music was active if the last music track was
3036 // just stopped
3037 if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
3038 mLimitRingtoneVolume) {
3039 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
3040 float musicVol = computeVolume(AudioSystem::MUSIC,
3041 mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
3042 output,
3043 musicDevice);
3044 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3045 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3046 if (volume > minVol) {
3047 volume = minVol;
3048 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3049 }
3050 }
3051 }
3052
3053 return volume;
3054}
3055
3056status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
3057 int index,
3058 audio_io_handle_t output,
3059 audio_devices_t device,
3060 int delayMs,
3061 bool force)
3062{
3063
3064 // do not change actual stream volume if the stream is muted
3065 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3066 ALOGVV("checkAndSetVolume() stream %d muted count %d",
3067 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3068 return NO_ERROR;
3069 }
3070
3071 // do not change in call volume if bluetooth is connected and vice versa
3072 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
3073 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
3074 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
3075 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
3076 return INVALID_OPERATION;
3077 }
3078
3079 float volume = computeVolume(stream, index, output, device);
3080 // We actually change the volume if:
3081 // - the float value returned by computeVolume() changed
3082 // - the force flag is set
3083 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3084 force) {
3085 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3086 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3087 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3088 // enabled
3089 if (stream == AudioSystem::BLUETOOTH_SCO) {
3090 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
3091 }
3092 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
3093 }
3094
3095 if (stream == AudioSystem::VOICE_CALL ||
3096 stream == AudioSystem::BLUETOOTH_SCO) {
3097 float voiceVolume;
3098 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3099 if (stream == AudioSystem::VOICE_CALL) {
3100 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3101 } else {
3102 voiceVolume = 1.0;
3103 }
3104
3105 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3106 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3107 mLastVoiceVolume = voiceVolume;
3108 }
3109 }
3110
3111 return NO_ERROR;
3112}
3113
3114void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
3115 audio_devices_t device,
3116 int delayMs,
3117 bool force)
3118{
3119 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3120
3121 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3122 checkAndSetVolume(stream,
3123 mStreams[stream].getVolumeIndex(device),
3124 output,
3125 device,
3126 delayMs,
3127 force);
3128 }
3129}
3130
3131void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
3132 bool on,
3133 audio_io_handle_t output,
3134 int delayMs,
3135 audio_devices_t device)
3136{
3137 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3138 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3139 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3140 setStreamMute(stream, on, output, delayMs, device);
3141 }
3142 }
3143}
3144
3145void AudioPolicyManagerBase::setStreamMute(int stream,
3146 bool on,
3147 audio_io_handle_t output,
3148 int delayMs,
3149 audio_devices_t device)
3150{
3151 StreamDescriptor &streamDesc = mStreams[stream];
3152 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3153 if (device == AUDIO_DEVICE_NONE) {
3154 device = outputDesc->device();
3155 }
3156
3157 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3158 stream, on, output, outputDesc->mMuteCount[stream], device);
3159
3160 if (on) {
3161 if (outputDesc->mMuteCount[stream] == 0) {
3162 if (streamDesc.mCanBeMuted &&
3163 ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3164 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3165 checkAndSetVolume(stream, 0, output, device, delayMs);
3166 }
3167 }
3168 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3169 outputDesc->mMuteCount[stream]++;
3170 } else {
3171 if (outputDesc->mMuteCount[stream] == 0) {
3172 ALOGV("setStreamMute() unmuting non muted stream!");
3173 return;
3174 }
3175 if (--outputDesc->mMuteCount[stream] == 0) {
3176 checkAndSetVolume(stream,
3177 streamDesc.getVolumeIndex(device),
3178 output,
3179 device,
3180 delayMs);
3181 }
3182 }
3183}
3184
3185void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3186{
3187 // if the stream pertains to sonification strategy and we are in call we must
3188 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3189 // in the device used for phone strategy and play the tone if the selected device does not
3190 // interfere with the device used for phone strategy
3191 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3192 // many times as there are active tracks on the output
3193 const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3194 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3195 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3196 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3197 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3198 stream, starting, outputDesc->mDevice, stateChange);
3199 if (outputDesc->mRefCount[stream]) {
3200 int muteCount = 1;
3201 if (stateChange) {
3202 muteCount = outputDesc->mRefCount[stream];
3203 }
3204 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3205 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3206 for (int i = 0; i < muteCount; i++) {
3207 setStreamMute(stream, starting, mPrimaryOutput);
3208 }
3209 } else {
3210 ALOGV("handleIncallSonification() high visibility");
3211 if (outputDesc->device() &
3212 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3213 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3214 for (int i = 0; i < muteCount; i++) {
3215 setStreamMute(stream, starting, mPrimaryOutput);
3216 }
3217 }
3218 if (starting) {
3219 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3220 } else {
3221 mpClientInterface->stopTone();
3222 }
3223 }
3224 }
3225 }
3226}
3227
3228bool AudioPolicyManagerBase::isInCall()
3229{
3230 return isStateInCall(mPhoneState);
3231}
3232
3233bool AudioPolicyManagerBase::isStateInCall(int state) {
3234 return ((state == AudioSystem::MODE_IN_CALL) ||
3235 (state == AudioSystem::MODE_IN_COMMUNICATION));
3236}
3237
3238uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3239{
3240 return MAX_EFFECTS_CPU_LOAD;
3241}
3242
3243uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3244{
3245 return MAX_EFFECTS_MEMORY;
3246}
3247
3248// --- AudioOutputDescriptor class implementation
3249
3250AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3251 const IOProfile *profile)
3252 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3253 mChannelMask(0), mLatency(0),
3254 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3255 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3256{
3257 // clear usage count for all stream types
3258 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3259 mRefCount[i] = 0;
3260 mCurVolume[i] = -1.0;
3261 mMuteCount[i] = 0;
3262 mStopTime[i] = 0;
3263 }
3264 for (int i = 0; i < NUM_STRATEGIES; i++) {
3265 mStrategyMutedByDevice[i] = false;
3266 }
3267 if (profile != NULL) {
3268 mSamplingRate = profile->mSamplingRates[0];
3269 mFormat = profile->mFormats[0];
3270 mChannelMask = profile->mChannelMasks[0];
3271 mFlags = profile->mFlags;
3272 }
3273}
3274
3275audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3276{
3277 if (isDuplicated()) {
3278 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3279 } else {
3280 return mDevice;
3281 }
3282}
3283
3284uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3285{
3286 if (isDuplicated()) {
3287 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3288 } else {
3289 return mLatency;
3290 }
3291}
3292
3293bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3294 const AudioOutputDescriptor *outputDesc)
3295{
3296 if (isDuplicated()) {
3297 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3298 } else if (outputDesc->isDuplicated()){
3299 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3300 } else {
3301 return (mProfile->mModule == outputDesc->mProfile->mModule);
3302 }
3303}
3304
3305void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3306{
3307 // forward usage count change to attached outputs
3308 if (isDuplicated()) {
3309 mOutput1->changeRefCount(stream, delta);
3310 mOutput2->changeRefCount(stream, delta);
3311 }
3312 if ((delta + (int)mRefCount[stream]) < 0) {
3313 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3314 mRefCount[stream] = 0;
3315 return;
3316 }
3317 mRefCount[stream] += delta;
3318 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3319}
3320
3321audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3322{
3323 if (isDuplicated()) {
3324 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3325 } else {
3326 return mProfile->mSupportedDevices ;
3327 }
3328}
3329
3330bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3331{
3332 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3333}
3334
3335bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3336 uint32_t inPastMs,
3337 nsecs_t sysTime) const
3338{
3339 if ((sysTime == 0) && (inPastMs != 0)) {
3340 sysTime = systemTime();
3341 }
3342 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3343 if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3344 (NUM_STRATEGIES == strategy)) &&
3345 isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3346 return true;
3347 }
3348 }
3349 return false;
3350}
3351
3352bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3353 uint32_t inPastMs,
3354 nsecs_t sysTime) const
3355{
3356 if (mRefCount[stream] != 0) {
3357 return true;
3358 }
3359 if (inPastMs == 0) {
3360 return false;
3361 }
3362 if (sysTime == 0) {
3363 sysTime = systemTime();
3364 }
3365 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3366 return true;
3367 }
3368 return false;
3369}
3370
3371
3372status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3373{
3374 const size_t SIZE = 256;
3375 char buffer[SIZE];
3376 String8 result;
3377
3378 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3379 result.append(buffer);
3380 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3381 result.append(buffer);
3382 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3383 result.append(buffer);
3384 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3385 result.append(buffer);
3386 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3387 result.append(buffer);
3388 snprintf(buffer, SIZE, " Devices %08x\n", device());
3389 result.append(buffer);
3390 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3391 result.append(buffer);
3392 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3393 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3394 result.append(buffer);
3395 }
3396 write(fd, result.string(), result.size());
3397
3398 return NO_ERROR;
3399}
3400
3401// --- AudioInputDescriptor class implementation
3402
3403AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3404 : mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
3405 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3406 mInputSource(0), mProfile(profile)
3407{
3408}
3409
3410status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3411{
3412 const size_t SIZE = 256;
3413 char buffer[SIZE];
3414 String8 result;
3415
3416 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3417 result.append(buffer);
3418 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3419 result.append(buffer);
3420 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3421 result.append(buffer);
3422 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3423 result.append(buffer);
3424 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3425 result.append(buffer);
3426 write(fd, result.string(), result.size());
3427
3428 return NO_ERROR;
3429}
3430
3431// --- StreamDescriptor class implementation
3432
3433AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3434 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3435{
3436 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3437}
3438
3439int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3440{
3441 device = AudioPolicyManagerBase::getDeviceForVolume(device);
3442 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3443 if (mIndexCur.indexOfKey(device) < 0) {
3444 device = AUDIO_DEVICE_OUT_DEFAULT;
3445 }
3446 return mIndexCur.valueFor(device);
3447}
3448
3449void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3450{
3451 const size_t SIZE = 256;
3452 char buffer[SIZE];
3453 String8 result;
3454
3455 snprintf(buffer, SIZE, "%s %02d %02d ",
3456 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3457 result.append(buffer);
3458 for (size_t i = 0; i < mIndexCur.size(); i++) {
3459 snprintf(buffer, SIZE, "%04x : %02d, ",
3460 mIndexCur.keyAt(i),
3461 mIndexCur.valueAt(i));
3462 result.append(buffer);
3463 }
3464 result.append("\n");
3465
3466 write(fd, result.string(), result.size());
3467}
3468
3469// --- EffectDescriptor class implementation
3470
3471status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3472{
3473 const size_t SIZE = 256;
3474 char buffer[SIZE];
3475 String8 result;
3476
3477 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3478 result.append(buffer);
3479 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3480 result.append(buffer);
3481 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3482 result.append(buffer);
3483 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3484 result.append(buffer);
3485 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3486 result.append(buffer);
3487 write(fd, result.string(), result.size());
3488
3489 return NO_ERROR;
3490}
3491
3492// --- IOProfile class implementation
3493
3494AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3495 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3496{
3497}
3498
3499AudioPolicyManagerBase::HwModule::~HwModule()
3500{
3501 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3502 delete mOutputProfiles[i];
3503 }
3504 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3505 delete mInputProfiles[i];
3506 }
3507 free((void *)mName);
3508}
3509
3510void AudioPolicyManagerBase::HwModule::dump(int fd)
3511{
3512 const size_t SIZE = 256;
3513 char buffer[SIZE];
3514 String8 result;
3515
3516 snprintf(buffer, SIZE, " - name: %s\n", mName);
3517 result.append(buffer);
3518 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3519 result.append(buffer);
3520 write(fd, result.string(), result.size());
3521 if (mOutputProfiles.size()) {
3522 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
3523 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3524 snprintf(buffer, SIZE, " output %d:\n", i);
3525 write(fd, buffer, strlen(buffer));
3526 mOutputProfiles[i]->dump(fd);
3527 }
3528 }
3529 if (mInputProfiles.size()) {
3530 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
3531 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3532 snprintf(buffer, SIZE, " input %d:\n", i);
3533 write(fd, buffer, strlen(buffer));
3534 mInputProfiles[i]->dump(fd);
3535 }
3536 }
3537}
3538
3539AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3540 : mFlags((audio_output_flags_t)0), mModule(module)
3541{
3542}
3543
3544AudioPolicyManagerBase::IOProfile::~IOProfile()
3545{
3546}
3547
3548// checks if the IO profile is compatible with specified parameters.
3549// Sampling rate, format and channel mask must be specified in order to
3550// get a valid a match
3551bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3552 uint32_t samplingRate,
3553 audio_format_t format,
3554 audio_channel_mask_t channelMask,
3555 audio_output_flags_t flags) const
3556{
3557 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3558 return false;
3559 }
3560
3561 if ((mSupportedDevices & device) != device) {
3562 return false;
3563 }
3564 if ((mFlags & flags) != flags) {
3565 return false;
3566 }
3567 size_t i;
3568 for (i = 0; i < mSamplingRates.size(); i++)
3569 {
3570 if (mSamplingRates[i] == samplingRate) {
3571 break;
3572 }
3573 }
3574 if (i == mSamplingRates.size()) {
3575 return false;
3576 }
3577 for (i = 0; i < mFormats.size(); i++)
3578 {
3579 if (mFormats[i] == format) {
3580 break;
3581 }
3582 }
3583 if (i == mFormats.size()) {
3584 return false;
3585 }
3586 for (i = 0; i < mChannelMasks.size(); i++)
3587 {
3588 if (mChannelMasks[i] == channelMask) {
3589 break;
3590 }
3591 }
3592 if (i == mChannelMasks.size()) {
3593 return false;
3594 }
3595 return true;
3596}
3597
3598void AudioPolicyManagerBase::IOProfile::dump(int fd)
3599{
3600 const size_t SIZE = 256;
3601 char buffer[SIZE];
3602 String8 result;
3603
3604 snprintf(buffer, SIZE, " - sampling rates: ");
3605 result.append(buffer);
3606 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3607 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3608 result.append(buffer);
3609 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3610 }
3611
3612 snprintf(buffer, SIZE, " - channel masks: ");
3613 result.append(buffer);
3614 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3615 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3616 result.append(buffer);
3617 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3618 }
3619
3620 snprintf(buffer, SIZE, " - formats: ");
3621 result.append(buffer);
3622 for (size_t i = 0; i < mFormats.size(); i++) {
3623 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3624 result.append(buffer);
3625 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3626 }
3627
3628 snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
3629 result.append(buffer);
3630 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3631 result.append(buffer);
3632
3633 write(fd, result.string(), result.size());
3634}
3635
3636// --- audio_policy.conf file parsing
3637
3638struct StringToEnum {
3639 const char *name;
3640 uint32_t value;
3641};
3642
3643#define STRING_TO_ENUM(string) { #string, string }
3644#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3645
3646const struct StringToEnum sDeviceNameToEnumTable[] = {
3647 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3648 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3649 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3650 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3651 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3652 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3653 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3654 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3655 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3656 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3657 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3658 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3659 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3660 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3661 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3662 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3663 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3664 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3665 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3666 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3667 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3668 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3669 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3670};
3671
3672const struct StringToEnum sFlagNameToEnumTable[] = {
3673 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3674 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3675 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3676 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3677 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3678 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3679};
3680
3681const struct StringToEnum sFormatNameToEnumTable[] = {
3682 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3683 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3684 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
3685 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
3686 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
3687 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
3688 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3689 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3690 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3691};
3692
3693const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3694 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3695 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3696 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3697 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3698};
3699
3700const struct StringToEnum sInChannelsNameToEnumTable[] = {
3701 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3702 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3703 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3704};
3705
3706
3707uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3708 size_t size,
3709 const char *name)
3710{
3711 for (size_t i = 0; i < size; i++) {
3712 if (strcmp(table[i].name, name) == 0) {
3713 ALOGV("stringToEnum() found %s", table[i].name);
3714 return table[i].value;
3715 }
3716 }
3717 return 0;
3718}
3719
3720bool AudioPolicyManagerBase::stringToBool(const char *value)
3721{
3722 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
3723}
3724
3725audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3726{
3727 uint32_t flag = 0;
3728
3729 // it is OK to cast name to non const here as we are not going to use it after
3730 // strtok() modifies it
3731 char *flagName = strtok(name, "|");
3732 while (flagName != NULL) {
3733 if (strlen(flagName) != 0) {
3734 flag |= stringToEnum(sFlagNameToEnumTable,
3735 ARRAY_SIZE(sFlagNameToEnumTable),
3736 flagName);
3737 }
3738 flagName = strtok(NULL, "|");
3739 }
3740 //force direct flag if offload flag is set: offloading implies a direct output stream
3741 // and all common behaviors are driven by checking only the direct flag
3742 // this should normally be set appropriately in the policy configuration file
3743 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3744 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
3745 }
3746
3747 return (audio_output_flags_t)flag;
3748}
3749
3750audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3751{
3752 uint32_t device = 0;
3753
3754 char *devName = strtok(name, "|");
3755 while (devName != NULL) {
3756 if (strlen(devName) != 0) {
3757 device |= stringToEnum(sDeviceNameToEnumTable,
3758 ARRAY_SIZE(sDeviceNameToEnumTable),
3759 devName);
3760 }
3761 devName = strtok(NULL, "|");
3762 }
3763 return device;
3764}
3765
3766void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3767{
3768 char *str = strtok(name, "|");
3769
3770 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3771 // rates should be read from the output stream after it is opened for the first time
3772 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3773 profile->mSamplingRates.add(0);
3774 return;
3775 }
3776
3777 while (str != NULL) {
3778 uint32_t rate = atoi(str);
3779 if (rate != 0) {
3780 ALOGV("loadSamplingRates() adding rate %d", rate);
3781 profile->mSamplingRates.add(rate);
3782 }
3783 str = strtok(NULL, "|");
3784 }
3785 return;
3786}
3787
3788void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3789{
3790 char *str = strtok(name, "|");
3791
3792 // by convention, "0' in the first entry in mFormats indicates the supported formats
3793 // should be read from the output stream after it is opened for the first time
3794 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3795 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3796 return;
3797 }
3798
3799 while (str != NULL) {
3800 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3801 ARRAY_SIZE(sFormatNameToEnumTable),
3802 str);
3803 if (format != AUDIO_FORMAT_DEFAULT) {
3804 profile->mFormats.add(format);
3805 }
3806 str = strtok(NULL, "|");
3807 }
3808 return;
3809}
3810
3811void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3812{
3813 const char *str = strtok(name, "|");
3814
3815 ALOGV("loadInChannels() %s", name);
3816
3817 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3818 profile->mChannelMasks.add(0);
3819 return;
3820 }
3821
3822 while (str != NULL) {
3823 audio_channel_mask_t channelMask =
3824 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3825 ARRAY_SIZE(sInChannelsNameToEnumTable),
3826 str);
3827 if (channelMask != 0) {
3828 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3829 profile->mChannelMasks.add(channelMask);
3830 }
3831 str = strtok(NULL, "|");
3832 }
3833 return;
3834}
3835
3836void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3837{
3838 const char *str = strtok(name, "|");
3839
3840 ALOGV("loadOutChannels() %s", name);
3841
3842 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3843 // masks should be read from the output stream after it is opened for the first time
3844 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3845 profile->mChannelMasks.add(0);
3846 return;
3847 }
3848
3849 while (str != NULL) {
3850 audio_channel_mask_t channelMask =
3851 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3852 ARRAY_SIZE(sOutChannelsNameToEnumTable),
3853 str);
3854 if (channelMask != 0) {
3855 profile->mChannelMasks.add(channelMask);
3856 }
3857 str = strtok(NULL, "|");
3858 }
3859 return;
3860}
3861
3862status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3863{
3864 cnode *node = root->first_child;
3865
3866 IOProfile *profile = new IOProfile(module);
3867
3868 while (node) {
3869 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3870 loadSamplingRates((char *)node->value, profile);
3871 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3872 loadFormats((char *)node->value, profile);
3873 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3874 loadInChannels((char *)node->value, profile);
3875 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3876 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3877 }
3878 node = node->next;
3879 }
3880 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3881 "loadInput() invalid supported devices");
3882 ALOGW_IF(profile->mChannelMasks.size() == 0,
3883 "loadInput() invalid supported channel masks");
3884 ALOGW_IF(profile->mSamplingRates.size() == 0,
3885 "loadInput() invalid supported sampling rates");
3886 ALOGW_IF(profile->mFormats.size() == 0,
3887 "loadInput() invalid supported formats");
3888 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3889 (profile->mChannelMasks.size() != 0) &&
3890 (profile->mSamplingRates.size() != 0) &&
3891 (profile->mFormats.size() != 0)) {
3892
3893 ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3894
3895 module->mInputProfiles.add(profile);
3896 return NO_ERROR;
3897 } else {
3898 delete profile;
3899 return BAD_VALUE;
3900 }
3901}
3902
3903status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3904{
3905 cnode *node = root->first_child;
3906
3907 IOProfile *profile = new IOProfile(module);
3908
3909 while (node) {
3910 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3911 loadSamplingRates((char *)node->value, profile);
3912 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3913 loadFormats((char *)node->value, profile);
3914 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3915 loadOutChannels((char *)node->value, profile);
3916 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3917 profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3918 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3919 profile->mFlags = parseFlagNames((char *)node->value);
3920 }
3921 node = node->next;
3922 }
3923 ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
3924 "loadOutput() invalid supported devices");
3925 ALOGW_IF(profile->mChannelMasks.size() == 0,
3926 "loadOutput() invalid supported channel masks");
3927 ALOGW_IF(profile->mSamplingRates.size() == 0,
3928 "loadOutput() invalid supported sampling rates");
3929 ALOGW_IF(profile->mFormats.size() == 0,
3930 "loadOutput() invalid supported formats");
3931 if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
3932 (profile->mChannelMasks.size() != 0) &&
3933 (profile->mSamplingRates.size() != 0) &&
3934 (profile->mFormats.size() != 0)) {
3935
3936 ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3937 profile->mSupportedDevices, profile->mFlags);
3938
3939 module->mOutputProfiles.add(profile);
3940 return NO_ERROR;
3941 } else {
3942 delete profile;
3943 return BAD_VALUE;
3944 }
3945}
3946
3947void AudioPolicyManagerBase::loadHwModule(cnode *root)
3948{
3949 cnode *node = config_find(root, OUTPUTS_TAG);
3950 status_t status = NAME_NOT_FOUND;
3951
3952 HwModule *module = new HwModule(root->name);
3953
3954 if (node != NULL) {
3955 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3956 mHasA2dp = true;
3957 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3958 mHasUsb = true;
3959 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
3960 mHasRemoteSubmix = true;
3961 }
3962
3963 node = node->first_child;
3964 while (node) {
3965 ALOGV("loadHwModule() loading output %s", node->name);
3966 status_t tmpStatus = loadOutput(node, module);
3967 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3968 status = tmpStatus;
3969 }
3970 node = node->next;
3971 }
3972 }
3973 node = config_find(root, INPUTS_TAG);
3974 if (node != NULL) {
3975 node = node->first_child;
3976 while (node) {
3977 ALOGV("loadHwModule() loading input %s", node->name);
3978 status_t tmpStatus = loadInput(node, module);
3979 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3980 status = tmpStatus;
3981 }
3982 node = node->next;
3983 }
3984 }
3985 if (status == NO_ERROR) {
3986 mHwModules.add(module);
3987 } else {
3988 delete module;
3989 }
3990}
3991
3992void AudioPolicyManagerBase::loadHwModules(cnode *root)
3993{
3994 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3995 if (node == NULL) {
3996 return;
3997 }
3998
3999 node = node->first_child;
4000 while (node) {
4001 ALOGV("loadHwModules() loading module %s", node->name);
4002 loadHwModule(node);
4003 node = node->next;
4004 }
4005}
4006
4007void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
4008{
4009 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4010 if (node == NULL) {
4011 return;
4012 }
4013 node = node->first_child;
4014 while (node) {
4015 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
4016 mAttachedOutputDevices = parseDeviceNames((char *)node->value);
4017 ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
4018 "loadGlobalConfig() no attached output devices");
4019 ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
4020 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
4021 mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
4022 ARRAY_SIZE(sDeviceNameToEnumTable),
4023 (char *)node->value);
4024 ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
4025 "loadGlobalConfig() default device not specified");
4026 ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
4027 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
4028 mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
4029 ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
4030 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4031 mSpeakerDrcEnabled = stringToBool((char *)node->value);
4032 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4033 }
4034 node = node->next;
4035 }
4036}
4037
4038status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
4039{
4040 cnode *root;
4041 char *data;
4042
4043 data = (char *)load_file(path, NULL);
4044 if (data == NULL) {
4045 return -ENODEV;
4046 }
4047 root = config_node("", "");
4048 config_load(root, data);
4049
4050 loadGlobalConfig(root);
4051 loadHwModules(root);
4052
4053 config_free(root);
4054 free(root);
4055 free(data);
4056
4057 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4058
4059 return NO_ERROR;
4060}
4061
4062void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
4063{
4064 HwModule *module;
4065 IOProfile *profile;
4066
4067 mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
4068 mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
4069 mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
4070
4071 module = new HwModule("primary");
4072
4073 profile = new IOProfile(module);
4074 profile->mSamplingRates.add(44100);
4075 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4076 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4077 profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
4078 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4079 module->mOutputProfiles.add(profile);
4080
4081 profile = new IOProfile(module);
4082 profile->mSamplingRates.add(8000);
4083 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4084 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4085 profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
4086 module->mInputProfiles.add(profile);
4087
4088 mHwModules.add(module);
4089}
4090
4091}; // namespace android