blob: ab933a0d63ed126e0fb72e69aecdb780551f04f8 [file] [log] [blame]
Marko Manef8d7e42018-08-26 23:20:31 +02001/*
2 * Copyright (c) 2013-2018 The Linux Foundation. All rights reserved.
3 * Not a contribution.
4 *
5 * Copyright (C) 2009 The Android Open Source Project
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20#define LOG_TAG "AudioPolicyManagerCustom"
21//#define LOG_NDEBUG 0
22
23//#define VERY_VERBOSE_LOGGING
24#ifdef VERY_VERBOSE_LOGGING
25#define ALOGVV ALOGV
26#else
27#define ALOGVV(a...) do { } while(0)
28#endif
29
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// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
37#define SAMPLE_RATE_8000 8000
38#include <inttypes.h>
39#include <math.h>
40
41#include <cutils/properties.h>
42#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
45#include <media/AudioParameter.h>
46#include <soundtrigger/SoundTrigger.h>
47#include "AudioPolicyManager.h"
48#include <policy.h>
49
50namespace android {
51/*audio policy: workaround for truncated touch sounds*/
52//FIXME: workaround for truncated touch sounds
53// to be removed when the problem is handled by system UI
54#define TOUCH_SOUND_FIXED_DELAY_MS 100
55#ifdef VOICE_CONCURRENCY
56audio_output_flags_t AudioPolicyManagerCustom::getFallBackPath()
57{
58 audio_output_flags_t flag = AUDIO_OUTPUT_FLAG_FAST;
59 char propValue[PROPERTY_VALUE_MAX];
60
61 if (property_get("vendor.voice.conc.fallbackpath", propValue, NULL)) {
62 if (!strncmp(propValue, "deep-buffer", 11)) {
63 flag = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
64 }
65 else if (!strncmp(propValue, "fast", 4)) {
66 flag = AUDIO_OUTPUT_FLAG_FAST;
67 }
68 else {
69 ALOGD("voice_conc:not a recognised path(%s) in prop vendor.voice.conc.fallbackpath",
70 propValue);
71 }
72 }
73 else {
74 ALOGD("voice_conc:prop vendor.voice.conc.fallbackpath not set");
75 }
76
77 ALOGD("voice_conc:picked up flag(0x%x) from prop vendor.voice.conc.fallbackpath",
78 flag);
79
80 return flag;
81}
82#endif /*VOICE_CONCURRENCY*/
83
84void AudioPolicyManagerCustom::moveGlobalEffect()
85{
86 audio_io_handle_t dstOutput = getOutputForEffect();
87 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle)
88 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
89 mPrimaryOutput->mIoHandle, dstOutput);
90}
91
92// ----------------------------------------------------------------------------
93// AudioPolicyInterface implementation
94// ----------------------------------------------------------------------------
95extern "C" AudioPolicyInterface* createAudioPolicyManager(
96 AudioPolicyClientInterface *clientInterface)
97{
98 return new AudioPolicyManagerCustom(clientInterface);
99}
100
101extern "C" void destroyAudioPolicyManager(AudioPolicyInterface *interface)
102{
103 delete interface;
104}
105
106status_t AudioPolicyManagerCustom::setDeviceConnectionStateInt(audio_devices_t device,
107 audio_policy_dev_state_t state,
108 const char *device_address,
109 const char *device_name)
110{
111 ALOGD("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
112 device, state, device_address, device_name);
113
114 // connect/disconnect only 1 device at a time
115 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
116
117 sp<DeviceDescriptor> devDesc =
118 mHwModules.getDeviceDescriptor(device, device_address, device_name);
119
120 // handle output devices
121 if (audio_is_output_device(device)) {
122 SortedVector <audio_io_handle_t> outputs;
123
124 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
125
126 // save a copy of the opened output descriptors before any output is opened or closed
127 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
128 mPreviousOutputs = mOutputs;
129 switch (state)
130 {
131 // handle output device connection
132 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
133 if (index >= 0) {
134#ifdef AUDIO_EXTN_HDMI_SPK_ENABLED
135 if ((popcount(device) == 1) && (device & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
136 if (!strncmp(device_address, "hdmi_spkr", 9)) {
137 mHdmiAudioDisabled = false;
138 } else {
139 mHdmiAudioEvent = true;
140 }
141 }
142#endif
143 ALOGW("setDeviceConnectionState() device already connected: %x", device);
144 return INVALID_OPERATION;
145 }
146 ALOGV("setDeviceConnectionState() connecting device %x", device);
147
148 // register new device as available
149 index = mAvailableOutputDevices.add(devDesc);
150#ifdef AUDIO_EXTN_HDMI_SPK_ENABLED
151 if ((popcount(device) == 1) && (device & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
152 if (!strncmp(device_address, "hdmi_spkr", 9)) {
153 mHdmiAudioDisabled = false;
154 } else {
155 mHdmiAudioEvent = true;
156 }
157 if (mHdmiAudioDisabled || !mHdmiAudioEvent) {
158 mAvailableOutputDevices.remove(devDesc);
159 ALOGW("HDMI sink not connected, do not route audio to HDMI out");
160 return INVALID_OPERATION;
161 }
162 }
163#endif
164 if (index >= 0) {
165 sp<HwModule> module = mHwModules.getModuleForDevice(device);
166 if (module == 0) {
167 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
168 device);
169 mAvailableOutputDevices.remove(devDesc);
170 return INVALID_OPERATION;
171 }
172 mAvailableOutputDevices[index]->attach(module);
173 } else {
174 return NO_MEMORY;
175 }
176
177 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
178 // parameters on newly connected devices (instead of opening the outputs...)
179 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
180
181 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
182 mAvailableOutputDevices.remove(devDesc);
183
184 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
185 devDesc->mAddress);
186 return INVALID_OPERATION;
187 }
188 // Propagate device availability to Engine
189 mEngine->setDeviceConnectionState(devDesc, state);
190 if (device == AUDIO_DEVICE_OUT_AUX_DIGITAL) {
191 chkDpConnAndAllowedForVoice();
192 }
193
194 // outputs should never be empty here
195 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
196 "checkOutputsForDevice() returned no outputs but status OK");
197 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
198 outputs.size());
199
200 } break;
201 // handle output device disconnection
202 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
203 if (index < 0) {
204#ifdef AUDIO_EXTN_HDMI_SPK_ENABLED
205 if ((popcount(device) == 1) && (device & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
206 if (!strncmp(device_address, "hdmi_spkr", 9)) {
207 mHdmiAudioDisabled = true;
208 } else {
209 mHdmiAudioEvent = false;
210 }
211 }
212#endif
213 ALOGW("setDeviceConnectionState() device not connected: %x", device);
214 return INVALID_OPERATION;
215 }
216
217 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
218
219 // Send Disconnect to HALs
220 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
221
222 // remove device from available output devices
223 mAvailableOutputDevices.remove(devDesc);
224#ifdef AUDIO_EXTN_HDMI_SPK_ENABLED
225 if ((popcount(device) == 1) && (device & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
226 if (!strncmp(device_address, "hdmi_spkr", 9)) {
227 mHdmiAudioDisabled = true;
228 } else {
229 mHdmiAudioEvent = false;
230 }
231 }
232#endif
233 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
234
235 // Propagate device availability to Engine
236 mEngine->setDeviceConnectionState(devDesc, state);
237 if (device == AUDIO_DEVICE_OUT_AUX_DIGITAL) {
238 mEngine->setDpConnAndAllowedForVoice(false);
239 }
240 } break;
241
242 default:
243 ALOGE("setDeviceConnectionState() invalid state: %x", state);
244 return BAD_VALUE;
245 }
246
247 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
248 // output is suspended before any tracks are moved to it
249 checkA2dpSuspend();
250
251 if (!outputs.isEmpty()) {
252 for (size_t i = 0; i < outputs.size(); i++) {
253 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
254 // close voip output before track invalidation to allow creation of
255 // new voip stream from restoreTrack
256 if((desc->mFlags == (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_VOIP_RX)) != 0) {
257 closeOutput(outputs[i]);
258 outputs.remove(outputs[i]);
259 }
260 }
261 }
262
263 checkOutputForAllStrategies();
264 // outputs must be closed after checkOutputForAllStrategies() is executed
265 if (!outputs.isEmpty()) {
266 for (size_t i = 0; i < outputs.size(); i++) {
267 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
268 // close unused outputs after device disconnection or direct outputs that have been
269 // opened by checkOutputsForDevice() to query dynamic parameters
270 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
271 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
272 (desc->mDirectOpenCount == 0))) {
273 closeOutput(outputs[i]);
274 }
275 }
276 // check again after closing A2DP output to reset mA2dpSuspended if needed
277 checkA2dpSuspend();
278 }
279
280#ifdef FM_POWER_OPT
281 // handle FM device connection state to trigger FM AFE loopback
282 if (device == AUDIO_DEVICE_OUT_FM && hasPrimaryOutput()) {
283 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
284 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
285 /*
286 when mPrimaryOutput->start() is called for FM it would check if isActive() is true
287 or not as mRefCount=0 so isActive() would return false and curActiveCount will be
288 1 and then the mRefCount will be increased by 1 for FM case.Updating curActiveCount
289 is important as in case of adding other tracks when FM is still active isActive()
290 will always be true as mRefCount will always be > 0,Hence curActiveCount will never
291 update for them. However ,when fm stops and the track stops too mRefCount will be 0
292 isActive will false,it will check if curActiveCount < 1 as curActiveCount was never
293 updated so LOG_FATAL will cause the AudioServer to die.Hence this start() call will
294 ensure that curActiveCount is updated at least once when FM starts prior to other
295 tracks and on calling of stop() LOG_FATAL is not called.
296 */
297 mPrimaryOutput->start();
298 mPrimaryOutput->changeRefCount(AUDIO_STREAM_MUSIC, 1);
299 newDevice = (audio_devices_t)(getNewOutputDevice(mPrimaryOutput, false)|AUDIO_DEVICE_OUT_FM);
300 mFMIsActive = true;
301 mPrimaryOutput->mDevice = newDevice & ~AUDIO_DEVICE_OUT_FM;
302 } else {
303 newDevice = (audio_devices_t)(getNewOutputDevice(mPrimaryOutput, false));
304 mFMIsActive = false;
305 mPrimaryOutput->changeRefCount(AUDIO_STREAM_MUSIC, -1);
306 /*
307 mPrimaryOutput->stop() is called as because of calling of start()
308 in FM case curActiveCount is getting updated and hence stop() is
309 called so that curActiveCount gets decremented and if any tracks
310 are added after FM stops they may get curActiveCount=0 ,ouptput
311 curActiveCount can be properly updated
312 */
313 mPrimaryOutput->stop();
314 }
315 AudioParameter param = AudioParameter();
316 param.addInt(String8("handle_fm"), (int)newDevice);
317 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, param.toString());
318 }
319#endif /* FM_POWER_OPT end */
320
321 updateDevicesAndOutputs();
322 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
323 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
324 updateCallRouting(newDevice);
325 }
326
327 for (size_t i = 0; i < mOutputs.size(); i++) {
328 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
329 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
330 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
331 // do not force device change on duplicated output because if device is 0, it will
332 // also force a device 0 for the two outputs it is duplicated to which may override
333 // a valid device selection on those outputs.
334 bool force = !desc->isDuplicated()
335 && (!device_distinguishes_on_address(device)
336 // always force when disconnecting (a non-duplicated device)
337 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
338 setOutputDevice(desc, newDevice, force, 0);
339 }
340 }
341
342 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
343 cleanUpForDevice(devDesc);
344 }
345
346 mpClientInterface->onAudioPortListUpdate();
347 return NO_ERROR;
348 } // end if is output device
349
350 // handle input devices
351 if (audio_is_input_device(device)) {
352 SortedVector <audio_io_handle_t> inputs;
353
354 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
355 switch (state)
356 {
357 // handle input device connection
358 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
359 if (index >= 0) {
360 ALOGW("setDeviceConnectionState() device already connected: %d", device);
361 return INVALID_OPERATION;
362 }
363 sp<HwModule> module = mHwModules.getModuleForDevice(device);
364 if (module == NULL) {
365 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
366 device);
367 return INVALID_OPERATION;
368 }
369
370 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
371 // parameters on newly connected devices (instead of opening the inputs...)
372 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
373
374 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
375 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
376 devDesc->mAddress);
377 return INVALID_OPERATION;
378 }
379
380 index = mAvailableInputDevices.add(devDesc);
381 if (index >= 0) {
382 mAvailableInputDevices[index]->attach(module);
383 } else {
384 return NO_MEMORY;
385 }
386
387 // Propagate device availability to Engine
388 mEngine->setDeviceConnectionState(devDesc, state);
389 } break;
390
391 // handle input device disconnection
392 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
393 if (index < 0) {
394 ALOGW("setDeviceConnectionState() device not connected: %d", device);
395 return INVALID_OPERATION;
396 }
397
398 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
399
400 // Set Disconnect to HALs
401 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
402
403 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
404 mAvailableInputDevices.remove(devDesc);
405
406 // Propagate device availability to Engine
407 mEngine->setDeviceConnectionState(devDesc, state);
408 } break;
409
410 default:
411 ALOGE("setDeviceConnectionState() invalid state: %x", state);
412 return BAD_VALUE;
413 }
414
415 closeAllInputs();
416 /*audio policy: fix call volume over USB*/
417 // As the input device list can impact the output device selection, update
418 // getDeviceForStrategy() cache
419 updateDevicesAndOutputs();
420
421 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
422 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
423 updateCallRouting(newDevice);
424 }
425
426 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
427 cleanUpForDevice(devDesc);
428 }
429
430 mpClientInterface->onAudioPortListUpdate();
431 return NO_ERROR;
432 } // end if is input device
433
434 ALOGW("setDeviceConnectionState() invalid device: %x", device);
435 return BAD_VALUE;
436}
437
438void AudioPolicyManagerCustom::chkDpConnAndAllowedForVoice()
439{
440 String8 value;
441 bool connAndAllowed = false;
442 String8 valueStr = mpClientInterface->getParameters((audio_io_handle_t)0,
443 String8("dp_for_voice"));
444
445 AudioParameter result = AudioParameter(valueStr);
446 if (result.get(String8("dp_for_voice"), value) == NO_ERROR) {
447 connAndAllowed = value.contains("true");
448 }
449 mEngine->setDpConnAndAllowedForVoice(connAndAllowed);
450}
451
452bool AudioPolicyManagerCustom::isInvalidationOfMusicStreamNeeded(routing_strategy strategy)
453{
454 if (strategy == STRATEGY_MEDIA) {
455 for (size_t i = 0; i < mOutputs.size(); i++) {
456 sp<SwAudioOutputDescriptor> newOutputDesc = mOutputs.valueAt(i);
457 if (newOutputDesc->mFormat == AUDIO_FORMAT_DSD)
458 return false;
459 }
460 }
461 return true;
462}
463
464void AudioPolicyManagerCustom::checkOutputForStrategy(routing_strategy strategy)
465{
466 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
467 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
468 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mOutputs);
469 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
470
471 // also take into account external policy-related changes: add all outputs which are
472 // associated with policies in the "before" and "after" output vectors
473 ALOGV("checkOutputForStrategy(): policy related outputs");
474 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
475 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
476 if (desc != 0 && desc->mPolicyMix != NULL) {
477 srcOutputs.add(desc->mIoHandle);
478 ALOGV(" previous outputs: adding %d", desc->mIoHandle);
479 }
480 }
481 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
482 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
483 if (desc != 0 && desc->mPolicyMix != NULL) {
484 dstOutputs.add(desc->mIoHandle);
485 ALOGV(" new outputs: adding %d", desc->mIoHandle);
486 }
487 }
488
489 if (!vectorsEqual(srcOutputs,dstOutputs) && isInvalidationOfMusicStreamNeeded(strategy)) {
490 AudioPolicyManager::checkOutputForStrategy(strategy);
491 }
492}
493
494// This function checks for the parameters which can be offloaded.
495// This can be enhanced depending on the capability of the DSP and policy
496// of the system.
497bool AudioPolicyManagerCustom::isOffloadSupported(const audio_offload_info_t& offloadInfo)
498{
499 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
500 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
501 offloadInfo.sample_rate, offloadInfo.channel_mask,
502 offloadInfo.format,
503 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
504 offloadInfo.has_video);
505
506 if (mMasterMono) {
507 return false; // no offloading if mono is set.
508 }
509
510#ifdef VOICE_CONCURRENCY
511 char concpropValue[PROPERTY_VALUE_MAX];
512 if (property_get("vendor.voice.playback.conc.disabled", concpropValue, NULL)) {
513 bool propenabled = atoi(concpropValue) || !strncmp("true", concpropValue, 4);
514 if (propenabled) {
515 if (isInCall())
516 {
517 ALOGD("\n copl: blocking compress offload on call mode\n");
518 return false;
519 }
520 }
521 }
522#endif
523 if (property_get_bool("vendor.voice.dsd.playback.conc.disabled", true) &&
524 isInCall() && (offloadInfo.format == AUDIO_FORMAT_DSD)) {
525 ALOGD("blocking DSD compress offload on call mode");
526 return false;
527 }
528#ifdef RECORD_PLAY_CONCURRENCY
529 char recConcPropValue[PROPERTY_VALUE_MAX];
530 bool prop_rec_play_enabled = false;
531
532 if (property_get("vendor.audio.rec.playback.conc.disabled", recConcPropValue, NULL)) {
533 prop_rec_play_enabled = atoi(recConcPropValue) || !strncmp("true", recConcPropValue, 4);
534 }
535
536 if ((prop_rec_play_enabled) &&
537 ((true == mIsInputRequestOnProgress) || (mInputs.activeInputsCountOnDevices() > 0))) {
538 ALOGD("copl: blocking compress offload for record concurrency");
539 return false;
540 }
541#endif
542 // Check if stream type is music, then only allow offload as of now.
543 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
544 {
545 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
546 return false;
547 }
548
549 // Check if offload has been disabled
550 bool offloadDisabled = property_get_bool("audio.offload.disable", false);
551 if (offloadDisabled) {
552 ALOGI("offload disabled by audio.offload.disable=%d", offloadDisabled);
553 return false;
554 }
555
556 //check if it's multi-channel AAC (includes sub formats) and FLAC format
557 if ((popcount(offloadInfo.channel_mask) > 2) &&
558 (((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC) ||
559 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_VORBIS))) {
560 ALOGD("offload disabled for multi-channel AAC,FLAC and VORBIS format");
561 return false;
562 }
563
564#ifdef AUDIO_EXTN_FORMATS_ENABLED
565 //check if it's multi-channel FLAC/ALAC/WMA format with sample rate > 48k
566 if ((popcount(offloadInfo.channel_mask) > 2) &&
567 (((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_FLAC) ||
568 (((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_ALAC) && (offloadInfo.sample_rate > 48000)) ||
569 (((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA) && (offloadInfo.sample_rate > 48000)) ||
570 (((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA_PRO) && (offloadInfo.sample_rate > 48000)) ||
571 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC_ADTS))) {
572 ALOGD("offload disabled for multi-channel FLAC/ALAC/WMA/AAC_ADTS clips with sample rate > 48kHz");
573 return false;
574 }
575
576 // check against wma std bit rate restriction
577 if ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA) {
578 int32_t sr_id = -1;
579 uint32_t min_bitrate, max_bitrate;
580 for (int i = 0; i < WMA_STD_NUM_FREQ; i++) {
581 if (offloadInfo.sample_rate == wmaStdSampleRateTbl[i]) {
582 sr_id = i;
583 break;
584 }
585 }
586 if ((sr_id < 0) || (popcount(offloadInfo.channel_mask) > 2)
587 || (popcount(offloadInfo.channel_mask) <= 0)) {
588 ALOGE("invalid sample rate or channel count");
589 return false;
590 }
591
592 min_bitrate = wmaStdMinAvgByteRateTbl[sr_id][popcount(offloadInfo.channel_mask) - 1];
593 max_bitrate = wmaStdMaxAvgByteRateTbl[sr_id][popcount(offloadInfo.channel_mask) - 1];
594 if ((offloadInfo.bit_rate > max_bitrate) || (offloadInfo.bit_rate < min_bitrate)) {
595 ALOGD("offload disabled for WMA clips with unsupported bit rate");
596 ALOGD("bit_rate %d, max_bitrate %d, min_bitrate %d", offloadInfo.bit_rate, max_bitrate, min_bitrate);
597 return false;
598 }
599 }
600
601 // Safely choose the min bitrate as threshold and leave the restriction to NT decoder as we can't distinguish wma pro and wma lossless here.
602 if ((((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA_PRO) && (offloadInfo.bit_rate > MAX_BITRATE_WMA_PRO)) ||
603 (((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA_PRO) && (offloadInfo.bit_rate > MAX_BITRATE_WMA_LOSSLESS))) {
604 ALOGD("offload disabled for WMA_PRO/WMA_LOSSLESS clips with bit rate over maximum supported value");
605 return false;
606 }
607#endif
608 //TODO: enable audio offloading with video when ready
609 const bool allowOffloadWithVideo =
610 property_get_bool("audio.offload.video", false /* default_value */);
611 if (offloadInfo.has_video && !allowOffloadWithVideo) {
612 ALOGV("isOffloadSupported: has_video == true, returning false");
613 return false;
614 }
615
616 const bool allowOffloadStreamingWithVideo =
617 property_get_bool("vendor.audio.av.streaming.offload.enable", false /*default value*/);
618 if (offloadInfo.has_video && offloadInfo.is_streaming && !allowOffloadStreamingWithVideo) {
619 ALOGW("offload disabled by vendor.audio.av.streaming.offload.enable %d",
620 allowOffloadStreamingWithVideo);
621 return false;
622 }
623
624 //If duration is less than minimum value defined in property, return false
625 char propValue[PROPERTY_VALUE_MAX];
626 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
627 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
628 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
629 return false;
630 }
631 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
632 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
633 //duration checks only valid for MP3/AAC/ formats,
634 //do not check duration for other audio formats, e.g. AAC/AC3 and amrwb+ formats
635 if ((offloadInfo.format == AUDIO_FORMAT_MP3) ||
636 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC) ||
637 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_FLAC) ||
638 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_VORBIS))
639 return false;
640
641#ifdef AUDIO_EXTN_FORMATS_ENABLED
642 if (((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA) ||
643 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA_PRO) ||
644 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_ALAC) ||
645 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_APE) ||
646 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_DSD) ||
647 ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC_ADTS))
648 return false;
649#endif
650 }
651
652 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
653 // creating an offloaded track and tearing it down immediately after start when audioflinger
654 // detects there is an active non offloadable effect.
655 // FIXME: We should check the audio session here but we do not have it in this context.
656 // This may prevent offloading in rare situations where effects are left active by apps
657 // in the background.
658 if (mEffects.isNonOffloadableEffectEnabled()) {
659 return false;
660 }
661
662 // See if there is a profile to support this.
663 // AUDIO_DEVICE_NONE
664 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
665 offloadInfo.sample_rate,
666 offloadInfo.format,
667 offloadInfo.channel_mask,
668 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
669 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
670 return (profile != 0);
671}
672
673void AudioPolicyManagerCustom::setPhoneState(audio_mode_t state)
674{
675 ALOGD("setPhoneState() state %d", state);
676 // store previous phone state for management of sonification strategy below
677 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
678 int oldState = mEngine->getPhoneState();
679
680 if (mEngine->setPhoneState(state) != NO_ERROR) {
681 ALOGW("setPhoneState() invalid or same state %d", state);
682 return;
683 }
684 /// Opens: can these line be executed after the switch of volume curves???
685 // if leaving call state, handle special case of active streams
686 // pertaining to sonification strategy see handleIncallSonification()
687 if (isStateInCall(oldState)) {
688 ALOGV("setPhoneState() in call state management: new state is %d", state);
689 for (size_t j = 0; j < mOutputs.size(); j++) {
690 audio_io_handle_t curOutput = mOutputs.keyAt(j);
691 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
692 handleIncallSonification((audio_stream_type_t)stream, false, true, curOutput);
693 }
694 }
695
696 // force reevaluating accessibility routing when call stops
697 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
698 }
699
700 /**
701 * Switching to or from incall state or switching between telephony and VoIP lead to force
702 * routing command.
703 */
704 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
705 || (is_state_in_call(state) && (state != oldState)));
706
707 // check for device and output changes triggered by new phone state
708 checkA2dpSuspend();
709 checkOutputForAllStrategies();
710 updateDevicesAndOutputs();
711
712 sp<SwAudioOutputDescriptor> hwOutputDesc = mPrimaryOutput;
713#ifdef VOICE_CONCURRENCY
714 char propValue[PROPERTY_VALUE_MAX];
715 bool prop_playback_enabled = false, prop_rec_enabled=false, prop_voip_enabled = false;
716
717 if(property_get("vendor.voice.playback.conc.disabled", propValue, NULL)) {
718 prop_playback_enabled = atoi(propValue) || !strncmp("true", propValue, 4);
719 }
720
721 if(property_get("vendor.voice.record.conc.disabled", propValue, NULL)) {
722 prop_rec_enabled = atoi(propValue) || !strncmp("true", propValue, 4);
723 }
724
725 if(property_get("vendor.voice.voip.conc.disabled", propValue, NULL)) {
726 prop_voip_enabled = atoi(propValue) || !strncmp("true", propValue, 4);
727 }
728
729 if ((AUDIO_MODE_IN_CALL != oldState) && (AUDIO_MODE_IN_CALL == state)) {
730 ALOGD("voice_conc:Entering to call mode oldState :: %d state::%d ",
731 oldState, state);
732 mvoice_call_state = state;
733 if (prop_rec_enabled) {
734 //Close all active inputs
735 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
736 if (activeInputs.size() != 0) {
737 for (size_t i = 0; i < activeInputs.size(); i++) {
738 sp<AudioInputDescriptor> activeInput = activeInputs[i];
739 switch(activeInput->inputSource()) {
740 case AUDIO_SOURCE_VOICE_UPLINK:
741 case AUDIO_SOURCE_VOICE_DOWNLINK:
742 case AUDIO_SOURCE_VOICE_CALL:
743 ALOGD("voice_conc:FOUND active input during call active: %d",activeInput->inputSource());
744 break;
745
746 case AUDIO_SOURCE_VOICE_COMMUNICATION:
747 if(prop_voip_enabled) {
748 ALOGD("voice_conc:CLOSING VoIP input source on call setup :%d ",activeInput->inputSource());
749 AudioSessionCollection activeSessions = activeInput->getAudioSessions(true);
750 audio_session_t activeSession = activeSessions.keyAt(0);
751 stopInput(activeInput->mIoHandle, activeSession);
752 releaseInput(activeInput->mIoHandle, activeSession);
753 }
754 break;
755
756 default:
757 ALOGD("voice_conc:CLOSING input on call setup for inputSource: %d",activeInput->inputSource());
758 AudioSessionCollection activeSessions = activeInput->getAudioSessions(true);
759 audio_session_t activeSession = activeSessions.keyAt(0);
760 stopInput(activeInput->mIoHandle, activeSession);
761 releaseInput(activeInput->mIoHandle, activeSession);
762 break;
763 }
764 }
765 }
766 } else if (prop_voip_enabled) {
767 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
768 if (activeInputs.size() != 0) {
769 for (size_t i = 0; i < activeInputs.size(); i++) {
770 sp<AudioInputDescriptor> activeInput = activeInputs[i];
771 if (AUDIO_SOURCE_VOICE_COMMUNICATION == activeInput->inputSource()) {
772 ALOGD("voice_conc:CLOSING VoIP on call setup : %d",activeInput->inputSource());
773 AudioSessionCollection activeSessions = activeInput->getAudioSessions(true);
774 audio_session_t activeSession = activeSessions.keyAt(0);
775 stopInput(activeInput->mIoHandle, activeSession);
776 releaseInput(activeInput->mIoHandle, activeSession);
777 }
778 }
779 }
780 }
781 if (prop_playback_enabled) {
782 // Move tracks associated to this strategy from previous output to new output
783 for (int i = AUDIO_STREAM_SYSTEM; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
784 ALOGV("voice_conc:Invalidate on call mode for stream :: %d ", i);
785 if (AUDIO_OUTPUT_FLAG_DEEP_BUFFER == mFallBackflag) {
786 if ((AUDIO_STREAM_MUSIC == i) ||
787 (AUDIO_STREAM_VOICE_CALL == i) ) {
788 ALOGD("voice_conc:Invalidate stream type %d", i);
789 mpClientInterface->invalidateStream((audio_stream_type_t)i);
790 }
791 } else if (AUDIO_OUTPUT_FLAG_FAST == mFallBackflag) {
792 ALOGD("voice_conc:Invalidate stream type %d", i);
793 mpClientInterface->invalidateStream((audio_stream_type_t)i);
794 }
795 }
796 }
797
798 for (size_t i = 0; i < mOutputs.size(); i++) {
799 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
800 if ( (outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
801 ALOGD("voice_conc:ouput desc / profile is NULL");
802 continue;
803 }
804
805 bool isFastFallBackNeeded =
806 ((AUDIO_OUTPUT_FLAG_DEEP_BUFFER | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT_PCM) & outputDesc->mProfile->getFlags());
807
808 if ((AUDIO_OUTPUT_FLAG_FAST == mFallBackflag) && isFastFallBackNeeded) {
809 if (((!outputDesc->isDuplicated() && outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY))
810 && prop_playback_enabled) {
811 ALOGD("voice_conc:calling suspendOutput on call mode for primary output");
812 mpClientInterface->suspendOutput(mOutputs.keyAt(i));
813 } //Close compress all sessions
814 else if ((outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
815 && prop_playback_enabled) {
816 ALOGD("voice_conc:calling closeOutput on call mode for COMPRESS output");
817 closeOutput(mOutputs.keyAt(i));
818 }
819 else if ((outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_VOIP_RX)
820 && prop_voip_enabled) {
821 ALOGD("voice_conc:calling closeOutput on call mode for DIRECT output");
822 closeOutput(mOutputs.keyAt(i));
823 }
824 } else if (AUDIO_OUTPUT_FLAG_DEEP_BUFFER == mFallBackflag) {
825 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_VOIP_RX) {
826 if (prop_voip_enabled) {
827 ALOGD("voice_conc:calling closeOutput on call mode for DIRECT output");
828 closeOutput(mOutputs.keyAt(i));
829 }
830 }
831 else if (prop_playback_enabled
832 && (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT)) {
833 ALOGD("voice_conc:calling closeOutput on call mode for COMPRESS output");
834 closeOutput(mOutputs.keyAt(i));
835 }
836 }
837 }
838 }
839
840 if ((AUDIO_MODE_IN_CALL == oldState || AUDIO_MODE_IN_COMMUNICATION == oldState) &&
841 (AUDIO_MODE_NORMAL == state) && prop_playback_enabled && mvoice_call_state) {
842 ALOGD("voice_conc:EXITING from call mode oldState :: %d state::%d \n",oldState, state);
843 mvoice_call_state = 0;
844 if (AUDIO_OUTPUT_FLAG_FAST == mFallBackflag) {
845 //restore PCM (deep-buffer) output after call termination
846 for (size_t i = 0; i < mOutputs.size(); i++) {
847 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
848 if ( (outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
849 ALOGD("voice_conc:ouput desc / profile is NULL");
850 continue;
851 }
852 if (!outputDesc->isDuplicated() && outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
853 ALOGD("voice_conc:calling restoreOutput after call mode for primary output");
854 mpClientInterface->restoreOutput(mOutputs.keyAt(i));
855 }
856 }
857 }
858 //call invalidate tracks so that any open streams can fall back to deep buffer/compress path from ULL
859 for (int i = AUDIO_STREAM_SYSTEM; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
860 ALOGV("voice_conc:Invalidate on call mode for stream :: %d ", i);
861 if (AUDIO_OUTPUT_FLAG_DEEP_BUFFER == mFallBackflag) {
862 if ((AUDIO_STREAM_MUSIC == i) ||
863 (AUDIO_STREAM_VOICE_CALL == i) ) {
864 mpClientInterface->invalidateStream((audio_stream_type_t)i);
865 }
866 } else if (AUDIO_OUTPUT_FLAG_FAST == mFallBackflag) {
867 mpClientInterface->invalidateStream((audio_stream_type_t)i);
868 }
869 }
870 }
871
872#endif
873
874 sp<SwAudioOutputDescriptor> outputDesc = NULL;
875 for (size_t i = 0; i < mOutputs.size(); i++) {
876 outputDesc = mOutputs.valueAt(i);
877 if ((outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
878 ALOGD("voice_conc:ouput desc / profile is NULL");
879 continue;
880 }
881
882 if (property_get_bool("vendor.voice.dsd.playback.conc.disabled", true) &&
883 (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
884 (outputDesc->mFormat == AUDIO_FORMAT_DSD)) {
885 ALOGD("voice_conc:calling closeOutput on call mode for DSD COMPRESS output");
886 closeOutput(mOutputs.keyAt(i));
887 // call invalidate for music, so that DSD compress will fallback to deep-buffer.
888 mpClientInterface->invalidateStream(AUDIO_STREAM_MUSIC);
889 }
890
891 }
892
893#ifdef RECORD_PLAY_CONCURRENCY
894 char recConcPropValue[PROPERTY_VALUE_MAX];
895 bool prop_rec_play_enabled = false;
896
897 if (property_get("vendor.audio.rec.playback.conc.disabled", recConcPropValue, NULL)) {
898 prop_rec_play_enabled = atoi(recConcPropValue) || !strncmp("true", recConcPropValue, 4);
899 }
900 if (prop_rec_play_enabled) {
901 if (AUDIO_MODE_IN_COMMUNICATION == mEngine->getPhoneState()) {
902 ALOGD("phone state changed to MODE_IN_COMM invlaidating music and voice streams");
903 // call invalidate for voice streams, so that it can use deepbuffer with VoIP out device from HAL
904 mpClientInterface->invalidateStream(AUDIO_STREAM_VOICE_CALL);
905 // call invalidate for music, so that compress will fallback to deep-buffer with VoIP out device
906 mpClientInterface->invalidateStream(AUDIO_STREAM_MUSIC);
907
908 // close compress output to make sure session will be closed before timeout(60sec)
909 for (size_t i = 0; i < mOutputs.size(); i++) {
910
911 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
912 if ((outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
913 ALOGD("ouput desc / profile is NULL");
914 continue;
915 }
916
917 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
918 ALOGD("calling closeOutput on call mode for COMPRESS output");
919 closeOutput(mOutputs.keyAt(i));
920 }
921 }
922 } else if ((oldState == AUDIO_MODE_IN_COMMUNICATION) &&
923 (mEngine->getPhoneState() == AUDIO_MODE_NORMAL)) {
924 // call invalidate for music so that music can fallback to compress
925 mpClientInterface->invalidateStream(AUDIO_STREAM_MUSIC);
926 }
927 }
928#endif
929 mPrevPhoneState = oldState;
930 int delayMs = 0;
931 if (isStateInCall(state)) {
932 nsecs_t sysTime = systemTime();
933 for (size_t i = 0; i < mOutputs.size(); i++) {
934 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
935 // mute media and sonification strategies and delay device switch by the largest
936 // latency of any output where either strategy is active.
937 // This avoid sending the ring tone or music tail into the earpiece or headset.
938 if ((isStrategyActive(desc, STRATEGY_MEDIA,
939 SONIFICATION_HEADSET_MUSIC_DELAY,
940 sysTime) ||
941 isStrategyActive(desc, STRATEGY_SONIFICATION,
942 SONIFICATION_HEADSET_MUSIC_DELAY,
943 sysTime)) &&
944 (delayMs < (int)desc->latency()*2)) {
945 delayMs = desc->latency()*2;
946 }
947 setStrategyMute(STRATEGY_MEDIA, true, desc);
948 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
949 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
950 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
951 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
952 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
953 }
954 }
955
956 if (hasPrimaryOutput()) {
957 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
958 // the device returned is not necessarily reachable via this output
959 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
960 // force routing command to audio hardware when ending call
961 // even if no device change is needed
962 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
963 rxDevice = mPrimaryOutput->device();
964 }
965
966 if (state == AUDIO_MODE_IN_CALL) {
967 updateCallRouting(rxDevice, delayMs);
968 } else if (oldState == AUDIO_MODE_IN_CALL) {
969 if (mCallRxPatch != 0) {
970 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
971 mCallRxPatch.clear();
972 }
973 if (mCallTxPatch != 0) {
974 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
975 mCallTxPatch.clear();
976 }
977 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
978 } else {
979 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
980 }
981 }
982 //update device for all non-primary outputs
983 for (size_t i = 0; i < mOutputs.size(); i++) {
984 audio_io_handle_t output = mOutputs.keyAt(i);
985 if (output != mPrimaryOutput->mIoHandle) {
986 newDevice = getNewOutputDevice(mOutputs.valueFor(output), false /*fromCache*/);
987 setOutputDevice(mOutputs.valueFor(output), newDevice, (newDevice != AUDIO_DEVICE_NONE));
988 }
989 }
990 // if entering in call state, handle special case of active streams
991 // pertaining to sonification strategy see handleIncallSonification()
992 if (isStateInCall(state)) {
993 ALOGV("setPhoneState() in call state management: new state is %d", state);
994 for (size_t j = 0; j < mOutputs.size(); j++) {
995 audio_io_handle_t curOutput = mOutputs.keyAt(j);
996 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
997 handleIncallSonification((audio_stream_type_t)stream, true, true, curOutput);
998 }
999 }
1000
1001 // force reevaluating accessibility routing when call starts
1002 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1003 }
1004
1005 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
1006 if (state == AUDIO_MODE_RINGTONE &&
1007 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
1008 mLimitRingtoneVolume = true;
1009 } else {
1010 mLimitRingtoneVolume = false;
1011 }
1012}
1013
1014void AudioPolicyManagerCustom::setForceUse(audio_policy_force_use_t usage,
1015 audio_policy_forced_cfg_t config)
1016{
1017 ALOGD("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
1018 if (config == mEngine->getForceUse(usage)) {
1019 return;
1020 }
1021
1022 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1023 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1024 return;
1025 }
1026 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1027 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1028 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
1029
1030 // check for device and output changes triggered by new force usage
1031 checkA2dpSuspend();
1032 checkOutputForAllStrategies();
1033 updateDevicesAndOutputs();
1034
1035 /*audio policy: workaround for truncated touch sounds*/
1036 //FIXME: workaround for truncated touch sounds
1037 // to be removed when the problem is handled by system UI
1038 uint32_t delayMs = 0;
1039 uint32_t waitMs = 0;
1040 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1041 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1042 }
1043 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
1044 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
1045 waitMs = updateCallRouting(newDevice, delayMs);
1046 }
1047 // Use reverse loop to make sure any low latency usecases (generally tones)
1048 // are not routed before non LL usecases (generally music).
1049 // We can safely assume that LL output would always have lower index,
1050 // and use this work-around to avoid routing of output with music stream
1051 // from the context of short lived LL output.
1052 // Note: in case output's share backend(HAL sharing is implicit) all outputs
1053 // gets routing update while processing first output itself.
1054 for (size_t i = mOutputs.size(); i > 0; i--) {
1055 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i-1);
1056 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
1057 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
1058 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
1059 delayMs);
1060 }
1061 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
1062 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
1063 }
1064 }
1065
1066 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1067 for (size_t i = 0; i < activeInputs.size(); i++) {
1068 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1069 audio_devices_t newDevice = getNewInputDevice(activeDesc);
1070 // Force new input selection if the new device can not be reached via current input
1071 if (activeDesc->mProfile->getSupportedDevices().types() &
1072 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
1073 setInputDevice(activeDesc->mIoHandle, newDevice);
1074 } else {
1075 closeInput(activeDesc->mIoHandle);
1076 }
1077 }
1078}
1079
1080status_t AudioPolicyManagerCustom::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
1081 audio_stream_type_t stream,
1082 bool forceDeviceUpdate)
1083{
1084 if (stream < 0 || stream >= AUDIO_STREAM_CNT) {
1085 ALOGW("stopSource() invalid stream %d", stream);
1086 return INVALID_OPERATION;
1087 }
1088 // always handle stream stop, check which stream type is stopping
1089 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1090
1091 // handle special case for sonification while in call
1092 if (isInCall()) {
1093 if (outputDesc->isDuplicated()) {
1094 handleIncallSonification(stream, false, false, outputDesc->subOutput1()->mIoHandle);
1095 handleIncallSonification(stream, false, false, outputDesc->subOutput2()->mIoHandle);
1096 }
1097 handleIncallSonification(stream, false, false, outputDesc->mIoHandle);
1098 }
1099
1100 if (outputDesc->mRefCount[stream] > 0) {
1101 // decrement usage count of this stream on the output
1102 outputDesc->changeRefCount(stream, -1);
1103
1104 // store time at which the stream was stopped - see isStreamActive()
1105 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
1106 outputDesc->mStopTime[stream] = systemTime();
1107 audio_devices_t prevDevice = outputDesc->device();
1108 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
1109 // delay the device switch by twice the latency because stopOutput() is executed when
1110 // the track stop() command is received and at that time the audio track buffer can
1111 // still contain data that needs to be drained. The latency only covers the audio HAL
1112 // and kernel buffers. Also the latency does not always include additional delay in the
1113 // audio path (audio DSP, CODEC ...)
1114 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
1115
1116 // force restoring the device selection on other active outputs if it differs from the
1117 // one being selected for this output
1118 for (size_t i = 0; i < mOutputs.size(); i++) {
1119 audio_io_handle_t curOutput = mOutputs.keyAt(i);
1120 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1121 if (desc != outputDesc &&
1122 desc->isActive() &&
1123 outputDesc->sharesHwModuleWith(desc) &&
1124 (newDevice != desc->device())) {
1125 audio_devices_t dev = getNewOutputDevice(mOutputs.valueFor(curOutput), false /*fromCache*/);
1126 bool force = prevDevice != dev;
1127 uint32_t delayMs;
1128 if (dev == prevDevice) {
1129 delayMs = 0;
1130 } else {
1131 delayMs = outputDesc->latency()*2;
1132 }
1133 setOutputDevice(desc,
1134 dev,
1135 force,
1136 delayMs);
1137 /*audio policy: fix media volume after ringtone*/
1138 // re-apply device specific volume if not done by setOutputDevice()
1139 if (!force) {
1140 applyStreamVolumes(desc, dev, delayMs);
1141 }
1142 }
1143 }
1144 // update the outputs if stopping one with a stream that can affect notification routing
1145 handleNotificationRoutingForStream(stream);
1146 }
1147 if (stream == AUDIO_STREAM_MUSIC) {
1148 selectOutputForMusicEffects();
1149 }
1150 return NO_ERROR;
1151 } else {
1152 ALOGW("stopOutput() refcount is already 0");
1153 return INVALID_OPERATION;
1154 }
1155}
1156
1157status_t AudioPolicyManagerCustom::startSource(const sp<AudioOutputDescriptor>& outputDesc,
1158 audio_stream_type_t stream,
1159 audio_devices_t device,
1160 const char *address,
1161 uint32_t *delayMs)
1162{
1163 // cannot start playback of STREAM_TTS if any other output is being used
1164 uint32_t beaconMuteLatency = 0;
1165
1166 if (stream < 0 || stream >= AUDIO_STREAM_CNT) {
1167 ALOGW("startSource() invalid stream %d", stream);
1168 return INVALID_OPERATION;
1169 }
1170
1171 *delayMs = 0;
1172 if (stream == AUDIO_STREAM_TTS) {
1173 ALOGV("\t found BEACON stream");
1174 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1175 return INVALID_OPERATION;
1176 } else {
1177 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1178 }
1179 } else {
1180 // some playback other than beacon starts
1181 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1182 }
1183
1184 // force device change if the output is inactive and no audio patch is already present.
1185 // check active before incrementing usage count
1186 bool force = !outputDesc->isActive() &&
1187 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
1188
1189 // increment usage count for this stream on the requested output:
1190 // NOTE that the usage count is the same for duplicated output and hardware output which is
1191 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1192 outputDesc->changeRefCount(stream, 1);
1193
1194 if (stream == AUDIO_STREAM_MUSIC) {
1195 selectOutputForMusicEffects();
1196 }
1197
1198 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
1199 // starting an output being rerouted?
1200 if (device == AUDIO_DEVICE_NONE) {
1201 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1202 }
1203 routing_strategy strategy = getStrategy(stream);
1204 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1205 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1206 (beaconMuteLatency > 0);
1207 uint32_t waitMs = beaconMuteLatency;
1208 for (size_t i = 0; i < mOutputs.size(); i++) {
1209 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1210 if (desc != outputDesc) {
1211 // force a device change if any other output is:
1212 // - managed by the same hw module
1213 // - has a current device selection that differs from selected device.
1214 // - supports currently selected device
1215 // - has an active audio patch
1216 // In this case, the audio HAL must receive the new device selection so that it can
1217 // change the device currently selected by the other active output.
1218 if (outputDesc->sharesHwModuleWith(desc) &&
1219 desc->device() != device &&
1220 desc->supportedDevices() & device &&
1221 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
1222 force = true;
1223 }
1224 // wait for audio on other active outputs to be presented when starting
1225 // a notification so that audio focus effect can propagate, or that a mute/unmute
1226 // event occurred for beacon
1227 uint32_t latency = desc->latency();
1228 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1229 waitMs = latency;
1230 }
1231 }
1232 }
1233 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
1234
1235 // handle special case for sonification while in call
1236 if (isInCall()) {
1237 handleIncallSonification(stream, true, false, outputDesc->mIoHandle);
1238 }
1239
1240 // apply volume rules for current stream and device if necessary
1241 checkAndSetVolume(stream,
1242 mVolumeCurves->getVolumeIndex(stream, device),
1243 outputDesc,
1244 device);
1245
1246 // update the outputs if starting an output with a stream that can affect notification
1247 // routing
1248 handleNotificationRoutingForStream(stream);
1249
1250 // force reevaluating accessibility routing when ringtone or alarm starts
1251 if (strategy == STRATEGY_SONIFICATION) {
1252 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1253 }
1254 if (waitMs > muteWaitMs) {
1255 *delayMs = waitMs - muteWaitMs;
1256 }
1257
1258 } else {
1259 // handle special case for sonification while in call
1260 if (isInCall()) {
1261 handleIncallSonification(stream, true, false, outputDesc->mIoHandle);
1262 }
1263 }
1264 return NO_ERROR;
1265}
1266
1267void AudioPolicyManagerCustom::handleIncallSonification(audio_stream_type_t stream,
1268 bool starting, bool stateChange,
1269 audio_io_handle_t output)
1270{
1271 if(!hasPrimaryOutput()) {
1272 return;
1273 }
1274 // no action needed for AUDIO_STREAM_PATCH stream type, it's for internal flinger tracks
1275 if (stream == AUDIO_STREAM_PATCH) {
1276 return;
1277 }
1278 // if the stream pertains to sonification strategy and we are in call we must
1279 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
1280 // in the device used for phone strategy and play the tone if the selected device does not
1281 // interfere with the device used for phone strategy
1282 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
1283 // many times as there are active tracks on the output
1284 const routing_strategy stream_strategy = getStrategy(stream);
1285 if ((stream_strategy == STRATEGY_SONIFICATION) ||
1286 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
1287 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
1288 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
1289 stream, starting, outputDesc->mDevice, stateChange);
1290 if (outputDesc->mRefCount[stream]) {
1291 int muteCount = 1;
1292 if (stateChange) {
1293 muteCount = outputDesc->mRefCount[stream];
1294 }
1295 if (audio_is_low_visibility(stream)) {
1296 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
1297 for (int i = 0; i < muteCount; i++) {
1298 setStreamMute(stream, starting, outputDesc);
1299 }
1300 } else {
1301 ALOGV("handleIncallSonification() high visibility");
1302 if (outputDesc->device() &
1303 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
1304 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
1305 for (int i = 0; i < muteCount; i++) {
1306 setStreamMute(stream, starting, outputDesc);
1307 }
1308 }
1309 if (starting) {
1310 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
1311 AUDIO_STREAM_VOICE_CALL);
1312 } else {
1313 mpClientInterface->stopTone();
1314 }
1315 }
1316 }
1317 }
1318}
1319
1320void AudioPolicyManagerCustom::handleNotificationRoutingForStream(audio_stream_type_t stream) {
1321 switch(stream) {
1322 case AUDIO_STREAM_MUSIC:
1323 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1324 updateDevicesAndOutputs();
1325 break;
1326 default:
1327 break;
1328 }
1329}
1330
1331status_t AudioPolicyManagerCustom::checkAndSetVolume(audio_stream_type_t stream,
1332 int index,
1333 const sp<AudioOutputDescriptor>& outputDesc,
1334 audio_devices_t device,
1335 int delayMs,
1336 bool force)
1337{
1338 if (stream < 0 || stream >= AUDIO_STREAM_CNT) {
1339 ALOGW("checkAndSetVolume() invalid stream %d", stream);
1340 return INVALID_OPERATION;
1341 }
1342 // do not change actual stream volume if the stream is muted
1343 if (outputDesc->mMuteCount[stream] != 0) {
1344 ALOGVV("checkAndSetVolume() stream %d muted count %d",
1345 stream, outputDesc->mMuteCount[stream]);
1346 return NO_ERROR;
1347 }
1348 audio_policy_forced_cfg_t forceUseForComm =
1349 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
1350 // do not change in call volume if bluetooth is connected and vice versa
1351 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
1352 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
1353 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1354 stream, forceUseForComm);
1355 return INVALID_OPERATION;
1356 }
1357
1358 if (device == AUDIO_DEVICE_NONE) {
1359 device = outputDesc->device();
1360 }
1361
1362 float volumeDb = computeVolume(stream, index, device);
1363 if (outputDesc->isFixedVolume(device)) {
1364 volumeDb = 0.0f;
1365 }
1366
1367 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
1368
1369 if (stream == AUDIO_STREAM_VOICE_CALL ||
1370 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
1371 float voiceVolume;
1372 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
1373 if (stream == AUDIO_STREAM_VOICE_CALL) {
1374 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
1375 } else {
1376 voiceVolume = 1.0;
1377 }
1378
1379 if (voiceVolume != mLastVoiceVolume) {
1380 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
1381 mLastVoiceVolume = voiceVolume;
1382 }
1383#ifdef FM_POWER_OPT
1384 } else if (stream == AUDIO_STREAM_MUSIC && hasPrimaryOutput() &&
1385 outputDesc == mPrimaryOutput && mFMIsActive) {
1386 /* Avoid unnecessary set_parameter calls as it puts the primary
1387 outputs FastMixer in HOT_IDLE leading to breaks in audio */
1388 if (volumeDb != mPrevFMVolumeDb) {
1389 mPrevFMVolumeDb = volumeDb;
1390 AudioParameter param = AudioParameter();
1391 param.addFloat(String8("fm_volume"), Volume::DbToAmpl(volumeDb));
1392 //Double delayMs to avoid sound burst while device switch.
1393 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, param.toString(), delayMs*2);
1394 }
1395#endif /* FM_POWER_OPT end */
1396 }
1397
1398 return NO_ERROR;
1399}
1400
1401bool AudioPolicyManagerCustom::isDirectOutput(audio_io_handle_t output) {
1402 for (size_t i = 0; i < mOutputs.size(); i++) {
1403 audio_io_handle_t curOutput = mOutputs.keyAt(i);
1404 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1405 if ((curOutput == output) && (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1406 return true;
1407 }
1408 }
1409 return false;
1410}
1411
1412bool static tryForDirectPCM(audio_output_flags_t flags)
1413{
1414 bool trackDirectPCM = false; // Output request for track created by other apps
1415
1416 if (flags == AUDIO_OUTPUT_FLAG_NONE) {
1417 trackDirectPCM = property_get_bool("vendor.audio.offload.track.enable", true);
1418 }
1419 return trackDirectPCM;
1420}
1421
1422status_t AudioPolicyManagerCustom::getOutputForAttr(const audio_attributes_t *attr,
1423 audio_io_handle_t *output,
1424 audio_session_t session,
1425 audio_stream_type_t *stream,
1426 uid_t uid,
1427 const audio_config_t *config,
1428 audio_output_flags_t *flags,
1429 audio_port_handle_t *selectedDeviceId,
1430 audio_port_handle_t *portId)
1431{
1432 audio_offload_info_t tOffloadInfo = AUDIO_INFO_INITIALIZER;
1433 audio_config_t tConfig;
1434
1435 uint32_t bitWidth = (audio_bytes_per_sample(config->format) * 8);
1436
1437 memcpy(&tConfig, config, sizeof(audio_config_t));
1438 if ((*flags == AUDIO_OUTPUT_FLAG_DIRECT || tryForDirectPCM(*flags)) &&
1439 (!memcmp(&config->offload_info, &tOffloadInfo, sizeof(audio_offload_info_t)))) {
1440 tConfig.offload_info.sample_rate = config->sample_rate;
1441 tConfig.offload_info.channel_mask = config->channel_mask;
1442 tConfig.offload_info.format = config->format;
1443 tConfig.offload_info.stream_type = *stream;
1444 tConfig.offload_info.bit_width = bitWidth;
1445 if (attr != NULL) {
1446 ALOGV("found attribute .. setting usage %d ", attr->usage);
1447 tConfig.offload_info.usage = attr->usage;
1448 } else {
1449 ALOGI("%s:: attribute is NULL .. no usage set", __func__);
1450 }
1451 }
1452
1453 return AudioPolicyManager::getOutputForAttr(attr, output, session, stream,
1454 (uid_t)uid, &tConfig,
1455 flags,
1456 (audio_port_handle_t*)selectedDeviceId,
1457 portId);
1458}
1459
1460audio_io_handle_t AudioPolicyManagerCustom::getOutputForDevice(
1461 audio_devices_t device,
1462 audio_session_t session,
1463 audio_stream_type_t stream,
1464 const audio_config_t *config,
1465 audio_output_flags_t *flags)
1466{
1467 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
1468 status_t status;
1469
1470 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_CNT) {
1471 ALOGE("%s: invalid stream %d", __func__, stream);
1472 return AUDIO_IO_HANDLE_NONE;
1473 }
1474
1475 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1476 (stream != AUDIO_STREAM_MUSIC)) {
1477 // compress should not be used for non-music streams
1478 ALOGE("Offloading only allowed with music stream");
1479 return 0;
1480 }
1481
1482#ifdef COMPRESS_VOIP_ENABLED
1483 if ((mEngine->getPhoneState() == AUDIO_MODE_IN_COMMUNICATION) &&
1484 (stream == AUDIO_STREAM_VOICE_CALL) &&
1485 audio_is_linear_pcm(config->format)) {
1486 // let voice stream to go with primary output by default
1487 // in case direct voip is bypassed
1488 bool use_primary_out = true;
1489
1490 if ((config->channel_mask == 1) &&
1491 (config->sample_rate == 8000 || config->sample_rate == 16000 ||
1492 config->sample_rate == 32000 || config->sample_rate == 48000)) {
1493 // Allow Voip direct output only if:
1494 // audio mode is MODE_IN_COMMUNCATION; AND
1495 // voip output is not opened already; AND
1496 // requested sample rate matches with that of voip input stream (if opened already)
1497 int value = 0;
1498 uint32_t voipOutCount = 1, voipSampleRate = 1;
1499
1500 String8 valueStr = mpClientInterface->getParameters((audio_io_handle_t)0,
1501 String8("voip_out_stream_count"));
1502 AudioParameter result = AudioParameter(valueStr);
1503 if (result.getInt(String8("voip_out_stream_count"), value) == NO_ERROR) {
1504 voipOutCount = value;
1505 }
1506
1507 valueStr = mpClientInterface->getParameters((audio_io_handle_t)0,
1508 String8("voip_sample_rate"));
1509 result = AudioParameter(valueStr);
1510 if (result.getInt(String8("voip_sample_rate"), value) == NO_ERROR) {
1511 voipSampleRate = value;
1512 }
1513
1514 if ((voipOutCount == 0) &&
1515 ((voipSampleRate == 0) || (voipSampleRate == config->sample_rate))) {
1516 char propValue[PROPERTY_VALUE_MAX] = {0};
1517 property_get("vendor.voice.path.for.pcm.voip", propValue, "0");
1518 bool voipPcmSysPropEnabled = !strncmp("true", propValue, sizeof("true"));
1519 if (voipPcmSysPropEnabled && (config->format == AUDIO_FORMAT_PCM_16_BIT)) {
1520 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
1521 AUDIO_OUTPUT_FLAG_DIRECT);
1522 ALOGD("Set VoIP and Direct output flags for PCM format");
1523 use_primary_out = false;
1524 }
1525 }
1526 }
1527
1528 if (use_primary_out) {
1529 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_FAST|AUDIO_OUTPUT_FLAG_PRIMARY);
1530 }
1531#else
1532 if (mEngine->getPhoneState() == AUDIO_MODE_IN_COMMUNICATION &&
1533 stream == AUDIO_STREAM_VOICE_CALL &&
1534 audio_is_linear_pcm(config->format)) {
1535 //check if VoIP output is not opened already
1536 bool voip_pcm_already_in_use = false;
1537 for (size_t i = 0; i < mOutputs.size(); i++) {
1538 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1539 if (desc->mFlags == (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_DIRECT)) {
1540 //close voip output if currently open by the same client with different device
1541 if (desc->mDirectClientSession == session &&
1542 desc->device() != device) {
1543 closeOutput(desc->mIoHandle);
1544 } else {
1545 voip_pcm_already_in_use = true;
1546 ALOGD("VoIP PCM already in use");
1547 }
1548 break;
1549 }
1550 }
1551
1552 if (!voip_pcm_already_in_use) {
1553 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
1554 AUDIO_OUTPUT_FLAG_DIRECT);
1555 ALOGV("Set VoIP and Direct output flags for PCM format");
1556 }
1557#endif
1558 //IF VOIP is going to be started at the same time as when
1559 //vr is enabled, get VOIP to fallback to low latency
1560 String8 vr_value;
1561 String8 value_Str;
1562 bool is_vr_mode_on = false;
1563 AudioParameter ret;
1564
1565 value_Str = mpClientInterface->getParameters((audio_io_handle_t)0,
1566 String8("vr_audio_mode_on"));
1567 ret = AudioParameter(value_Str);
1568 if (ret.get(String8("vr_audio_mode_on"), vr_value) == NO_ERROR) {
1569 is_vr_mode_on = vr_value.contains("true");
1570 ALOGI("VR mode is %d, switch to primary output if request is for fast|raw",
1571 is_vr_mode_on);
1572 }
1573
1574 if (is_vr_mode_on) {
1575 //check the flags being requested for, and clear FAST|RAW
1576 *flags = (audio_output_flags_t)(*flags &
1577 (~(AUDIO_OUTPUT_FLAG_FAST|AUDIO_OUTPUT_FLAG_RAW)));
1578
1579 }
1580
1581 }
1582
1583#ifdef VOICE_CONCURRENCY
1584 char propValue[PROPERTY_VALUE_MAX];
1585 bool prop_play_enabled=false, prop_voip_enabled = false;
1586
1587 if(property_get("vendor.voice.playback.conc.disabled", propValue, NULL)) {
1588 prop_play_enabled = atoi(propValue) || !strncmp("true", propValue, 4);
1589 }
1590
1591 if(property_get("vendor.voice.voip.conc.disabled", propValue, NULL)) {
1592 prop_voip_enabled = atoi(propValue) || !strncmp("true", propValue, 4);
1593 }
1594
1595 bool isDeepBufferFallBackNeeded =
1596 ((AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT_PCM) & *flags);
1597 bool isFastFallBackNeeded =
1598 ((AUDIO_OUTPUT_FLAG_DEEP_BUFFER | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT_PCM) & *flags);
1599
1600 if (prop_play_enabled && mvoice_call_state) {
1601 //check if voice call is active / running in background
1602 if((AUDIO_MODE_IN_CALL == mEngine->getPhoneState()) ||
1603 ((AUDIO_MODE_IN_CALL == mPrevPhoneState)
1604 && (AUDIO_MODE_IN_COMMUNICATION == mEngine->getPhoneState())))
1605 {
1606 if(AUDIO_OUTPUT_FLAG_VOIP_RX & *flags) {
1607 if(prop_voip_enabled) {
1608 ALOGD("voice_conc:getoutput:IN call mode return no o/p for VoIP %x",
1609 *flags );
1610 return 0;
1611 }
1612 }
1613 else {
1614 if (isFastFallBackNeeded &&
1615 (AUDIO_OUTPUT_FLAG_FAST == mFallBackflag)) {
1616 ALOGD("voice_conc:IN call mode adding ULL flags .. flags: %x ", *flags );
1617 *flags = AUDIO_OUTPUT_FLAG_FAST;
1618 } else if (isDeepBufferFallBackNeeded &&
1619 (AUDIO_OUTPUT_FLAG_DEEP_BUFFER == mFallBackflag)) {
1620 if (AUDIO_STREAM_MUSIC == stream) {
1621 *flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1622 ALOGD("voice_conc:IN call mode adding deep-buffer flags %x ", *flags );
1623 }
1624 else {
1625 *flags = AUDIO_OUTPUT_FLAG_FAST;
1626 ALOGD("voice_conc:IN call mode adding fast flags %x ", *flags );
1627 }
1628 }
1629 }
1630 }
1631 } else if (prop_voip_enabled && mvoice_call_state) {
1632 //check if voice call is active / running in background
1633 //some of VoIP apps(like SIP2SIP call) supports resume of VoIP call when call in progress
1634 //return only ULL ouput
1635 if((AUDIO_MODE_IN_CALL == mEngine->getPhoneState()) ||
1636 ((AUDIO_MODE_IN_CALL == mPrevPhoneState)
1637 && (AUDIO_MODE_IN_COMMUNICATION == mEngine->getPhoneState())))
1638 {
1639 if(AUDIO_OUTPUT_FLAG_VOIP_RX & *flags) {
1640 ALOGD("voice_conc:getoutput:IN call mode return no o/p for VoIP %x",
1641 *flags );
1642 return 0;
1643 }
1644 }
1645 }
1646#endif
1647#ifdef RECORD_PLAY_CONCURRENCY
1648 char recConcPropValue[PROPERTY_VALUE_MAX];
1649 bool prop_rec_play_enabled = false;
1650
1651 if (property_get("vendor.audio.rec.playback.conc.disabled", recConcPropValue, NULL)) {
1652 prop_rec_play_enabled = atoi(recConcPropValue) || !strncmp("true", recConcPropValue, 4);
1653 }
1654 if ((prop_rec_play_enabled) &&
1655 ((true == mIsInputRequestOnProgress) || (mInputs.activeInputsCountOnDevices() > 0))) {
1656 if (AUDIO_MODE_IN_COMMUNICATION == mEngine->getPhoneState()) {
1657 if (AUDIO_OUTPUT_FLAG_VOIP_RX & *flags) {
1658 // allow VoIP using voice path
1659 // Do nothing
1660 } else if((*flags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1661 ALOGD("voice_conc:MODE_IN_COMM is setforcing deep buffer output for non ULL... flags: %x", *flags);
1662 // use deep buffer path for all non ULL outputs
1663 *flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1664 }
1665 } else if ((*flags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1666 ALOGD("voice_conc:Record mode is on forcing deep buffer output for non ULL... flags: %x ", *flags);
1667 // use deep buffer path for all non ULL outputs
1668 *flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1669 }
1670 }
1671 if (prop_rec_play_enabled &&
1672 (stream == AUDIO_STREAM_ENFORCED_AUDIBLE)) {
1673 ALOGD("Record conc is on forcing ULL output for ENFORCED_AUDIBLE");
1674 *flags = AUDIO_OUTPUT_FLAG_FAST;
1675 }
1676#endif
1677
1678#ifdef AUDIO_EXTN_AFE_PROXY_ENABLED
1679 /*
1680 * WFD audio routes back to target speaker when starting a ringtone playback.
1681 * This is because primary output is reused for ringtone, so output device is
1682 * updated based on SONIFICATION strategy for both ringtone and music playback.
1683 * The same issue is not seen on remoted_submix HAL based WFD audio because
1684 * primary output is not reused and a new output is created for ringtone playback.
1685 * Issue is fixed by updating output flag to AUDIO_OUTPUT_FLAG_FAST when there is
1686 * a non-music stream playback on WFD, so primary output is not reused for ringtone.
1687 */
1688 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
1689 if ((availableOutputDeviceTypes & AUDIO_DEVICE_OUT_PROXY)
1690 && (stream != AUDIO_STREAM_MUSIC)) {
1691 ALOGD("WFD audio: use OUTPUT_FLAG_FAST for non music stream. flags:%x", *flags );
1692 //For voip paths
1693 if (*flags & AUDIO_OUTPUT_FLAG_DIRECT)
1694 *flags = AUDIO_OUTPUT_FLAG_DIRECT;
1695 else //route every thing else to ULL path
1696 *flags = AUDIO_OUTPUT_FLAG_FAST;
1697 }
1698#endif
1699
1700 // open a direct output if required by specified parameters
1701 // force direct flag if offload flag is set: offloading implies a direct output stream
1702 // and all common behaviors are driven by checking only the direct flag
1703 // this should normally be set appropriately in the policy configuration file
1704 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1705 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
1706 }
1707 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1708 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
1709 }
1710
1711 // Do internal direct magic here
1712 bool offload_disabled = property_get_bool("audio.offload.disable", false);
1713 if ((*flags == AUDIO_OUTPUT_FLAG_NONE) &&
1714 (stream == AUDIO_STREAM_MUSIC) &&
1715 ( !offload_disabled) &&
1716 ((config->offload_info.usage == AUDIO_USAGE_MEDIA) ||
1717 (config->offload_info.usage == AUDIO_USAGE_GAME))) {
1718 audio_output_flags_t old_flags = *flags;
1719 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_DIRECT);
1720 ALOGD("Force Direct Flag .. old flags(0x%x)", old_flags);
1721 } else if (*flags == AUDIO_OUTPUT_FLAG_DIRECT &&
1722 (offload_disabled || stream != AUDIO_STREAM_MUSIC)) {
1723 ALOGD("Offloading is disabled or Stream is not music --> Force Remove Direct Flag");
1724 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_NONE);
1725 }
1726
1727 // check if direct output for pcm/track offload already exits
1728 bool direct_pcm_already_in_use = false;
1729 if (*flags == AUDIO_OUTPUT_FLAG_DIRECT) {
1730 for (size_t i = 0; i < mOutputs.size(); i++) {
1731 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1732 if (desc->mFlags == AUDIO_OUTPUT_FLAG_DIRECT) {
1733 direct_pcm_already_in_use = true;
1734 ALOGD("Direct PCM already in use");
1735 break;
1736 }
1737 }
1738 // prevent direct pcm for non-music stream blindly if direct pcm already in use
1739 // for other music stream concurrency is handled after checking direct ouput usage
1740 // and checking client
1741 if (direct_pcm_already_in_use == true && stream != AUDIO_STREAM_MUSIC) {
1742 ALOGD("disabling offload for non music stream as direct pcm is already in use");
1743 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_NONE);
1744 }
1745 }
1746
1747 bool forced_deep = false;
1748 // only allow deep buffering for music stream type
1749 if (stream != AUDIO_STREAM_MUSIC) {
1750 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1751 } else if (/* stream == AUDIO_STREAM_MUSIC && */
1752 (*flags == AUDIO_OUTPUT_FLAG_NONE || *flags == AUDIO_OUTPUT_FLAG_DIRECT) &&
1753 property_get_bool("audio.deep_buffer.media", false /* default_value */) && !isInCall()) {
1754 forced_deep = true;
1755 }
1756
1757 if (stream == AUDIO_STREAM_TTS) {
1758 *flags = AUDIO_OUTPUT_FLAG_TTS;
1759 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
1760 audio_is_linear_pcm(config->format)) {
1761 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
1762 AUDIO_OUTPUT_FLAG_DIRECT);
1763 ALOGV("Set VoIP and Direct output flags for PCM format");
1764 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
1765 stream == AUDIO_STREAM_MUSIC &&
1766 audio_is_linear_pcm(config->format) &&
1767 isInCall()) {
1768 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
1769 }
1770
1771 sp<IOProfile> profile;
1772
1773 // skip direct output selection if the request can obviously be attached to a mixed output
1774 // and not explicitly requested
1775 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1776 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1777 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1778 goto non_direct_output;
1779 }
1780
1781 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1782 // This prevents creating an offloaded track and tearing it down immediately after start
1783 // when audioflinger detects there is an active non offloadable effect.
1784 // FIXME: We should check the audio session here but we do not have it in this context.
1785 // This may prevent offloading in rare situations where effects are left active by apps
1786 // in the background.
1787 //
1788 // Supplementary annotation:
1789 // For sake of track offload introduced, we need a rollback for both compress offload
1790 // and track offload use cases.
1791 if ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD|AUDIO_OUTPUT_FLAG_DIRECT)) &&
1792 (mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1793 ALOGD("non offloadable effect is enabled, try with non direct output");
1794 goto non_direct_output;
1795 }
1796
1797 profile = getProfileForDirectOutput(device,
1798 config->sample_rate,
1799 config->format,
1800 config->channel_mask,
1801 (audio_output_flags_t)*flags);
1802
1803 if (profile != 0) {
1804
1805 if (!(*flags & AUDIO_OUTPUT_FLAG_DIRECT) &&
1806 (profile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT)) {
1807 ALOGI("got Direct without requesting ... reject ");
1808 profile = NULL;
1809 goto non_direct_output;
1810 }
1811
1812 if ((*flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0 || output != AUDIO_IO_HANDLE_NONE) {
1813 sp<SwAudioOutputDescriptor> outputDesc = NULL;
1814 // if multiple concurrent offload decode is supported
1815 // do no check for reuse and also don't close previous output if its offload
1816 // previous output will be closed during track destruction
1817 if (!(property_get_bool("vendor.audio.offload.multiple.enabled", false) &&
1818 ((*flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0))) {
1819 for (size_t i = 0; i < mOutputs.size(); i++) {
1820 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1821 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1822 outputDesc = desc;
1823 // reuse direct output if currently open by the same client
1824 // and configured with same parameters
1825 if ((config->sample_rate == desc->mSamplingRate) &&
1826 audio_formats_match(config->format, desc->mFormat) &&
1827 (config->channel_mask == desc->mChannelMask) &&
1828 (session == desc->mDirectClientSession)) {
1829 desc->mDirectOpenCount++;
1830 ALOGV("getOutputForDevice() reusing direct output %d for session %d",
1831 mOutputs.keyAt(i), session);
1832 return mOutputs.keyAt(i);
1833 }
1834 }
1835 }
1836 if (outputDesc != NULL) {
1837 if (*flags == AUDIO_OUTPUT_FLAG_DIRECT &&
1838 direct_pcm_already_in_use == true &&
1839 session != outputDesc->mDirectClientSession) {
1840 ALOGV("getOutput() do not reuse direct pcm output because current client (%d) "
1841 "is not the same as requesting client (%d) for different output conf",
1842 outputDesc->mDirectClientSession, session);
1843 goto non_direct_output;
1844 }
1845 closeOutput(outputDesc->mIoHandle);
1846 }
1847
1848 }
1849 if (!profile->canOpenNewIo()) {
1850 goto non_direct_output;
1851 }
1852
1853 outputDesc =
1854 new SwAudioOutputDescriptor(profile, mpClientInterface);
1855 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
1856 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1857 : String8("");
1858 status = outputDesc->open(config, device, address, stream, *flags, &output);
1859
1860 // only accept an output with the requested parameters
1861 if (status != NO_ERROR ||
1862 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
1863 (config->format != AUDIO_FORMAT_DEFAULT &&
1864 !audio_formats_match(config->format, outputDesc->mFormat)) ||
1865 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1866 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1867 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1868 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1869 config->channel_mask, outputDesc->mChannelMask);
1870 if (output != AUDIO_IO_HANDLE_NONE) {
1871 outputDesc->close();
1872 }
1873 // fall back to mixer output if possible when the direct output could not be open
1874 if (audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1875 goto non_direct_output;
1876 }
1877 return AUDIO_IO_HANDLE_NONE;
1878 }
1879 outputDesc->mRefCount[stream] = 0;
1880 outputDesc->mStopTime[stream] = 0;
1881 outputDesc->mDirectOpenCount = 1;
1882 outputDesc->mDirectClientSession = session;
1883
1884 addOutput(output, outputDesc);
1885 mPreviousOutputs = mOutputs;
1886 ALOGV("getOutputForDevice() returns new direct output %d", output);
1887 mpClientInterface->onAudioPortListUpdate();
1888 return output;
1889 }
1890 }
1891
1892non_direct_output:
1893
1894 // A request for HW A/V sync cannot fallback to a mixed output because time
1895 // stamps are embedded in audio data
1896 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1897 return AUDIO_IO_HANDLE_NONE;
1898 }
1899
1900 // ignoring channel mask due to downmix capability in mixer
1901
1902 // open a non direct output
1903
1904 // for non direct outputs, only PCM is supported
1905 if (audio_is_linear_pcm(config->format)) {
1906 // get which output is suitable for the specified stream. The actual
1907 // routing change will happen when startOutput() will be called
1908 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1909
1910 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1911 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1912
1913 if (forced_deep) {
1914 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1915 ALOGI("setting force DEEP buffer now ");
1916 } else if(*flags == AUDIO_OUTPUT_FLAG_NONE) {
1917 // no deep buffer playback is requested hence fallback to primary
1918 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_PRIMARY);
1919 ALOGI("FLAG None hence request for a primary output");
1920 }
1921
1922 output = selectOutput(outputs, *flags, config->format);
1923 }
1924
1925 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
1926 "sampling rate %d, format %#x, channels %#x, flags %#x",
1927 stream, config->sample_rate, config->format, config->channel_mask, *flags);
1928
1929 ALOGV("getOutputForDevice() returns output %d", output);
1930
1931 return output;
1932}
1933
1934status_t AudioPolicyManagerCustom::getInputForAttr(const audio_attributes_t *attr,
1935 audio_io_handle_t *input,
1936 audio_session_t session,
1937 uid_t uid,
1938 const audio_config_base_t *config,
1939 audio_input_flags_t flags,
1940 audio_port_handle_t *selectedDeviceId,
1941 input_type_t *inputType,
1942 audio_port_handle_t *portId)
1943{
1944 audio_source_t inputSource;
1945 inputSource = attr->source;
1946#ifdef VOICE_CONCURRENCY
1947
1948 char propValue[PROPERTY_VALUE_MAX];
1949 bool prop_rec_enabled=false, prop_voip_enabled = false;
1950
1951 if(property_get("vendor.voice.record.conc.disabled", propValue, NULL)) {
1952 prop_rec_enabled = atoi(propValue) || !strncmp("true", propValue, 4);
1953 }
1954
1955 if(property_get("vendor.voice.voip.conc.disabled", propValue, NULL)) {
1956 prop_voip_enabled = atoi(propValue) || !strncmp("true", propValue, 4);
1957 }
1958
1959 if (prop_rec_enabled && mvoice_call_state) {
1960 //check if voice call is active / running in background
1961 //some of VoIP apps(like SIP2SIP call) supports resume of VoIP call when call in progress
1962 //Need to block input request
1963 if((AUDIO_MODE_IN_CALL == mEngine->getPhoneState()) ||
1964 ((AUDIO_MODE_IN_CALL == mPrevPhoneState) &&
1965 (AUDIO_MODE_IN_COMMUNICATION == mEngine->getPhoneState())))
1966 {
1967 switch(inputSource) {
1968 case AUDIO_SOURCE_VOICE_UPLINK:
1969 case AUDIO_SOURCE_VOICE_DOWNLINK:
1970 case AUDIO_SOURCE_VOICE_CALL:
1971 ALOGD("voice_conc:Creating input during incall mode for inputSource: %d",
1972 inputSource);
1973 break;
1974
1975 case AUDIO_SOURCE_VOICE_COMMUNICATION:
1976 if(prop_voip_enabled) {
1977 ALOGD("voice_conc:BLOCK VoIP requst incall mode for inputSource: %d",
1978 inputSource);
1979 return NO_INIT;
1980 }
1981 break;
1982 default:
1983 ALOGD("voice_conc:BLOCK VoIP requst incall mode for inputSource: %d",
1984 inputSource);
1985 return NO_INIT;
1986 }
1987 }
1988 }//check for VoIP flag
1989 else if(prop_voip_enabled && mvoice_call_state) {
1990 //check if voice call is active / running in background
1991 //some of VoIP apps(like SIP2SIP call) supports resume of VoIP call when call in progress
1992 //Need to block input request
1993 if((AUDIO_MODE_IN_CALL == mEngine->getPhoneState()) ||
1994 ((AUDIO_MODE_IN_CALL == mPrevPhoneState) &&
1995 (AUDIO_MODE_IN_COMMUNICATION == mEngine->getPhoneState())))
1996 {
1997 if(inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION) {
1998 ALOGD("BLOCKING VoIP request during incall mode for inputSource: %d ",inputSource);
1999 return NO_INIT;
2000 }
2001 }
2002 }
2003
2004#endif
2005
2006 return AudioPolicyManager::getInputForAttr(attr,
2007 input,
2008 session,
2009 uid,
2010 config,
2011 flags,
2012 selectedDeviceId,
2013 inputType,
2014 portId);
2015}
2016
2017uint32_t AudioPolicyManagerCustom::activeNonSoundTriggerInputsCountOnDevices(audio_devices_t devices) const
2018{
2019 uint32_t count = 0;
2020 for (size_t i = 0; i < mInputs.size(); i++) {
2021 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
2022 if (inputDescriptor->isActive() && !inputDescriptor->isSoundTrigger() &&
2023 ((devices == AUDIO_DEVICE_IN_DEFAULT) ||
2024 ((inputDescriptor->mDevice & devices & ~AUDIO_DEVICE_BIT_IN) != 0))) {
2025 count++;
2026 }
2027 }
2028 return count;
2029}
2030
2031status_t AudioPolicyManagerCustom::startInput(audio_io_handle_t input,
2032 audio_session_t session,
2033 bool silenced,
2034 concurrency_type__mask_t *concurrency)
2035{
2036
2037 ALOGV("startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
2038 input, session, silenced, *concurrency);
2039 *concurrency = API_INPUT_CONCURRENCY_NONE;
2040 ssize_t index = mInputs.indexOfKey(input);
2041 if (index < 0) {
2042 ALOGW("startInput() unknown input %d", input);
2043 return BAD_VALUE;
2044 }
2045 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2046
2047 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2048 if (audioSession == 0) {
2049 ALOGW("startInput() unknown session %d on input %d", session, input);
2050 return BAD_VALUE;
2051 }
2052
2053// FIXME: disable concurrent capture until UI is ready
2054#if 0
2055 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
2056 ALOGW("startInput(%d) failed: other input already started", input);
2057 return INVALID_OPERATION;
2058 }
2059
2060 if (isInCall()) {
2061 *concurrency |= API_INPUT_CONCURRENCY_CALL;
2062 }
2063
2064 if (mInputs.activeInputsCountOnDevices() != 0) {
2065 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
2066 }
2067#else
2068 if (!is_virtual_input_device(inputDesc->mDevice)) {
2069 if (mCallTxPatch != 0 &&
2070 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2071 ALOGW("startInput(%d) failed: call in progress", input);
2072 return INVALID_OPERATION;
2073 }
2074
2075 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
2076
2077 // If a UID is idle and records silence and another not silenced recording starts
2078 // from another UID (idle or active) we stop the current idle UID recording in
2079 // favor of the new one - "There can be only one" TM
2080 if (!silenced) {
2081
2082 for (const auto& activeDesc : activeInputs) {
2083 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2084 activeDesc->getId() == inputDesc->getId()) {
2085 continue;
2086 }
2087
2088 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
2089 true /*activeOnly*/);
2090 sp<AudioSession> activeSession = activeSessions.valueAt(0);
2091 if (activeSession->isSilenced()) {
2092 audio_io_handle_t activeInput = activeDesc->mIoHandle;
2093 audio_session_t activeSessionId = activeSession->session();
2094 stopInput(activeInput, activeSessionId);
2095 releaseInput(activeInput, activeSessionId);
2096 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
2097 activeInputs = mInputs.getActiveInputs();
2098 }
2099 }
2100 }
2101 for (const auto& activeDesc : activeInputs) {
2102 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2103 activeDesc->getId() == inputDesc->getId()) {
2104 continue;
2105 }
2106 // Don't allow sound triggers streams to preempt one another.
2107 if (inputDesc->isSoundTrigger() && activeDesc->isSoundTrigger()) {
2108 continue;
2109 }
2110
2111 audio_source_t activeSource = activeDesc->inputSource(true);
2112 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
2113 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2114 if (activeDesc->hasPreemptedSession(session)) {
2115 ALOGW("startInput(%d) failed for HOTWORD: "
2116 "other input %d already started for HOTWORD",
2117 input, activeDesc->mIoHandle);
2118 return INVALID_OPERATION;
2119 }
2120 } else {
2121 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
2122 input, activeDesc->mIoHandle);
2123 return INVALID_OPERATION;
2124 }
2125 } else {
2126 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2127 ALOGW("startInput(%d) failed: other input %d already started",
2128 input, activeDesc->mIoHandle);
2129 return INVALID_OPERATION;
2130 }
2131 }
2132 }
2133
2134 // We only need to check if the sound trigger session supports concurrent capture if the
2135 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2136 // that's running.
2137 const bool allowConcurrentWithSoundTrigger =
2138 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2139
2140 // if capture is allowed, preempt currently active HOTWORD captures
2141 for (const auto& activeDesc : activeInputs) {
2142 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2143 continue;
2144 }
2145
2146 audio_source_t activeSource = activeDesc->inputSource(true);
2147 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2148 AudioSessionCollection activeSessions =
2149 activeDesc->getAudioSessions(true /*activeOnly*/);
2150 audio_session_t activeSession = activeSessions.keyAt(0);
2151 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2152 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2153 sessions.add(activeSession);
2154 inputDesc->setPreemptedSessions(sessions);
2155 stopInput(activeHandle, activeSession);
2156 releaseInput(activeHandle, activeSession);
2157 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2158 input, activeDesc->mIoHandle);
2159 }
2160 }
2161 }
2162#endif
2163
2164#ifdef RECORD_PLAY_CONCURRENCY
2165 mIsInputRequestOnProgress = true;
2166
2167 char getPropValue[PROPERTY_VALUE_MAX];
2168 bool prop_rec_play_enabled = false;
2169
2170 if (property_get("vendor.audio.rec.playback.conc.disabled", getPropValue, NULL)) {
2171 prop_rec_play_enabled = atoi(getPropValue) || !strncmp("true", getPropValue, 4);
2172 }
2173
2174 if ((prop_rec_play_enabled) && (mInputs.activeInputsCountOnDevices() == 0)){
2175 // send update to HAL on record playback concurrency
2176 AudioParameter param = AudioParameter();
2177 param.add(String8("rec_play_conc_on"), String8("true"));
2178 ALOGD("startInput() setParameters rec_play_conc is setting to ON ");
2179 mpClientInterface->setParameters(0, param.toString());
2180
2181 // Call invalidate to reset all opened non ULL audio tracks
2182 // Move tracks associated to this strategy from previous output to new output
2183 for (int i = AUDIO_STREAM_SYSTEM; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
2184 // Do not call invalidate for ENFORCED_AUDIBLE (otherwise pops are seen for camcorder)
2185 if (i != AUDIO_STREAM_ENFORCED_AUDIBLE) {
2186 ALOGD("Invalidate on releaseInput for stream :: %d ", i);
2187 //FIXME see fixme on name change
2188 mpClientInterface->invalidateStream((audio_stream_type_t)i);
2189 }
2190 }
2191 // close compress tracks
2192 for (size_t i = 0; i < mOutputs.size(); i++) {
2193 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
2194 if ((outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
2195 ALOGD("ouput desc / profile is NULL");
2196 continue;
2197 }
2198 if (outputDesc->mProfile->getFlags()
2199 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2200 // close compress sessions
2201 ALOGD("calling closeOutput on record conc for COMPRESS output");
2202 closeOutput(mOutputs.keyAt(i));
2203 }
2204 }
2205 }
2206#endif
2207
2208 // increment activity count before calling getNewInputDevice() below as only active sessions
2209 // are considered for device selection
2210 audioSession->changeActiveCount(1);
2211
2212 // Routing?
2213 mInputRoutes.incRouteActivity(session);
2214
2215 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
2216 // indicate active capture to sound trigger service if starting capture from a mic on
2217 // primary HW module
2218 audio_devices_t device = getNewInputDevice(inputDesc);
2219 setInputDevice(input, device, true /* force */);
2220 status_t status = inputDesc->start();
2221 if (status != NO_ERROR) {
2222 mInputRoutes.decRouteActivity(session);
2223 audioSession->changeActiveCount(-1);
2224 return status;
2225 }
2226
2227 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2228 // if input maps to a dynamic policy with an activity listener, notify of state change
2229 if ((inputDesc->mPolicyMix != NULL)
2230 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2231 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2232 MIX_STATE_MIXING);
2233 }
2234
2235 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2236 if ((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) {
2237 if (property_get_bool("persist.vendor.audio.va_concurrency_enabled", false)) {
2238 if (activeNonSoundTriggerInputsCountOnDevices(primaryInputDevices) == 1)
2239 SoundTrigger::setCaptureState(true);
2240 } else if (mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1)
2241 SoundTrigger::setCaptureState(true);
2242 }
2243
2244 // automatically enable the remote submix output when input is started if not
2245 // used by a policy mix of type MIX_TYPE_RECORDERS
2246 // For remote submix (a virtual device), we open only one input per capture request.
2247 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2248 String8 address = String8("");
2249 if (inputDesc->mPolicyMix == NULL) {
2250 address = String8("0");
2251 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2252 address = inputDesc->mPolicyMix->mDeviceAddress;
2253 }
2254 if (address != "") {
2255 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2256 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2257 address, "remote-submix");
2258 }
2259 }
2260 }
2261 }
2262
2263 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
2264#ifdef RECORD_PLAY_CONCURRENCY
2265 mIsInputRequestOnProgress = false;
2266#endif
2267 return NO_ERROR;
2268}
2269
2270status_t AudioPolicyManagerCustom::stopInput(audio_io_handle_t input,
2271 audio_session_t session)
2272{
2273 status_t status;
2274 status = AudioPolicyManager::stopInput(input, session);
2275 if (property_get_bool("persist.vendor.audio.va_concurrency_enabled", false)) {
2276 ssize_t index = mInputs.indexOfKey(input);
2277 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2278 audio_devices_t device = inputDesc->mDevice;
2279 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2280 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2281 activeNonSoundTriggerInputsCountOnDevices(primaryInputDevices) == 0) {
2282 SoundTrigger::setCaptureState(false);
2283 }
2284 }
2285#ifdef RECORD_PLAY_CONCURRENCY
2286 char propValue[PROPERTY_VALUE_MAX];
2287 bool prop_rec_play_enabled = false;
2288
2289 if (property_get("vendor.audio.rec.playback.conc.disabled", propValue, NULL)) {
2290 prop_rec_play_enabled = atoi(propValue) || !strncmp("true", propValue, 4);
2291 }
2292
2293 if ((prop_rec_play_enabled) && (mInputs.activeInputsCountOnDevices() == 0)) {
2294
2295 //send update to HAL on record playback concurrency
2296 AudioParameter param = AudioParameter();
2297 param.add(String8("rec_play_conc_on"), String8("false"));
2298 ALOGD("stopInput() setParameters rec_play_conc is setting to OFF ");
2299 mpClientInterface->setParameters(0, param.toString());
2300
2301 //call invalidate tracks so that any open streams can fall back to deep buffer/compress path from ULL
2302 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
2303 //Do not call invalidate for ENFORCED_AUDIBLE (otherwise pops are seen for camcorder stop tone)
2304 if ((i != AUDIO_STREAM_ENFORCED_AUDIBLE) && (i != AUDIO_STREAM_PATCH)) {
2305 ALOGD(" Invalidate on stopInput for stream :: %d ", i);
2306 //FIXME see fixme on name change
2307 mpClientInterface->invalidateStream((audio_stream_type_t)i);
2308 }
2309 }
2310 }
2311#endif
2312 return status;
2313}
2314
2315AudioPolicyManagerCustom::AudioPolicyManagerCustom(AudioPolicyClientInterface *clientInterface)
2316 : AudioPolicyManager(clientInterface),
2317 mHdmiAudioDisabled(false),
2318 mHdmiAudioEvent(false),
2319#ifndef FM_POWER_OPT
2320 mPrevPhoneState(0)
2321#else
2322 mPrevPhoneState(0),
2323 mPrevFMVolumeDb(0.0f),
2324 mFMIsActive(false)
2325#endif
2326{
2327
2328#ifdef USE_XML_AUDIO_POLICY_CONF
2329 ALOGD("USE_XML_AUDIO_POLICY_CONF is TRUE");
2330#else
2331 ALOGD("USE_XML_AUDIO_POLICY_CONF is FALSE");
2332#endif
2333
2334#ifdef RECORD_PLAY_CONCURRENCY
2335 mIsInputRequestOnProgress = false;
2336#endif
2337
2338
2339#ifdef VOICE_CONCURRENCY
2340 mFallBackflag = getFallBackPath();
2341#endif
2342}
2343}