1 /*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "APM_AudioPolicyManager"
18 //#define LOG_NDEBUG 0
19
20 //#define VERY_VERBOSE_LOGGING
21 #ifdef VERY_VERBOSE_LOGGING
22 #define ALOGVV ALOGV
23 #else
24 #define ALOGVV(a...) do { } while(0)
25 #endif
26
27 #define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28 #define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
29 #define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
31
32 #include <inttypes.h>
33 #include <math.h>
34
35 #include <AudioPolicyManagerInterface.h>
36 #include <AudioPolicyEngineInstance.h>
37 #include <cutils/properties.h>
38 #include <utils/Log.h>
39 #include <media/AudioParameter.h>
40 #include <media/AudioPolicyHelper.h>
41 #include <soundtrigger/SoundTrigger.h>
42 #include <system/audio.h>
43 #include <audio_policy_conf.h>
44 #include "AudioPolicyManager.h"
45 #ifndef USE_XML_AUDIO_POLICY_CONF
46 #include <ConfigParsingUtils.h>
47 #include <StreamDescriptor.h>
48 #endif
49 #include <Serializer.h>
50 #include "TypeConverter.h"
51 #include <policy.h>
52
53 namespace android {
54
55 //FIXME: workaround for truncated touch sounds
56 // to be removed when the problem is handled by system UI
57 #define TOUCH_SOUND_FIXED_DELAY_MS 100
58
59 // Largest difference in dB on earpiece in call between the voice volume and another
60 // media / notification / system volume.
61 constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
62
63 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64 // Array of all surround formats.
65 static const audio_format_t SURROUND_FORMATS[] = {
66 AUDIO_FORMAT_AC3,
67 AUDIO_FORMAT_E_AC3,
68 AUDIO_FORMAT_DTS,
69 AUDIO_FORMAT_DTS_HD,
70 AUDIO_FORMAT_AAC_LC,
71 AUDIO_FORMAT_DOLBY_TRUEHD,
72 AUDIO_FORMAT_E_AC3_JOC,
73 };
74 // Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
75 static const audio_format_t AAC_FORMATS[] = {
76 AUDIO_FORMAT_AAC_LC,
77 AUDIO_FORMAT_AAC_HE_V1,
78 AUDIO_FORMAT_AAC_HE_V2,
79 AUDIO_FORMAT_AAC_ELD,
80 AUDIO_FORMAT_AAC_XHE,
81 };
82
83 // ----------------------------------------------------------------------------
84 // AudioPolicyInterface implementation
85 // ----------------------------------------------------------------------------
86
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name)87 status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
88 audio_policy_dev_state_t state,
89 const char *device_address,
90 const char *device_name)
91 {
92 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
93 nextAudioPortGeneration();
94 return status;
95 }
96
broadcastDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const String8 & device_address)97 void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
98 audio_policy_dev_state_t state,
99 const String8 &device_address)
100 {
101 AudioParameter param(device_address);
102 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
103 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
104 param.addInt(key, device);
105 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
106 }
107
setDeviceConnectionStateInt(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name)108 status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
109 audio_policy_dev_state_t state,
110 const char *device_address,
111 const char *device_name)
112 {
113 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
114 device, state, device_address, device_name);
115
116 // connect/disconnect only 1 device at a time
117 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
118
119 sp<DeviceDescriptor> devDesc =
120 mHwModules.getDeviceDescriptor(device, device_address, device_name);
121
122 // handle output devices
123 if (audio_is_output_device(device)) {
124 SortedVector <audio_io_handle_t> outputs;
125
126 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
127
128 // save a copy of the opened output descriptors before any output is opened or closed
129 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
130 mPreviousOutputs = mOutputs;
131 switch (state)
132 {
133 // handle output device connection
134 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
135 if (index >= 0) {
136 ALOGW("setDeviceConnectionState() device already connected: %x", device);
137 return INVALID_OPERATION;
138 }
139 ALOGV("setDeviceConnectionState() connecting device %x", device);
140
141 // register new device as available
142 index = mAvailableOutputDevices.add(devDesc);
143 if (index >= 0) {
144 sp<HwModule> module = mHwModules.getModuleForDevice(device);
145 if (module == 0) {
146 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
147 device);
148 mAvailableOutputDevices.remove(devDesc);
149 return INVALID_OPERATION;
150 }
151 mAvailableOutputDevices[index]->attach(module);
152 } else {
153 return NO_MEMORY;
154 }
155
156 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
157 // parameters on newly connected devices (instead of opening the outputs...)
158 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
159
160 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
161 mAvailableOutputDevices.remove(devDesc);
162
163 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
164 devDesc->mAddress);
165 return INVALID_OPERATION;
166 }
167 // Propagate device availability to Engine
168 mEngine->setDeviceConnectionState(devDesc, state);
169
170 // outputs should never be empty here
171 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
172 "checkOutputsForDevice() returned no outputs but status OK");
173 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
174 outputs.size());
175
176 } break;
177 // handle output device disconnection
178 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
179 if (index < 0) {
180 ALOGW("setDeviceConnectionState() device not connected: %x", device);
181 return INVALID_OPERATION;
182 }
183
184 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
185
186 // Send Disconnect to HALs
187 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
188
189 // remove device from available output devices
190 mAvailableOutputDevices.remove(devDesc);
191
192 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
193
194 // Propagate device availability to Engine
195 mEngine->setDeviceConnectionState(devDesc, state);
196 } break;
197
198 default:
199 ALOGE("setDeviceConnectionState() invalid state: %x", state);
200 return BAD_VALUE;
201 }
202
203 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
204 // output is suspended before any tracks are moved to it
205 checkA2dpSuspend();
206 checkOutputForAllStrategies();
207 // outputs must be closed after checkOutputForAllStrategies() is executed
208 if (!outputs.isEmpty()) {
209 for (audio_io_handle_t output : outputs) {
210 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
211 // close unused outputs after device disconnection or direct outputs that have been
212 // opened by checkOutputsForDevice() to query dynamic parameters
213 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
214 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
215 (desc->mDirectOpenCount == 0))) {
216 closeOutput(output);
217 }
218 }
219 // check again after closing A2DP output to reset mA2dpSuspended if needed
220 checkA2dpSuspend();
221 }
222
223 updateDevicesAndOutputs();
224 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
225 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
226 updateCallRouting(newDevice);
227 }
228 for (size_t i = 0; i < mOutputs.size(); i++) {
229 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
230 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
231 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
232 // do not force device change on duplicated output because if device is 0, it will
233 // also force a device 0 for the two outputs it is duplicated to which may override
234 // a valid device selection on those outputs.
235 bool force = !desc->isDuplicated()
236 && (!device_distinguishes_on_address(device)
237 // always force when disconnecting (a non-duplicated device)
238 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
239 setOutputDevice(desc, newDevice, force, 0);
240 }
241 }
242
243 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
244 cleanUpForDevice(devDesc);
245 }
246
247 mpClientInterface->onAudioPortListUpdate();
248 return NO_ERROR;
249 } // end if is output device
250
251 // handle input devices
252 if (audio_is_input_device(device)) {
253 SortedVector <audio_io_handle_t> inputs;
254
255 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
256 switch (state)
257 {
258 // handle input device connection
259 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
260 if (index >= 0) {
261 ALOGW("setDeviceConnectionState() device already connected: %d", device);
262 return INVALID_OPERATION;
263 }
264 sp<HwModule> module = mHwModules.getModuleForDevice(device);
265 if (module == NULL) {
266 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
267 device);
268 return INVALID_OPERATION;
269 }
270
271 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
272 // parameters on newly connected devices (instead of opening the inputs...)
273 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
274
275 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
276 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
277 devDesc->mAddress);
278 return INVALID_OPERATION;
279 }
280
281 index = mAvailableInputDevices.add(devDesc);
282 if (index >= 0) {
283 mAvailableInputDevices[index]->attach(module);
284 } else {
285 return NO_MEMORY;
286 }
287
288 // Propagate device availability to Engine
289 mEngine->setDeviceConnectionState(devDesc, state);
290 } break;
291
292 // handle input device disconnection
293 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
294 if (index < 0) {
295 ALOGW("setDeviceConnectionState() device not connected: %d", device);
296 return INVALID_OPERATION;
297 }
298
299 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
300
301 // Set Disconnect to HALs
302 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
303
304 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
305 mAvailableInputDevices.remove(devDesc);
306
307 // Propagate device availability to Engine
308 mEngine->setDeviceConnectionState(devDesc, state);
309 } break;
310
311 default:
312 ALOGE("setDeviceConnectionState() invalid state: %x", state);
313 return BAD_VALUE;
314 }
315
316 closeAllInputs();
317 // As the input device list can impact the output device selection, update
318 // getDeviceForStrategy() cache
319 updateDevicesAndOutputs();
320
321 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
322 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
323 updateCallRouting(newDevice);
324 }
325
326 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
327 cleanUpForDevice(devDesc);
328 }
329
330 mpClientInterface->onAudioPortListUpdate();
331 return NO_ERROR;
332 } // end if is input device
333
334 ALOGW("setDeviceConnectionState() invalid device: %x", device);
335 return BAD_VALUE;
336 }
337
getDeviceConnectionState(audio_devices_t device,const char * device_address)338 audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
339 const char *device_address)
340 {
341 sp<DeviceDescriptor> devDesc =
342 mHwModules.getDeviceDescriptor(device, device_address, "",
343 (strlen(device_address) != 0)/*matchAddress*/);
344
345 if (devDesc == 0) {
346 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
347 device, device_address);
348 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
349 }
350
351 DeviceVector *deviceVector;
352
353 if (audio_is_output_device(device)) {
354 deviceVector = &mAvailableOutputDevices;
355 } else if (audio_is_input_device(device)) {
356 deviceVector = &mAvailableInputDevices;
357 } else {
358 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
359 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
360 }
361
362 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
363 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
364 }
365
handleDeviceConfigChange(audio_devices_t device,const char * device_address,const char * device_name)366 status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
367 const char *device_address,
368 const char *device_name)
369 {
370 status_t status;
371 String8 reply;
372 AudioParameter param;
373 int isReconfigA2dpSupported = 0;
374
375 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
376 device, device_address, device_name);
377
378 // connect/disconnect only 1 device at a time
379 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
380
381 // Check if the device is currently connected
382 sp<DeviceDescriptor> devDesc =
383 mHwModules.getDeviceDescriptor(device, device_address, device_name);
384 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
385 if (index < 0) {
386 // Nothing to do: device is not connected
387 return NO_ERROR;
388 }
389
390 // For offloaded A2DP, Hw modules may have the capability to
391 // configure codecs. Check if any of the loaded hw modules
392 // supports this.
393 // If supported, send a set parameter to configure A2DP codecs
394 // and return. No need to toggle device state.
395 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
396 reply = mpClientInterface->getParameters(
397 AUDIO_IO_HANDLE_NONE,
398 String8(AudioParameter::keyReconfigA2dpSupported));
399 AudioParameter repliedParameters(reply);
400 repliedParameters.getInt(
401 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
402 if (isReconfigA2dpSupported) {
403 const String8 key(AudioParameter::keyReconfigA2dp);
404 param.add(key, String8("true"));
405 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
406 return NO_ERROR;
407 }
408 }
409
410 // Toggle the device state: UNAVAILABLE -> AVAILABLE
411 // This will force reading again the device configuration
412 status = setDeviceConnectionState(device,
413 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
414 device_address, device_name);
415 if (status != NO_ERROR) {
416 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
417 status);
418 return status;
419 }
420
421 status = setDeviceConnectionState(device,
422 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
423 device_address, device_name);
424 if (status != NO_ERROR) {
425 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
426 status);
427 return status;
428 }
429
430 return NO_ERROR;
431 }
432
updateCallRouting(audio_devices_t rxDevice,uint32_t delayMs)433 uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
434 {
435 bool createTxPatch = false;
436 uint32_t muteWaitMs = 0;
437
438 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
439 return muteWaitMs;
440 }
441 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
442 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
443
444 // release existing RX patch if any
445 if (mCallRxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
447 mCallRxPatch.clear();
448 }
449 // release TX patch if any
450 if (mCallTxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
452 mCallTxPatch.clear();
453 }
454
455 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
456 // via setOutputDevice() on primary output.
457 // Otherwise, create two audio patches for TX and RX path.
458 if (availablePrimaryOutputDevices() & rxDevice) {
459 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
460 // If the TX device is also on the primary HW module, setOutputDevice() will take care
461 // of it due to legacy implementation. If not, create a patch.
462 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
463 == AUDIO_DEVICE_NONE) {
464 createTxPatch = true;
465 }
466 } else { // create RX path audio patch
467 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
468 createTxPatch = true;
469 }
470 if (createTxPatch) { // create TX path audio patch
471 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
472 }
473
474 return muteWaitMs;
475 }
476
createTelephonyPatch(bool isRx,audio_devices_t device,uint32_t delayMs)477 sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
478 bool isRx, audio_devices_t device, uint32_t delayMs) {
479 struct audio_patch patch;
480 patch.num_sources = 1;
481 patch.num_sinks = 1;
482
483 sp<DeviceDescriptor> txSourceDeviceDesc;
484 if (isRx) {
485 fillAudioPortConfigForDevice(mAvailableOutputDevices, device, &patch.sinks[0]);
486 fillAudioPortConfigForDevice(
487 mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX, &patch.sources[0]);
488 } else {
489 txSourceDeviceDesc = fillAudioPortConfigForDevice(
490 mAvailableInputDevices, device, &patch.sources[0]);
491 fillAudioPortConfigForDevice(
492 mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX, &patch.sinks[0]);
493 }
494
495 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
496 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
497 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
498 // request to reuse existing output stream if one is already opened to reach the target device
499 if (output != AUDIO_IO_HANDLE_NONE) {
500 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
501 ALOG_ASSERT(!outputDesc->isDuplicated(),
502 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
503 outputDesc->toAudioPortConfig(&patch.sources[1]);
504 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
505 patch.num_sources = 2;
506 }
507
508 if (!isRx) {
509 // terminate active capture if on the same HW module as the call TX source device
510 // FIXME: would be better to refine to only inputs whose profile connects to the
511 // call TX device but this information is not in the audio patch and logic here must be
512 // symmetric to the one in startInput()
513 for (const auto& activeDesc : mInputs.getActiveInputs()) {
514 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
515 AudioSessionCollection activeSessions =
516 activeDesc->getAudioSessions(true /*activeOnly*/);
517 for (size_t j = 0; j < activeSessions.size(); j++) {
518 audio_session_t activeSession = activeSessions.keyAt(j);
519 stopInput(activeDesc->mIoHandle, activeSession);
520 releaseInput(activeDesc->mIoHandle, activeSession);
521 }
522 }
523 }
524 }
525
526 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
527 status_t status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
528 ALOGW_IF(status != NO_ERROR,
529 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
530 sp<AudioPatch> audioPatch;
531 if (status == NO_ERROR) {
532 audioPatch = new AudioPatch(&patch, mUidCached);
533 audioPatch->mAfPatchHandle = afPatchHandle;
534 audioPatch->mUid = mUidCached;
535 }
536 return audioPatch;
537 }
538
fillAudioPortConfigForDevice(const DeviceVector & devices,audio_devices_t device,audio_port_config * config)539 sp<DeviceDescriptor> AudioPolicyManager::fillAudioPortConfigForDevice(
540 const DeviceVector& devices, audio_devices_t device, audio_port_config *config) {
541 DeviceVector deviceList = devices.getDevicesFromType(device);
542 ALOG_ASSERT(!deviceList.isEmpty(),
543 "%s() selected device type %#x is not in devices list", __func__, device);
544 sp<DeviceDescriptor> deviceDesc = deviceList.itemAt(0);
545 deviceDesc->toAudioPortConfig(config);
546 return deviceDesc;
547 }
548
setPhoneState(audio_mode_t state)549 void AudioPolicyManager::setPhoneState(audio_mode_t state)
550 {
551 ALOGV("setPhoneState() state %d", state);
552 // store previous phone state for management of sonification strategy below
553 int oldState = mEngine->getPhoneState();
554
555 if (mEngine->setPhoneState(state) != NO_ERROR) {
556 ALOGW("setPhoneState() invalid or same state %d", state);
557 return;
558 }
559 /// Opens: can these line be executed after the switch of volume curves???
560 // if leaving call state, handle special case of active streams
561 // pertaining to sonification strategy see handleIncallSonification()
562 if (isStateInCall(oldState)) {
563 ALOGV("setPhoneState() in call state management: new state is %d", state);
564 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
565 handleIncallSonification((audio_stream_type_t)stream, false, true);
566 }
567
568 // force reevaluating accessibility routing when call stops
569 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
570 }
571
572 /**
573 * Switching to or from incall state or switching between telephony and VoIP lead to force
574 * routing command.
575 */
576 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
577 || (is_state_in_call(state) && (state != oldState)));
578
579 // check for device and output changes triggered by new phone state
580 checkA2dpSuspend();
581 checkOutputForAllStrategies();
582 updateDevicesAndOutputs();
583
584 int delayMs = 0;
585 if (isStateInCall(state)) {
586 nsecs_t sysTime = systemTime();
587 for (size_t i = 0; i < mOutputs.size(); i++) {
588 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
589 // mute media and sonification strategies and delay device switch by the largest
590 // latency of any output where either strategy is active.
591 // This avoid sending the ring tone or music tail into the earpiece or headset.
592 if ((isStrategyActive(desc, STRATEGY_MEDIA,
593 SONIFICATION_HEADSET_MUSIC_DELAY,
594 sysTime) ||
595 isStrategyActive(desc, STRATEGY_SONIFICATION,
596 SONIFICATION_HEADSET_MUSIC_DELAY,
597 sysTime)) &&
598 (delayMs < (int)desc->latency()*2)) {
599 delayMs = desc->latency()*2;
600 }
601 setStrategyMute(STRATEGY_MEDIA, true, desc);
602 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
603 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
604 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
605 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
606 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
607 }
608 }
609
610 if (hasPrimaryOutput()) {
611 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
612 // the device returned is not necessarily reachable via this output
613 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
614 // force routing command to audio hardware when ending call
615 // even if no device change is needed
616 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
617 rxDevice = mPrimaryOutput->device();
618 }
619
620 if (state == AUDIO_MODE_IN_CALL) {
621 updateCallRouting(rxDevice, delayMs);
622 } else if (oldState == AUDIO_MODE_IN_CALL) {
623 if (mCallRxPatch != 0) {
624 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
625 mCallRxPatch.clear();
626 }
627 if (mCallTxPatch != 0) {
628 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
629 mCallTxPatch.clear();
630 }
631 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
632 } else {
633 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
634 }
635 }
636
637 // reevaluate routing on all outputs in case tracks have been started during the call
638 for (size_t i = 0; i < mOutputs.size(); i++) {
639 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
640 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
641 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
642 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
643 }
644 }
645
646 // if entering in call state, handle special case of active streams
647 // pertaining to sonification strategy see handleIncallSonification()
648 if (isStateInCall(state)) {
649 ALOGV("setPhoneState() in call state management: new state is %d", state);
650 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
651 handleIncallSonification((audio_stream_type_t)stream, true, true);
652 }
653
654 // force reevaluating accessibility routing when call starts
655 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
656 }
657
658 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
659 if (state == AUDIO_MODE_RINGTONE &&
660 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
661 mLimitRingtoneVolume = true;
662 } else {
663 mLimitRingtoneVolume = false;
664 }
665 }
666
getPhoneState()667 audio_mode_t AudioPolicyManager::getPhoneState() {
668 return mEngine->getPhoneState();
669 }
670
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)671 void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
672 audio_policy_forced_cfg_t config)
673 {
674 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
675 if (config == mEngine->getForceUse(usage)) {
676 return;
677 }
678
679 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
680 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
681 return;
682 }
683 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
684 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
685 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
686
687 // check for device and output changes triggered by new force usage
688 checkA2dpSuspend();
689 checkOutputForAllStrategies();
690 updateDevicesAndOutputs();
691
692 //FIXME: workaround for truncated touch sounds
693 // to be removed when the problem is handled by system UI
694 uint32_t delayMs = 0;
695 uint32_t waitMs = 0;
696 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
697 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
698 }
699 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
700 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
701 waitMs = updateCallRouting(newDevice, delayMs);
702 }
703 for (size_t i = 0; i < mOutputs.size(); i++) {
704 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
705 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
706 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
707 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
708 delayMs);
709 }
710 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
711 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
712 }
713 }
714
715 for (const auto& activeDesc : mInputs.getActiveInputs()) {
716 audio_devices_t newDevice = getNewInputDevice(activeDesc);
717 // Force new input selection if the new device can not be reached via current input
718 if (activeDesc->mProfile->getSupportedDevices().types() &
719 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
720 setInputDevice(activeDesc->mIoHandle, newDevice);
721 } else {
722 closeInput(activeDesc->mIoHandle);
723 }
724 }
725 }
726
setSystemProperty(const char * property,const char * value)727 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
728 {
729 ALOGV("setSystemProperty() property %s, value %s", property, value);
730 }
731
732 // Find a direct output profile compatible with the parameters passed, even if the input flags do
733 // not explicitly request a direct output
getProfileForDirectOutput(audio_devices_t device,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags)734 sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
735 audio_devices_t device,
736 uint32_t samplingRate,
737 audio_format_t format,
738 audio_channel_mask_t channelMask,
739 audio_output_flags_t flags)
740 {
741 // only retain flags that will drive the direct output profile selection
742 // if explicitly requested
743 static const uint32_t kRelevantFlags =
744 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
745 AUDIO_OUTPUT_FLAG_VOIP_RX);
746 flags =
747 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
748
749 sp<IOProfile> profile;
750
751 for (const auto& hwModule : mHwModules) {
752 for (const auto& curProfile : hwModule->getOutputProfiles()) {
753 if (!curProfile->isCompatibleProfile(device, String8(""),
754 samplingRate, NULL /*updatedSamplingRate*/,
755 format, NULL /*updatedFormat*/,
756 channelMask, NULL /*updatedChannelMask*/,
757 flags)) {
758 continue;
759 }
760 // reject profiles not corresponding to a device currently available
761 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
762 continue;
763 }
764 // if several profiles are compatible, give priority to one with offload capability
765 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
766 continue;
767 }
768 profile = curProfile;
769 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
770 break;
771 }
772 }
773 }
774 return profile;
775 }
776
getOutput(audio_stream_type_t stream)777 audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
778 {
779 routing_strategy strategy = getStrategy(stream);
780 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
781
782 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
783 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
784 // format, flags, etc. This may result in some discrepancy for functions that utilize
785 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
786 // and AudioSystem::getOutputSamplingRate().
787
788 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
789 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
790
791 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
792 return output;
793 }
794
getOutputForAttr(const audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,uid_t uid,const audio_config_t * config,audio_output_flags_t * flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId)795 status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
796 audio_io_handle_t *output,
797 audio_session_t session,
798 audio_stream_type_t *stream,
799 uid_t uid,
800 const audio_config_t *config,
801 audio_output_flags_t *flags,
802 audio_port_handle_t *selectedDeviceId,
803 audio_port_handle_t *portId)
804 {
805 audio_attributes_t attributes;
806 if (attr != NULL) {
807 if (!isValidAttributes(attr)) {
808 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
809 attr->usage, attr->content_type, attr->flags,
810 attr->tags);
811 return BAD_VALUE;
812 }
813 attributes = *attr;
814 } else {
815 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
816 ALOGE("getOutputForAttr(): invalid stream type");
817 return BAD_VALUE;
818 }
819 stream_type_to_audio_attributes(*stream, &attributes);
820 }
821
822 // TODO: check for existing client for this port ID
823 if (*portId == AUDIO_PORT_HANDLE_NONE) {
824 *portId = AudioPort::getNextUniqueId();
825 }
826
827 sp<SwAudioOutputDescriptor> desc;
828 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
829 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
830 if (!audio_has_proportional_frames(config->format)) {
831 return BAD_VALUE;
832 }
833 *stream = streamTypefromAttributesInt(&attributes);
834 *output = desc->mIoHandle;
835 ALOGV("getOutputForAttr() returns output %d", *output);
836 return NO_ERROR;
837 }
838 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
839 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
840 return BAD_VALUE;
841 }
842
843 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
844 " session %d selectedDeviceId %d",
845 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
846 session, *selectedDeviceId);
847
848 *stream = streamTypefromAttributesInt(&attributes);
849
850 // Explicit routing?
851 sp<DeviceDescriptor> deviceDesc;
852 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
853 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
854 }
855 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
856
857 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
858 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
859
860 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
861 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
862 }
863
864 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
865 "flags %#x",
866 device, config->sample_rate, config->format, config->channel_mask, *flags);
867
868 *output = getOutputForDevice(device, session, *stream, config, flags);
869 if (*output == AUDIO_IO_HANDLE_NONE) {
870 mOutputRoutes.removeRoute(session);
871 return INVALID_OPERATION;
872 }
873
874 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
875 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
876 : AUDIO_PORT_HANDLE_NONE;
877
878 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
879
880 return NO_ERROR;
881 }
882
getOutputForDevice(audio_devices_t device,audio_session_t session,audio_stream_type_t stream,const audio_config_t * config,audio_output_flags_t * flags)883 audio_io_handle_t AudioPolicyManager::getOutputForDevice(
884 audio_devices_t device,
885 audio_session_t session,
886 audio_stream_type_t stream,
887 const audio_config_t *config,
888 audio_output_flags_t *flags)
889 {
890 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
891 status_t status;
892
893 // open a direct output if required by specified parameters
894 //force direct flag if offload flag is set: offloading implies a direct output stream
895 // and all common behaviors are driven by checking only the direct flag
896 // this should normally be set appropriately in the policy configuration file
897 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
898 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
899 }
900 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
901 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
902 }
903 // only allow deep buffering for music stream type
904 if (stream != AUDIO_STREAM_MUSIC) {
905 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
906 } else if (/* stream == AUDIO_STREAM_MUSIC && */
907 *flags == AUDIO_OUTPUT_FLAG_NONE &&
908 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
909 // use DEEP_BUFFER as default output for music stream type
910 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
911 }
912 if (stream == AUDIO_STREAM_TTS) {
913 *flags = AUDIO_OUTPUT_FLAG_TTS;
914 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
915 audio_is_linear_pcm(config->format)) {
916 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
917 AUDIO_OUTPUT_FLAG_DIRECT);
918 ALOGV("Set VoIP and Direct output flags for PCM format");
919 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
920 stream == AUDIO_STREAM_MUSIC &&
921 audio_is_linear_pcm(config->format) &&
922 isInCall()) {
923 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
924 }
925
926
927 sp<IOProfile> profile;
928
929 // skip direct output selection if the request can obviously be attached to a mixed output
930 // and not explicitly requested
931 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
932 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
933 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
934 goto non_direct_output;
935 }
936
937 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
938 // This prevents creating an offloaded track and tearing it down immediately after start
939 // when audioflinger detects there is an active non offloadable effect.
940 // FIXME: We should check the audio session here but we do not have it in this context.
941 // This may prevent offloading in rare situations where effects are left active by apps
942 // in the background.
943
944 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
945 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
946 profile = getProfileForDirectOutput(device,
947 config->sample_rate,
948 config->format,
949 config->channel_mask,
950 (audio_output_flags_t)*flags);
951 }
952
953 if (profile != 0) {
954 // exclusive outputs for MMAP and Offload are enforced by different session ids.
955 for (size_t i = 0; i < mOutputs.size(); i++) {
956 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
957 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
958 // reuse direct output if currently open by the same client
959 // and configured with same parameters
960 if ((config->sample_rate == desc->mSamplingRate) &&
961 (config->format == desc->mFormat) &&
962 (config->channel_mask == desc->mChannelMask) &&
963 (session == desc->mDirectClientSession)) {
964 desc->mDirectOpenCount++;
965 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
966 mOutputs.keyAt(i), session);
967 return mOutputs.keyAt(i);
968 }
969 }
970 }
971
972 if (!profile->canOpenNewIo()) {
973 goto non_direct_output;
974 }
975
976 sp<SwAudioOutputDescriptor> outputDesc =
977 new SwAudioOutputDescriptor(profile, mpClientInterface);
978
979 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
980 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
981 : String8("");
982
983 status = outputDesc->open(config, device, address, stream, *flags, &output);
984
985 // only accept an output with the requested parameters
986 if (status != NO_ERROR ||
987 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
988 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
989 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
990 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
991 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
992 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
993 config->channel_mask, outputDesc->mChannelMask);
994 if (output != AUDIO_IO_HANDLE_NONE) {
995 outputDesc->close();
996 }
997 // fall back to mixer output if possible when the direct output could not be open
998 if (audio_is_linear_pcm(config->format) &&
999 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1000 goto non_direct_output;
1001 }
1002 return AUDIO_IO_HANDLE_NONE;
1003 }
1004 outputDesc->mRefCount[stream] = 0;
1005 outputDesc->mStopTime[stream] = 0;
1006 outputDesc->mDirectOpenCount = 1;
1007 outputDesc->mDirectClientSession = session;
1008
1009 addOutput(output, outputDesc);
1010 mPreviousOutputs = mOutputs;
1011 ALOGV("getOutputForDevice() returns new direct output %d", output);
1012 mpClientInterface->onAudioPortListUpdate();
1013 return output;
1014 }
1015
1016 non_direct_output:
1017
1018 // A request for HW A/V sync cannot fallback to a mixed output because time
1019 // stamps are embedded in audio data
1020 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1021 return AUDIO_IO_HANDLE_NONE;
1022 }
1023
1024 // ignoring channel mask due to downmix capability in mixer
1025
1026 // open a non direct output
1027
1028 // for non direct outputs, only PCM is supported
1029 if (audio_is_linear_pcm(config->format)) {
1030 // get which output is suitable for the specified stream. The actual
1031 // routing change will happen when startOutput() will be called
1032 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1033
1034 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1035 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1036 output = selectOutput(outputs, *flags, config->format);
1037 }
1038 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
1039 "sampling rate %d, format %#x, channels %#x, flags %#x",
1040 stream, config->sample_rate, config->format, config->channel_mask, *flags);
1041
1042 return output;
1043 }
1044
selectOutput(const SortedVector<audio_io_handle_t> & outputs,audio_output_flags_t flags,audio_format_t format)1045 audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
1046 audio_output_flags_t flags,
1047 audio_format_t format)
1048 {
1049 // select one output among several that provide a path to a particular device or set of
1050 // devices (the list was previously build by getOutputsForDevice()).
1051 // The priority is as follows:
1052 // 1: the output with the highest number of requested policy flags
1053 // 2: the output with the bit depth the closest to the requested one
1054 // 3: the primary output
1055 // 4: the first output in the list
1056
1057 if (outputs.size() == 0) {
1058 return AUDIO_IO_HANDLE_NONE;
1059 }
1060 if (outputs.size() == 1) {
1061 return outputs[0];
1062 }
1063
1064 int maxCommonFlags = 0;
1065 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1066 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1067 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
1068 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1069 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
1070
1071 for (audio_io_handle_t output : outputs) {
1072 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
1073 if (!outputDesc->isDuplicated()) {
1074 // if a valid format is specified, skip output if not compatible
1075 if (format != AUDIO_FORMAT_INVALID) {
1076 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1077 if (format != outputDesc->mFormat) {
1078 continue;
1079 }
1080 } else if (!audio_is_linear_pcm(format)) {
1081 continue;
1082 }
1083 if (AudioPort::isBetterFormatMatch(
1084 outputDesc->mFormat, bestFormat, format)) {
1085 outputForFormat = output;
1086 bestFormat = outputDesc->mFormat;
1087 }
1088 }
1089
1090 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
1091 if (commonFlags >= maxCommonFlags) {
1092 if (commonFlags == maxCommonFlags) {
1093 if (format != AUDIO_FORMAT_INVALID
1094 && AudioPort::isBetterFormatMatch(
1095 outputDesc->mFormat, bestFormatForFlags, format)) {
1096 outputForFlags = output;
1097 bestFormatForFlags = outputDesc->mFormat;
1098 }
1099 } else {
1100 outputForFlags = output;
1101 maxCommonFlags = commonFlags;
1102 bestFormatForFlags = outputDesc->mFormat;
1103 }
1104 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
1105 }
1106 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
1107 outputForPrimary = output;
1108 }
1109 }
1110 }
1111
1112 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
1113 return outputForFlags;
1114 }
1115 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
1116 return outputForFormat;
1117 }
1118 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
1119 return outputForPrimary;
1120 }
1121
1122 return outputs[0];
1123 }
1124
startOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)1125 status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
1126 audio_stream_type_t stream,
1127 audio_session_t session)
1128 {
1129 ALOGV("startOutput() output %d, stream %d, session %d",
1130 output, stream, session);
1131 ssize_t index = mOutputs.indexOfKey(output);
1132 if (index < 0) {
1133 ALOGW("startOutput() unknown output %d", output);
1134 return BAD_VALUE;
1135 }
1136
1137 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1138
1139 status_t status = outputDesc->start();
1140 if (status != NO_ERROR) {
1141 return status;
1142 }
1143
1144 // Routing?
1145 mOutputRoutes.incRouteActivity(session);
1146
1147 audio_devices_t newDevice;
1148 AudioMix *policyMix = NULL;
1149 const char *address = NULL;
1150 if (outputDesc->mPolicyMix != NULL) {
1151 policyMix = outputDesc->mPolicyMix;
1152 address = policyMix->mDeviceAddress.string();
1153 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1154 newDevice = policyMix->mDeviceType;
1155 } else {
1156 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1157 }
1158 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
1159 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
1160 if (newDevice != outputDesc->device()) {
1161 checkStrategyRoute(getStrategy(stream), output);
1162 }
1163 } else {
1164 newDevice = AUDIO_DEVICE_NONE;
1165 }
1166
1167 uint32_t delayMs = 0;
1168
1169 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
1170
1171 if (status != NO_ERROR) {
1172 mOutputRoutes.decRouteActivity(session);
1173 outputDesc->stop();
1174 return status;
1175 }
1176 // Automatically enable the remote submix input when output is started on a re routing mix
1177 // of type MIX_TYPE_RECORDERS
1178 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1179 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1180 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1181 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1182 address,
1183 "remote-submix");
1184 }
1185
1186 if (delayMs != 0) {
1187 usleep(delayMs * 1000);
1188 }
1189
1190 return status;
1191 }
1192
startSource(const sp<AudioOutputDescriptor> & outputDesc,audio_stream_type_t stream,audio_devices_t device,const char * address,uint32_t * delayMs)1193 status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
1194 audio_stream_type_t stream,
1195 audio_devices_t device,
1196 const char *address,
1197 uint32_t *delayMs)
1198 {
1199 // cannot start playback of STREAM_TTS if any other output is being used
1200 uint32_t beaconMuteLatency = 0;
1201
1202 *delayMs = 0;
1203 if (stream == AUDIO_STREAM_TTS) {
1204 ALOGV("\t found BEACON stream");
1205 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1206 return INVALID_OPERATION;
1207 } else {
1208 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1209 }
1210 } else {
1211 // some playback other than beacon starts
1212 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1213 }
1214
1215 // force device change if the output is inactive and no audio patch is already present.
1216 // check active before incrementing usage count
1217 bool force = !outputDesc->isActive() &&
1218 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
1219
1220 // requiresMuteCheck is false when we can bypass mute strategy.
1221 // It covers a common case when there is no materially active audio
1222 // and muting would result in unnecessary delay and dropped audio.
1223 const uint32_t outputLatencyMs = outputDesc->latency();
1224 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1225
1226 // increment usage count for this stream on the requested output:
1227 // NOTE that the usage count is the same for duplicated output and hardware output which is
1228 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1229 outputDesc->changeRefCount(stream, 1);
1230
1231 if (stream == AUDIO_STREAM_MUSIC) {
1232 selectOutputForMusicEffects();
1233 }
1234
1235 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
1236 // starting an output being rerouted?
1237 if (device == AUDIO_DEVICE_NONE) {
1238 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1239 }
1240
1241 routing_strategy strategy = getStrategy(stream);
1242 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1243 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1244 (beaconMuteLatency > 0);
1245 uint32_t waitMs = beaconMuteLatency;
1246 for (size_t i = 0; i < mOutputs.size(); i++) {
1247 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1248 if (desc != outputDesc) {
1249 // An output has a shared device if
1250 // - managed by the same hw module
1251 // - supports the currently selected device
1252 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1253 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1254
1255 // force a device change if any other output is:
1256 // - managed by the same hw module
1257 // - supports currently selected device
1258 // - has a current device selection that differs from selected device.
1259 // - has an active audio patch
1260 // In this case, the audio HAL must receive the new device selection so that it can
1261 // change the device currently selected by the other output.
1262 if (sharedDevice &&
1263 desc->device() != device &&
1264 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
1265 force = true;
1266 }
1267 // wait for audio on other active outputs to be presented when starting
1268 // a notification so that audio focus effect can propagate, or that a mute/unmute
1269 // event occurred for beacon
1270 const uint32_t latencyMs = desc->latency();
1271 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1272
1273 if (shouldWait && isActive && (waitMs < latencyMs)) {
1274 waitMs = latencyMs;
1275 }
1276
1277 // Require mute check if another output is on a shared device
1278 // and currently active to have proper drain and avoid pops.
1279 // Note restoring AudioTracks onto this output needs to invoke
1280 // a volume ramp if there is no mute.
1281 requiresMuteCheck |= sharedDevice && isActive;
1282 }
1283 }
1284
1285 const uint32_t muteWaitMs =
1286 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
1287
1288 // handle special case for sonification while in call
1289 if (isInCall()) {
1290 handleIncallSonification(stream, true, false);
1291 }
1292
1293 // apply volume rules for current stream and device if necessary
1294 checkAndSetVolume(stream,
1295 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
1296 outputDesc,
1297 outputDesc->device());
1298
1299 // update the outputs if starting an output with a stream that can affect notification
1300 // routing
1301 handleNotificationRoutingForStream(stream);
1302
1303 // force reevaluating accessibility routing when ringtone or alarm starts
1304 if (strategy == STRATEGY_SONIFICATION) {
1305 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1306 }
1307
1308 if (waitMs > muteWaitMs) {
1309 *delayMs = waitMs - muteWaitMs;
1310 }
1311
1312 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1313 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1314 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1315 // change occurs after the MixerThread starts and causes a stream volume
1316 // glitch.
1317 //
1318 // We do not introduce additional delay here.
1319 }
1320
1321 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1322 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1323 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1324 }
1325
1326 return NO_ERROR;
1327 }
1328
1329
stopOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)1330 status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
1331 audio_stream_type_t stream,
1332 audio_session_t session)
1333 {
1334 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1335 ssize_t index = mOutputs.indexOfKey(output);
1336 if (index < 0) {
1337 ALOGW("stopOutput() unknown output %d", output);
1338 return BAD_VALUE;
1339 }
1340
1341 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1342
1343 if (outputDesc->mRefCount[stream] == 1) {
1344 // Automatically disable the remote submix input when output is stopped on a
1345 // re routing mix of type MIX_TYPE_RECORDERS
1346 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1347 outputDesc->mPolicyMix != NULL &&
1348 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1349 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1350 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1351 outputDesc->mPolicyMix->mDeviceAddress,
1352 "remote-submix");
1353 }
1354 }
1355
1356 // Routing?
1357 bool forceDeviceUpdate = false;
1358 if (outputDesc->mRefCount[stream] > 0) {
1359 int activityCount = mOutputRoutes.decRouteActivity(session);
1360 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1361
1362 if (forceDeviceUpdate) {
1363 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1364 }
1365 }
1366
1367 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1368
1369 if (status == NO_ERROR ) {
1370 outputDesc->stop();
1371 }
1372 return status;
1373 }
1374
stopSource(const sp<AudioOutputDescriptor> & outputDesc,audio_stream_type_t stream,bool forceDeviceUpdate)1375 status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
1376 audio_stream_type_t stream,
1377 bool forceDeviceUpdate)
1378 {
1379 // always handle stream stop, check which stream type is stopping
1380 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1381
1382 // handle special case for sonification while in call
1383 if (isInCall()) {
1384 handleIncallSonification(stream, false, false);
1385 }
1386
1387 if (outputDesc->mRefCount[stream] > 0) {
1388 // decrement usage count of this stream on the output
1389 outputDesc->changeRefCount(stream, -1);
1390
1391 // store time at which the stream was stopped - see isStreamActive()
1392 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
1393 outputDesc->mStopTime[stream] = systemTime();
1394 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
1395 // delay the device switch by twice the latency because stopOutput() is executed when
1396 // the track stop() command is received and at that time the audio track buffer can
1397 // still contain data that needs to be drained. The latency only covers the audio HAL
1398 // and kernel buffers. Also the latency does not always include additional delay in the
1399 // audio path (audio DSP, CODEC ...)
1400 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
1401
1402 // force restoring the device selection on other active outputs if it differs from the
1403 // one being selected for this output
1404 uint32_t delayMs = outputDesc->latency()*2;
1405 for (size_t i = 0; i < mOutputs.size(); i++) {
1406 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1407 if (desc != outputDesc &&
1408 desc->isActive() &&
1409 outputDesc->sharesHwModuleWith(desc) &&
1410 (newDevice != desc->device())) {
1411 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1412 bool force = desc->device() != newDevice2;
1413
1414 setOutputDevice(desc,
1415 newDevice2,
1416 force,
1417 delayMs);
1418 // re-apply device specific volume if not done by setOutputDevice()
1419 if (!force) {
1420 applyStreamVolumes(desc, newDevice2, delayMs);
1421 }
1422 }
1423 }
1424 // update the outputs if stopping one with a stream that can affect notification routing
1425 handleNotificationRoutingForStream(stream);
1426 }
1427
1428 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1429 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1430 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1431 }
1432
1433 if (stream == AUDIO_STREAM_MUSIC) {
1434 selectOutputForMusicEffects();
1435 }
1436 return NO_ERROR;
1437 } else {
1438 ALOGW("stopOutput() refcount is already 0");
1439 return INVALID_OPERATION;
1440 }
1441 }
1442
releaseOutput(audio_io_handle_t output,audio_stream_type_t stream __unused,audio_session_t session __unused)1443 void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
1444 audio_stream_type_t stream __unused,
1445 audio_session_t session __unused)
1446 {
1447 ALOGV("releaseOutput() %d", output);
1448 ssize_t index = mOutputs.indexOfKey(output);
1449 if (index < 0) {
1450 ALOGW("releaseOutput() releasing unknown output %d", output);
1451 return;
1452 }
1453
1454 // Routing
1455 mOutputRoutes.removeRoute(session);
1456
1457 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
1458 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1459 if (desc->mDirectOpenCount <= 0) {
1460 ALOGW("releaseOutput() invalid open count %d for output %d",
1461 desc->mDirectOpenCount, output);
1462 return;
1463 }
1464 if (--desc->mDirectOpenCount == 0) {
1465 closeOutput(output);
1466 mpClientInterface->onAudioPortListUpdate();
1467 }
1468 }
1469 }
1470
1471
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_session_t session,uid_t uid,const audio_config_base_t * config,audio_input_flags_t flags,audio_port_handle_t * selectedDeviceId,input_type_t * inputType,audio_port_handle_t * portId)1472 status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1473 audio_io_handle_t *input,
1474 audio_session_t session,
1475 uid_t uid,
1476 const audio_config_base_t *config,
1477 audio_input_flags_t flags,
1478 audio_port_handle_t *selectedDeviceId,
1479 input_type_t *inputType,
1480 audio_port_handle_t *portId)
1481 {
1482 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
1483 "session %d, flags %#x",
1484 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
1485
1486 status_t status = NO_ERROR;
1487 // handle legacy remote submix case where the address was not always specified
1488 String8 address = String8("");
1489 audio_source_t halInputSource;
1490 audio_source_t inputSource = attr->source;
1491 AudioMix *policyMix = NULL;
1492 DeviceVector inputDevices;
1493
1494 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1495 inputSource = AUDIO_SOURCE_MIC;
1496 }
1497
1498 // Explicit routing?
1499 sp<DeviceDescriptor> deviceDesc;
1500 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1501 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
1502 }
1503 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
1504
1505 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1506 // possible
1507 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1508 *input != AUDIO_IO_HANDLE_NONE) {
1509 ssize_t index = mInputs.indexOfKey(*input);
1510 if (index < 0) {
1511 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1512 status = BAD_VALUE;
1513 goto error;
1514 }
1515 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1516 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1517 if (audioSession == 0) {
1518 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1519 status = BAD_VALUE;
1520 goto error;
1521 }
1522 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1523 // The second call is for the first active client and sets the UID. Any further call
1524 // corresponds to a new client and is only permitted from the same UID.
1525 // If the first UID is silenced, allow a new UID connection and replace with new UID
1526 if (audioSession->openCount() == 1) {
1527 audioSession->setUid(uid);
1528 } else if (audioSession->uid() != uid) {
1529 if (!audioSession->isSilenced()) {
1530 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1531 uid, session, audioSession->uid());
1532 status = INVALID_OPERATION;
1533 goto error;
1534 }
1535 audioSession->setUid(uid);
1536 audioSession->setSilenced(false);
1537 }
1538 audioSession->changeOpenCount(1);
1539 *inputType = API_INPUT_LEGACY;
1540 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1541 *portId = AudioPort::getNextUniqueId();
1542 }
1543 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1544 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1545 : AUDIO_PORT_HANDLE_NONE;
1546 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1547
1548 return NO_ERROR;
1549 }
1550
1551 *input = AUDIO_IO_HANDLE_NONE;
1552 *inputType = API_INPUT_INVALID;
1553
1554 halInputSource = inputSource;
1555
1556 // TODO: check for existing client for this port ID
1557 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1558 *portId = AudioPort::getNextUniqueId();
1559 }
1560
1561 audio_devices_t device;
1562
1563 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
1564 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1565 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1566 if (status != NO_ERROR) {
1567 goto error;
1568 }
1569 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1570 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1571 address = String8(attr->tags + strlen("addr="));
1572 } else {
1573 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1574 if (device == AUDIO_DEVICE_NONE) {
1575 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
1576 status = BAD_VALUE;
1577 goto error;
1578 }
1579 if (policyMix != NULL) {
1580 address = policyMix->mDeviceAddress;
1581 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1582 // there is an external policy, but this input is attached to a mix of recorders,
1583 // meaning it receives audio injected into the framework, so the recorder doesn't
1584 // know about it and is therefore considered "legacy"
1585 *inputType = API_INPUT_LEGACY;
1586 } else {
1587 // recording a mix of players defined by an external policy, we're rerouting for
1588 // an external policy
1589 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1590 }
1591 } else if (audio_is_remote_submix_device(device)) {
1592 address = String8("0");
1593 *inputType = API_INPUT_MIX_CAPTURE;
1594 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1595 *inputType = API_INPUT_TELEPHONY_RX;
1596 } else {
1597 *inputType = API_INPUT_LEGACY;
1598 }
1599
1600 }
1601
1602 *input = getInputForDevice(device, address, session, uid, inputSource,
1603 config, flags,
1604 policyMix);
1605 if (*input == AUDIO_IO_HANDLE_NONE) {
1606 status = INVALID_OPERATION;
1607 goto error;
1608 }
1609
1610 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1611 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1612 : AUDIO_PORT_HANDLE_NONE;
1613
1614 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1615 *input, *inputType, *selectedDeviceId);
1616
1617 return NO_ERROR;
1618
1619 error:
1620 mInputRoutes.removeRoute(session);
1621 return status;
1622 }
1623
1624
getInputForDevice(audio_devices_t device,String8 address,audio_session_t session,uid_t uid,audio_source_t inputSource,const audio_config_base_t * config,audio_input_flags_t flags,AudioMix * policyMix)1625 audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1626 String8 address,
1627 audio_session_t session,
1628 uid_t uid,
1629 audio_source_t inputSource,
1630 const audio_config_base_t *config,
1631 audio_input_flags_t flags,
1632 AudioMix *policyMix)
1633 {
1634 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1635 audio_source_t halInputSource = inputSource;
1636 bool isSoundTrigger = false;
1637
1638 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1639 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1640 if (index >= 0) {
1641 input = mSoundTriggerSessions.valueFor(session);
1642 isSoundTrigger = true;
1643 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1644 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1645 } else {
1646 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1647 }
1648 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
1649 audio_is_linear_pcm(config->format)) {
1650 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
1651 }
1652
1653 // find a compatible input profile (not necessarily identical in parameters)
1654 sp<IOProfile> profile;
1655 // sampling rate and flags may be updated by getInputProfile
1656 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1657 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
1658 audio_format_t profileFormat;
1659 audio_channel_mask_t profileChannelMask = config->channel_mask;
1660 audio_input_flags_t profileFlags = flags;
1661 for (;;) {
1662 profileFormat = config->format; // reset each time through loop, in case it is updated
1663 profile = getInputProfile(device, address,
1664 profileSamplingRate, profileFormat, profileChannelMask,
1665 profileFlags);
1666 if (profile != 0) {
1667 break; // success
1668 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1669 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
1670 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1671 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1672 } else { // fail
1673 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
1674 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1675 device, config->sample_rate, config->format, config->channel_mask, flags);
1676 return input;
1677 }
1678 }
1679 // Pick input sampling rate if not specified by client
1680 uint32_t samplingRate = config->sample_rate;
1681 if (samplingRate == 0) {
1682 samplingRate = profileSamplingRate;
1683 }
1684
1685 if (profile->getModuleHandle() == 0) {
1686 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
1687 return input;
1688 }
1689
1690 sp<AudioSession> audioSession = new AudioSession(session,
1691 inputSource,
1692 config->format,
1693 samplingRate,
1694 config->channel_mask,
1695 flags,
1696 uid,
1697 isSoundTrigger,
1698 policyMix, mpClientInterface);
1699
1700 // FIXME: disable concurrent capture until UI is ready
1701 #if 0
1702 // reuse an open input if possible
1703 sp<AudioInputDescriptor> reusedInputDesc;
1704 for (size_t i = 0; i < mInputs.size(); i++) {
1705 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
1706 // reuse input if:
1707 // - it shares the same profile
1708 // AND
1709 // - it is not a reroute submix input
1710 // AND
1711 // - it is: not used for sound trigger
1712 // OR
1713 // used for sound trigger and all clients use the same session ID
1714 //
1715 if ((profile == desc->mProfile) &&
1716 (isSoundTrigger == desc->isSoundTrigger()) &&
1717 !is_virtual_input_device(device)) {
1718
1719 sp<AudioSession> as = desc->getAudioSession(session);
1720 if (as != 0) {
1721 // do not allow unmatching properties on same session
1722 if (as->matches(audioSession)) {
1723 as->changeOpenCount(1);
1724 } else {
1725 ALOGW("getInputForDevice() record with different attributes"
1726 " exists for session %d", session);
1727 continue;
1728 }
1729 } else if (isSoundTrigger) {
1730 continue;
1731 }
1732
1733 // Reuse the already opened input stream on this profile if:
1734 // - the new capture source is background OR
1735 // - the path requested configurations match OR
1736 // - the new source priority is less than the highest source priority on this input
1737 // If the input stream cannot be reused, close it before opening a new stream
1738 // on the same profile for the new client so that the requested path configuration
1739 // can be selected.
1740 if (!isConcurrentSource(inputSource) &&
1741 ((desc->mSamplingRate != samplingRate ||
1742 desc->mChannelMask != config->channel_mask ||
1743 !audio_formats_match(desc->mFormat, config->format)) &&
1744 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1745 source_priority(inputSource)))) {
1746 reusedInputDesc = desc;
1747 continue;
1748 } else {
1749 desc->addAudioSession(session, audioSession);
1750 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1751 return mInputs.keyAt(i);
1752 }
1753 }
1754 }
1755
1756 if (reusedInputDesc != 0) {
1757 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1758 for (size_t j = 0; j < sessions.size(); j++) {
1759 audio_session_t currentSession = sessions.keyAt(j);
1760 stopInput(reusedInputDesc->mIoHandle, currentSession);
1761 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1762 }
1763 }
1764 #endif
1765
1766 if (!profile->canOpenNewIo()) {
1767 return AUDIO_IO_HANDLE_NONE;
1768 }
1769
1770 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
1771
1772 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1773 lConfig.sample_rate = profileSamplingRate;
1774 lConfig.channel_mask = profileChannelMask;
1775 lConfig.format = profileFormat;
1776
1777 if (address == "") {
1778 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1779 // the inputs vector must be of size >= 1, but we don't want to crash here
1780 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1781 }
1782
1783 status_t status = inputDesc->open(&lConfig, device, address,
1784 halInputSource, profileFlags, &input);
1785
1786 // only accept input with the exact requested set of parameters
1787 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
1788 (profileSamplingRate != lConfig.sample_rate) ||
1789 !audio_formats_match(profileFormat, lConfig.format) ||
1790 (profileChannelMask != lConfig.channel_mask)) {
1791 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
1792 ", format %#x, channel mask %#x",
1793 profileSamplingRate, profileFormat, profileChannelMask);
1794 if (input != AUDIO_IO_HANDLE_NONE) {
1795 inputDesc->close();
1796 }
1797 return AUDIO_IO_HANDLE_NONE;
1798 }
1799
1800 inputDesc->mPolicyMix = policyMix;
1801 inputDesc->addAudioSession(session, audioSession);
1802
1803 addInput(input, inputDesc);
1804 mpClientInterface->onAudioPortListUpdate();
1805
1806 return input;
1807 }
1808
1809 //static
isConcurrentSource(audio_source_t source)1810 bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1811 {
1812 return (source == AUDIO_SOURCE_HOTWORD) ||
1813 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1814 (source == AUDIO_SOURCE_FM_TUNER);
1815 }
1816
isConcurentCaptureAllowed(const sp<AudioInputDescriptor> & inputDesc,const sp<AudioSession> & audioSession)1817 bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1818 const sp<AudioSession>& audioSession)
1819 {
1820 // Do not allow capture if an active voice call is using a software patch and
1821 // the call TX source device is on the same HW module.
1822 // FIXME: would be better to refine to only inputs whose profile connects to the
1823 // call TX device but this information is not in the audio patch
1824 if (mCallTxPatch != 0 &&
1825 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1826 return false;
1827 }
1828
1829 // starting concurrent capture is enabled if:
1830 // 1) capturing for re-routing
1831 // 2) capturing for HOTWORD source
1832 // 3) capturing for FM TUNER source
1833 // 3) All other active captures are either for re-routing or HOTWORD
1834
1835 if (is_virtual_input_device(inputDesc->mDevice) ||
1836 isConcurrentSource(audioSession->inputSource())) {
1837 return true;
1838 }
1839
1840 for (const auto& activeInput : mInputs.getActiveInputs()) {
1841 if (!isConcurrentSource(activeInput->inputSource(true)) &&
1842 !is_virtual_input_device(activeInput->mDevice)) {
1843 return false;
1844 }
1845 }
1846
1847 return true;
1848 }
1849
1850 // FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
soundTriggerSupportsConcurrentCapture()1851 bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1852 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1853 bool soundTriggerSupportsConcurrentCapture = false;
1854 unsigned int numModules = 0;
1855 struct sound_trigger_module_descriptor* nModules = NULL;
1856
1857 status_t status = SoundTrigger::listModules(nModules, &numModules);
1858 if (status == NO_ERROR && numModules != 0) {
1859 nModules = (struct sound_trigger_module_descriptor*) calloc(
1860 numModules, sizeof(struct sound_trigger_module_descriptor));
1861 if (nModules == NULL) {
1862 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1863 // ram the next time this function is called.
1864 ALOGE("Failed to allocate buffer for module descriptors");
1865 return false;
1866 }
1867
1868 status = SoundTrigger::listModules(nModules, &numModules);
1869 if (status == NO_ERROR) {
1870 soundTriggerSupportsConcurrentCapture = true;
1871 for (size_t i = 0; i < numModules; ++i) {
1872 soundTriggerSupportsConcurrentCapture &=
1873 nModules[i].properties.concurrent_capture;
1874 }
1875 }
1876 free(nModules);
1877 }
1878 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1879 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1880 }
1881 return mSoundTriggerSupportsConcurrentCapture;
1882 }
1883
1884
startInput(audio_io_handle_t input,audio_session_t session,bool silenced,concurrency_type__mask_t * concurrency)1885 status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1886 audio_session_t session,
1887 bool silenced,
1888 concurrency_type__mask_t *concurrency)
1889 {
1890
1891 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1892 input, session, silenced, *concurrency);
1893
1894 *concurrency = API_INPUT_CONCURRENCY_NONE;
1895
1896 ssize_t index = mInputs.indexOfKey(input);
1897 if (index < 0) {
1898 ALOGW("startInput() unknown input %d", input);
1899 return BAD_VALUE;
1900 }
1901 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1902
1903 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1904 if (audioSession == 0) {
1905 ALOGW("startInput() unknown session %d on input %d", session, input);
1906 return BAD_VALUE;
1907 }
1908
1909 // FIXME: disable concurrent capture until UI is ready
1910 #if 0
1911 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1912 ALOGW("startInput(%d) failed: other input already started", input);
1913 return INVALID_OPERATION;
1914 }
1915
1916 if (isInCall()) {
1917 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1918 }
1919 if (mInputs.activeInputsCountOnDevices() != 0) {
1920 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
1921 }
1922 #else
1923 if (!is_virtual_input_device(inputDesc->mDevice)) {
1924 if (mCallTxPatch != 0 &&
1925 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1926 ALOGW("startInput(%d) failed: call in progress", input);
1927 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1928 return INVALID_OPERATION;
1929 }
1930
1931 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
1932
1933 // If a UID is idle and records silence and another not silenced recording starts
1934 // from another UID (idle or active) we stop the current idle UID recording in
1935 // favor of the new one - "There can be only one" TM
1936 if (!silenced) {
1937 for (const auto& activeDesc : activeInputs) {
1938 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1939 activeDesc->getId() == inputDesc->getId()) {
1940 continue;
1941 }
1942
1943 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1944 true /*activeOnly*/);
1945 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1946 if (activeSession->isSilenced()) {
1947 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1948 audio_session_t activeSessionId = activeSession->session();
1949 stopInput(activeInput, activeSessionId);
1950 releaseInput(activeInput, activeSessionId);
1951 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1952 activeInputs = mInputs.getActiveInputs();
1953 }
1954 }
1955 }
1956
1957 for (const auto& activeDesc : activeInputs) {
1958 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1959 activeDesc->getId() == inputDesc->getId()) {
1960 continue;
1961 }
1962
1963 audio_source_t activeSource = activeDesc->inputSource(true);
1964 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1965 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1966 if (activeDesc->hasPreemptedSession(session)) {
1967 ALOGW("startInput(%d) failed for HOTWORD: "
1968 "other input %d already started for HOTWORD",
1969 input, activeDesc->mIoHandle);
1970 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
1971 return INVALID_OPERATION;
1972 }
1973 } else {
1974 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1975 input, activeDesc->mIoHandle);
1976 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
1977 return INVALID_OPERATION;
1978 }
1979 } else {
1980 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1981 ALOGW("startInput(%d) failed: other input %d already started",
1982 input, activeDesc->mIoHandle);
1983 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
1984 return INVALID_OPERATION;
1985 }
1986 }
1987 }
1988
1989 // We only need to check if the sound trigger session supports concurrent capture if the
1990 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1991 // that's running.
1992 const bool allowConcurrentWithSoundTrigger =
1993 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1994
1995 // if capture is allowed, preempt currently active HOTWORD captures
1996 for (const auto& activeDesc : activeInputs) {
1997 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1998 continue;
1999 }
2000
2001 audio_source_t activeSource = activeDesc->inputSource(true);
2002 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2003 AudioSessionCollection activeSessions =
2004 activeDesc->getAudioSessions(true /*activeOnly*/);
2005 audio_session_t activeSession = activeSessions.keyAt(0);
2006 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2007 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2008 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2009 sessions.add(activeSession);
2010 inputDesc->setPreemptedSessions(sessions);
2011 stopInput(activeHandle, activeSession);
2012 releaseInput(activeHandle, activeSession);
2013 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2014 input, activeDesc->mIoHandle);
2015 }
2016 }
2017 }
2018 #endif
2019
2020 // Make sure we start with the correct silence state
2021 audioSession->setSilenced(silenced);
2022
2023 // increment activity count before calling getNewInputDevice() below as only active sessions
2024 // are considered for device selection
2025 audioSession->changeActiveCount(1);
2026
2027 // Routing?
2028 mInputRoutes.incRouteActivity(session);
2029
2030 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
2031 // indicate active capture to sound trigger service if starting capture from a mic on
2032 // primary HW module
2033 audio_devices_t device = getNewInputDevice(inputDesc);
2034 setInputDevice(input, device, true /* force */);
2035
2036 status_t status = inputDesc->start();
2037 if (status != NO_ERROR) {
2038 mInputRoutes.decRouteActivity(session);
2039 audioSession->changeActiveCount(-1);
2040 return status;
2041 }
2042
2043 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2044 // if input maps to a dynamic policy with an activity listener, notify of state change
2045 if ((inputDesc->mPolicyMix != NULL)
2046 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2047 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2048 MIX_STATE_MIXING);
2049 }
2050
2051 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2052 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2053 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2054 SoundTrigger::setCaptureState(true);
2055 }
2056
2057 // automatically enable the remote submix output when input is started if not
2058 // used by a policy mix of type MIX_TYPE_RECORDERS
2059 // For remote submix (a virtual device), we open only one input per capture request.
2060 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2061 String8 address = String8("");
2062 if (inputDesc->mPolicyMix == NULL) {
2063 address = String8("0");
2064 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2065 address = inputDesc->mPolicyMix->mDeviceAddress;
2066 }
2067 if (address != "") {
2068 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2069 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2070 address, "remote-submix");
2071 }
2072 }
2073 }
2074 }
2075
2076 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
2077
2078 return NO_ERROR;
2079 }
2080
stopInput(audio_io_handle_t input,audio_session_t session)2081 status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2082 audio_session_t session)
2083 {
2084 ALOGV("stopInput() input %d", input);
2085 ssize_t index = mInputs.indexOfKey(input);
2086 if (index < 0) {
2087 ALOGW("stopInput() unknown input %d", input);
2088 return BAD_VALUE;
2089 }
2090 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2091
2092 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2093 if (index < 0) {
2094 ALOGW("stopInput() unknown session %d on input %d", session, input);
2095 return BAD_VALUE;
2096 }
2097
2098 if (audioSession->activeCount() == 0) {
2099 ALOGW("stopInput() input %d already stopped", input);
2100 return INVALID_OPERATION;
2101 }
2102
2103 audioSession->changeActiveCount(-1);
2104
2105 // Routing?
2106 mInputRoutes.decRouteActivity(session);
2107
2108 if (audioSession->activeCount() == 0) {
2109 inputDesc->stop();
2110 if (inputDesc->isActive()) {
2111 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2112 } else {
2113 // if input maps to a dynamic policy with an activity listener, notify of state change
2114 if ((inputDesc->mPolicyMix != NULL)
2115 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2116 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2117 MIX_STATE_IDLE);
2118 }
2119
2120 // automatically disable the remote submix output when input is stopped if not
2121 // used by a policy mix of type MIX_TYPE_RECORDERS
2122 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2123 String8 address = String8("");
2124 if (inputDesc->mPolicyMix == NULL) {
2125 address = String8("0");
2126 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2127 address = inputDesc->mPolicyMix->mDeviceAddress;
2128 }
2129 if (address != "") {
2130 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2131 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2132 address, "remote-submix");
2133 }
2134 }
2135
2136 audio_devices_t device = inputDesc->mDevice;
2137 resetInputDevice(input);
2138
2139 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2140 // primary HW module
2141 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2142 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2143 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2144 SoundTrigger::setCaptureState(false);
2145 }
2146 inputDesc->clearPreemptedSessions();
2147 }
2148 }
2149 return NO_ERROR;
2150 }
2151
releaseInput(audio_io_handle_t input,audio_session_t session)2152 void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2153 audio_session_t session)
2154 {
2155 ALOGV("releaseInput() %d", input);
2156 ssize_t index = mInputs.indexOfKey(input);
2157 if (index < 0) {
2158 ALOGW("releaseInput() releasing unknown input %d", input);
2159 return;
2160 }
2161
2162 // Routing
2163 mInputRoutes.removeRoute(session);
2164
2165 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2166 ALOG_ASSERT(inputDesc != 0);
2167
2168 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2169 if (audioSession == 0) {
2170 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2171 return;
2172 }
2173
2174 if (audioSession->openCount() == 0) {
2175 ALOGW("releaseInput() invalid open count %d on session %d",
2176 audioSession->openCount(), session);
2177 return;
2178 }
2179
2180 if (audioSession->changeOpenCount(-1) == 0) {
2181 inputDesc->removeAudioSession(session);
2182 }
2183
2184 if (inputDesc->getOpenRefCount() > 0) {
2185 ALOGV("releaseInput() exit > 0");
2186 return;
2187 }
2188
2189 closeInput(input);
2190 mpClientInterface->onAudioPortListUpdate();
2191 ALOGV("releaseInput() exit");
2192 }
2193
closeAllInputs()2194 void AudioPolicyManager::closeAllInputs() {
2195 bool patchRemoved = false;
2196
2197 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2198 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
2199 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
2200 if (patch_index >= 0) {
2201 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
2202 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2203 mAudioPatches.removeItemsAt(patch_index);
2204 patchRemoved = true;
2205 }
2206 inputDesc->close();
2207 }
2208 mInputRoutes.clear();
2209 mInputs.clear();
2210 SoundTrigger::setCaptureState(false);
2211 nextAudioPortGeneration();
2212
2213 if (patchRemoved) {
2214 mpClientInterface->onAudioPatchListUpdate();
2215 }
2216 }
2217
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)2218 void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
2219 int indexMin,
2220 int indexMax)
2221 {
2222 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
2223 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
2224
2225 // initialize other private stream volumes which follow this one
2226 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2227 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2228 continue;
2229 }
2230 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
2231 }
2232 }
2233
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)2234 status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
2235 int index,
2236 audio_devices_t device)
2237 {
2238
2239 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2240 // app that has MODIFY_PHONE_STATE permission.
2241 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2242 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
2243 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
2244 return BAD_VALUE;
2245 }
2246 if (!audio_is_output_device(device)) {
2247 return BAD_VALUE;
2248 }
2249
2250 // Force max volume if stream cannot be muted
2251 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
2252
2253 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
2254 stream, device, index);
2255
2256 // update other private stream volumes which follow this one
2257 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2258 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2259 continue;
2260 }
2261 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2262 }
2263
2264 // update volume on all outputs and streams matching the following:
2265 // - The requested stream (or a stream matching for volume control) is active on the output
2266 // - The device (or devices) selected by the strategy corresponding to this stream includes
2267 // the requested device
2268 // - For non default requested device, currently selected device on the output is either the
2269 // requested device or one of the devices selected by the strategy
2270 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2271 // no specific device volume value exists for currently selected device.
2272 status_t status = NO_ERROR;
2273 for (size_t i = 0; i < mOutputs.size(); i++) {
2274 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2275 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
2276 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2277 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2278 continue;
2279 }
2280 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2281 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
2282 continue;
2283 }
2284 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
2285 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2286 curStrategy, false /*fromCache*/));
2287 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2288 ((curStreamDevice & device) == 0)) {
2289 continue;
2290 }
2291 bool applyVolume;
2292 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2293 curStreamDevice |= device;
2294 applyVolume = (curDevice & curStreamDevice) != 0;
2295 } else {
2296 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
2297 stream, curStreamDevice);
2298 }
2299
2300 if (applyVolume) {
2301 //FIXME: workaround for truncated touch sounds
2302 // delayed volume change for system stream to be removed when the problem is
2303 // handled by system UI
2304 status_t volStatus =
2305 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2306 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
2307 if (volStatus != NO_ERROR) {
2308 status = volStatus;
2309 }
2310 }
2311 }
2312 }
2313 return status;
2314 }
2315
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)2316 status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
2317 int *index,
2318 audio_devices_t device)
2319 {
2320 if (index == NULL) {
2321 return BAD_VALUE;
2322 }
2323 if (!audio_is_output_device(device)) {
2324 return BAD_VALUE;
2325 }
2326 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
2327 // the strategy the stream belongs to.
2328 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2329 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2330 }
2331 device = Volume::getDeviceForVolume(device);
2332
2333 *index = mVolumeCurves->getVolumeIndex(stream, device);
2334 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2335 return NO_ERROR;
2336 }
2337
selectOutputForMusicEffects()2338 audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
2339 {
2340 // select one output among several suitable for global effects.
2341 // The priority is as follows:
2342 // 1: An offloaded output. If the effect ends up not being offloadable,
2343 // AudioFlinger will invalidate the track and the offloaded output
2344 // will be closed causing the effect to be moved to a PCM output.
2345 // 2: A deep buffer output
2346 // 3: The primary output
2347 // 4: the first output in the list
2348
2349 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
2350 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2351 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2352
2353 if (outputs.size() == 0) {
2354 return AUDIO_IO_HANDLE_NONE;
2355 }
2356
2357 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2358 bool activeOnly = true;
2359
2360 while (output == AUDIO_IO_HANDLE_NONE) {
2361 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2362 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2363 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2364
2365 for (audio_io_handle_t output : outputs) {
2366 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
2367 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2368 continue;
2369 }
2370 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2371 activeOnly, output, desc->mFlags);
2372 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2373 outputOffloaded = output;
2374 }
2375 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2376 outputDeepBuffer = output;
2377 }
2378 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2379 outputPrimary = output;
2380 }
2381 }
2382 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2383 output = outputOffloaded;
2384 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2385 output = outputDeepBuffer;
2386 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2387 output = outputPrimary;
2388 } else {
2389 output = outputs[0];
2390 }
2391 activeOnly = false;
2392 }
2393
2394 if (output != mMusicEffectOutput) {
2395 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2396 mMusicEffectOutput = output;
2397 }
2398
2399 ALOGV("selectOutputForMusicEffects selected output %d", output);
2400 return output;
2401 }
2402
getOutputForEffect(const effect_descriptor_t * desc __unused)2403 audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2404 {
2405 return selectOutputForMusicEffects();
2406 }
2407
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,uint32_t strategy,int session,int id)2408 status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
2409 audio_io_handle_t io,
2410 uint32_t strategy,
2411 int session,
2412 int id)
2413 {
2414 ssize_t index = mOutputs.indexOfKey(io);
2415 if (index < 0) {
2416 index = mInputs.indexOfKey(io);
2417 if (index < 0) {
2418 ALOGW("registerEffect() unknown io %d", io);
2419 return INVALID_OPERATION;
2420 }
2421 }
2422 return mEffects.registerEffect(desc, io, strategy, session, id);
2423 }
2424
isStreamActive(audio_stream_type_t stream,uint32_t inPastMs) const2425 bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2426 {
2427 bool active = false;
2428 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2429 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2430 continue;
2431 }
2432 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2433 }
2434 return active;
2435 }
2436
isStreamActiveRemotely(audio_stream_type_t stream,uint32_t inPastMs) const2437 bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2438 {
2439 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2440 }
2441
isSourceActive(audio_source_t source) const2442 bool AudioPolicyManager::isSourceActive(audio_source_t source) const
2443 {
2444 for (size_t i = 0; i < mInputs.size(); i++) {
2445 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
2446 if (inputDescriptor->isSourceActive(source)) {
2447 return true;
2448 }
2449 }
2450 return false;
2451 }
2452
2453 // Register a list of custom mixes with their attributes and format.
2454 // When a mix is registered, corresponding input and output profiles are
2455 // added to the remote submix hw module. The profile contains only the
2456 // parameters (sampling rate, format...) specified by the mix.
2457 // The corresponding input remote submix device is also connected.
2458 //
2459 // When a remote submix device is connected, the address is checked to select the
2460 // appropriate profile and the corresponding input or output stream is opened.
2461 //
2462 // When capture starts, getInputForAttr() will:
2463 // - 1 look for a mix matching the address passed in attribtutes tags if any
2464 // - 2 if none found, getDeviceForInputSource() will:
2465 // - 2.1 look for a mix matching the attributes source
2466 // - 2.2 if none found, default to device selection by policy rules
2467 // At this time, the corresponding output remote submix device is also connected
2468 // and active playback use cases can be transferred to this mix if needed when reconnecting
2469 // after AudioTracks are invalidated
2470 //
2471 // When playback starts, getOutputForAttr() will:
2472 // - 1 look for a mix matching the address passed in attribtutes tags if any
2473 // - 2 if none found, look for a mix matching the attributes usage
2474 // - 3 if none found, default to device and output selection by policy rules.
2475
registerPolicyMixes(const Vector<AudioMix> & mixes)2476 status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
2477 {
2478 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2479 status_t res = NO_ERROR;
2480
2481 sp<HwModule> rSubmixModule;
2482 // examine each mix's route type
2483 for (size_t i = 0; i < mixes.size(); i++) {
2484 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2485 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2486 res = INVALID_OPERATION;
2487 break;
2488 }
2489 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2490 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
2491 if (rSubmixModule == 0) {
2492 rSubmixModule = mHwModules.getModuleFromName(
2493 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2494 if (rSubmixModule == 0) {
2495 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2496 i);
2497 res = INVALID_OPERATION;
2498 break;
2499 }
2500 }
2501
2502 String8 address = mixes[i].mDeviceAddress;
2503
2504 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
2505 ALOGE(" Error registering mix %zu for address %s", i, address.string());
2506 res = INVALID_OPERATION;
2507 break;
2508 }
2509 audio_config_t outputConfig = mixes[i].mFormat;
2510 audio_config_t inputConfig = mixes[i].mFormat;
2511 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2512 // stereo and let audio flinger do the channel conversion if needed.
2513 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2514 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2515 rSubmixModule->addOutputProfile(address, &outputConfig,
2516 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2517 rSubmixModule->addInputProfile(address, &inputConfig,
2518 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2519
2520 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2521 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2522 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2523 address.string(), "remote-submix");
2524 } else {
2525 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2526 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2527 address.string(), "remote-submix");
2528 }
2529 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2530 String8 address = mixes[i].mDeviceAddress;
2531 audio_devices_t device = mixes[i].mDeviceType;
2532 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2533 i, mixes.size(), device, address.string());
2534
2535 bool foundOutput = false;
2536 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2537 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2538 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2539 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2540 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2541 && (patch->mPatch.sinks[0].ext.device.type == device)
2542 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2543 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
2544 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2545 res = INVALID_OPERATION;
2546 } else {
2547 foundOutput = true;
2548 }
2549 break;
2550 }
2551 }
2552
2553 if (res != NO_ERROR) {
2554 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
2555 i, device, address.string());
2556 res = INVALID_OPERATION;
2557 break;
2558 } else if (!foundOutput) {
2559 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2560 i, device, address.string());
2561 res = INVALID_OPERATION;
2562 break;
2563 }
2564 }
2565 }
2566 if (res != NO_ERROR) {
2567 unregisterPolicyMixes(mixes);
2568 }
2569 return res;
2570 }
2571
unregisterPolicyMixes(Vector<AudioMix> mixes)2572 status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2573 {
2574 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
2575 status_t res = NO_ERROR;
2576 sp<HwModule> rSubmixModule;
2577 // examine each mix's route type
2578 for (const auto& mix : mixes) {
2579 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2580
2581 if (rSubmixModule == 0) {
2582 rSubmixModule = mHwModules.getModuleFromName(
2583 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2584 if (rSubmixModule == 0) {
2585 res = INVALID_OPERATION;
2586 continue;
2587 }
2588 }
2589
2590 String8 address = mix.mDeviceAddress;
2591
2592 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2593 res = INVALID_OPERATION;
2594 continue;
2595 }
2596
2597 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2598 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2599 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2600 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2601 address.string(), "remote-submix");
2602 }
2603 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2604 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2605 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2606 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2607 address.string(), "remote-submix");
2608 }
2609 rSubmixModule->removeOutputProfile(address);
2610 rSubmixModule->removeInputProfile(address);
2611
2612 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2613 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
2614 res = INVALID_OPERATION;
2615 continue;
2616 }
2617 }
2618 }
2619 return res;
2620 }
2621
2622
dump(int fd)2623 status_t AudioPolicyManager::dump(int fd)
2624 {
2625 const size_t SIZE = 256;
2626 char buffer[SIZE];
2627 String8 result;
2628
2629 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2630 result.append(buffer);
2631
2632 snprintf(buffer, SIZE, " Primary Output: %d\n",
2633 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
2634 result.append(buffer);
2635 std::string stateLiteral;
2636 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2637 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
2638 result.append(buffer);
2639 snprintf(buffer, SIZE, " Force use for communications %d\n",
2640 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
2641 result.append(buffer);
2642 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
2643 result.append(buffer);
2644 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
2645 result.append(buffer);
2646 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
2647 result.append(buffer);
2648 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
2649 result.append(buffer);
2650 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2651 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
2652 result.append(buffer);
2653 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2654 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2655 result.append(buffer);
2656 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2657 result.append(buffer);
2658 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2659 result.append(buffer);
2660
2661 write(fd, result.string(), result.size());
2662
2663 mAvailableOutputDevices.dump(fd, String8("Available output"));
2664 mAvailableInputDevices.dump(fd, String8("Available input"));
2665 mHwModulesAll.dump(fd);
2666 mOutputs.dump(fd);
2667 mInputs.dump(fd);
2668 mVolumeCurves->dump(fd);
2669 mEffects.dump(fd);
2670 mAudioPatches.dump(fd);
2671 mPolicyMixes.dump(fd);
2672
2673 return NO_ERROR;
2674 }
2675
2676 // This function checks for the parameters which can be offloaded.
2677 // This can be enhanced depending on the capability of the DSP and policy
2678 // of the system.
isOffloadSupported(const audio_offload_info_t & offloadInfo)2679 bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
2680 {
2681 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
2682 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
2683 offloadInfo.sample_rate, offloadInfo.channel_mask,
2684 offloadInfo.format,
2685 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2686 offloadInfo.has_video);
2687
2688 if (mMasterMono) {
2689 return false; // no offloading if mono is set.
2690 }
2691
2692 // Check if offload has been disabled
2693 char propValue[PROPERTY_VALUE_MAX];
2694 if (property_get("audio.offload.disable", propValue, "0")) {
2695 if (atoi(propValue) != 0) {
2696 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2697 return false;
2698 }
2699 }
2700
2701 // Check if stream type is music, then only allow offload as of now.
2702 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2703 {
2704 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2705 return false;
2706 }
2707
2708 //TODO: enable audio offloading with video when ready
2709 const bool allowOffloadWithVideo =
2710 property_get_bool("audio.offload.video", false /* default_value */);
2711 if (offloadInfo.has_video && !allowOffloadWithVideo) {
2712 ALOGV("isOffloadSupported: has_video == true, returning false");
2713 return false;
2714 }
2715
2716 //If duration is less than minimum value defined in property, return false
2717 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2718 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2719 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2720 return false;
2721 }
2722 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2723 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2724 return false;
2725 }
2726
2727 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2728 // creating an offloaded track and tearing it down immediately after start when audioflinger
2729 // detects there is an active non offloadable effect.
2730 // FIXME: We should check the audio session here but we do not have it in this context.
2731 // This may prevent offloading in rare situations where effects are left active by apps
2732 // in the background.
2733 if (mEffects.isNonOffloadableEffectEnabled()) {
2734 return false;
2735 }
2736
2737 // See if there is a profile to support this.
2738 // AUDIO_DEVICE_NONE
2739 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
2740 offloadInfo.sample_rate,
2741 offloadInfo.format,
2742 offloadInfo.channel_mask,
2743 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
2744 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2745 return (profile != 0);
2746 }
2747
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port * ports,unsigned int * generation)2748 status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2749 audio_port_type_t type,
2750 unsigned int *num_ports,
2751 struct audio_port *ports,
2752 unsigned int *generation)
2753 {
2754 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2755 generation == NULL) {
2756 return BAD_VALUE;
2757 }
2758 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2759 if (ports == NULL) {
2760 *num_ports = 0;
2761 }
2762
2763 size_t portsWritten = 0;
2764 size_t portsMax = *num_ports;
2765 *num_ports = 0;
2766 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2767 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2768 // as they are used by stub HALs by convention
2769 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2770 for (const auto& dev : mAvailableOutputDevices) {
2771 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
2772 continue;
2773 }
2774 if (portsWritten < portsMax) {
2775 dev->toAudioPort(&ports[portsWritten++]);
2776 }
2777 (*num_ports)++;
2778 }
2779 }
2780 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2781 for (const auto& dev : mAvailableInputDevices) {
2782 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
2783 continue;
2784 }
2785 if (portsWritten < portsMax) {
2786 dev->toAudioPort(&ports[portsWritten++]);
2787 }
2788 (*num_ports)++;
2789 }
2790 }
2791 }
2792 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2793 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2794 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2795 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2796 }
2797 *num_ports += mInputs.size();
2798 }
2799 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2800 size_t numOutputs = 0;
2801 for (size_t i = 0; i < mOutputs.size(); i++) {
2802 if (!mOutputs[i]->isDuplicated()) {
2803 numOutputs++;
2804 if (portsWritten < portsMax) {
2805 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2806 }
2807 }
2808 }
2809 *num_ports += numOutputs;
2810 }
2811 }
2812 *generation = curAudioPortGeneration();
2813 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
2814 return NO_ERROR;
2815 }
2816
getAudioPort(struct audio_port * port)2817 status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
2818 {
2819 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2820 return BAD_VALUE;
2821 }
2822 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2823 if (dev != 0) {
2824 dev->toAudioPort(port);
2825 return NO_ERROR;
2826 }
2827 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2828 if (dev != 0) {
2829 dev->toAudioPort(port);
2830 return NO_ERROR;
2831 }
2832 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2833 if (out != 0) {
2834 out->toAudioPort(port);
2835 return NO_ERROR;
2836 }
2837 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2838 if (in != 0) {
2839 in->toAudioPort(port);
2840 return NO_ERROR;
2841 }
2842 return BAD_VALUE;
2843 }
2844
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid)2845 status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2846 audio_patch_handle_t *handle,
2847 uid_t uid)
2848 {
2849 ALOGV("createAudioPatch()");
2850
2851 if (handle == NULL || patch == NULL) {
2852 return BAD_VALUE;
2853 }
2854 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2855
2856 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2857 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2858 return BAD_VALUE;
2859 }
2860 // only one source per audio patch supported for now
2861 if (patch->num_sources > 1) {
2862 return INVALID_OPERATION;
2863 }
2864
2865 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
2866 return INVALID_OPERATION;
2867 }
2868 for (size_t i = 0; i < patch->num_sinks; i++) {
2869 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2870 return INVALID_OPERATION;
2871 }
2872 }
2873
2874 sp<AudioPatch> patchDesc;
2875 ssize_t index = mAudioPatches.indexOfKey(*handle);
2876
2877 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2878 patch->sources[0].role,
2879 patch->sources[0].type);
2880 #if LOG_NDEBUG == 0
2881 for (size_t i = 0; i < patch->num_sinks; i++) {
2882 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
2883 patch->sinks[i].role,
2884 patch->sinks[i].type);
2885 }
2886 #endif
2887
2888 if (index >= 0) {
2889 patchDesc = mAudioPatches.valueAt(index);
2890 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2891 mUidCached, patchDesc->mUid, uid);
2892 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2893 return INVALID_OPERATION;
2894 }
2895 } else {
2896 *handle = AUDIO_PATCH_HANDLE_NONE;
2897 }
2898
2899 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
2900 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
2901 if (outputDesc == NULL) {
2902 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2903 return BAD_VALUE;
2904 }
2905 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2906 outputDesc->mIoHandle);
2907 if (patchDesc != 0) {
2908 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2909 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2910 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2911 return BAD_VALUE;
2912 }
2913 }
2914 DeviceVector devices;
2915 for (size_t i = 0; i < patch->num_sinks; i++) {
2916 // Only support mix to devices connection
2917 // TODO add support for mix to mix connection
2918 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2919 ALOGV("createAudioPatch() source mix but sink is not a device");
2920 return INVALID_OPERATION;
2921 }
2922 sp<DeviceDescriptor> devDesc =
2923 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2924 if (devDesc == 0) {
2925 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2926 return BAD_VALUE;
2927 }
2928
2929 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
2930 devDesc->mAddress,
2931 patch->sources[0].sample_rate,
2932 NULL, // updatedSamplingRate
2933 patch->sources[0].format,
2934 NULL, // updatedFormat
2935 patch->sources[0].channel_mask,
2936 NULL, // updatedChannelMask
2937 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2938 ALOGV("createAudioPatch() profile not supported for device %08x",
2939 devDesc->type());
2940 return INVALID_OPERATION;
2941 }
2942 devices.add(devDesc);
2943 }
2944 if (devices.size() == 0) {
2945 return INVALID_OPERATION;
2946 }
2947
2948 // TODO: reconfigure output format and channels here
2949 ALOGV("createAudioPatch() setting device %08x on output %d",
2950 devices.types(), outputDesc->mIoHandle);
2951 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
2952 index = mAudioPatches.indexOfKey(*handle);
2953 if (index >= 0) {
2954 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2955 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2956 }
2957 patchDesc = mAudioPatches.valueAt(index);
2958 patchDesc->mUid = uid;
2959 ALOGV("createAudioPatch() success");
2960 } else {
2961 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2962 return INVALID_OPERATION;
2963 }
2964 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2965 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2966 // input device to input mix connection
2967 // only one sink supported when connecting an input device to a mix
2968 if (patch->num_sinks > 1) {
2969 return INVALID_OPERATION;
2970 }
2971 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
2972 if (inputDesc == NULL) {
2973 return BAD_VALUE;
2974 }
2975 if (patchDesc != 0) {
2976 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2977 return BAD_VALUE;
2978 }
2979 }
2980 sp<DeviceDescriptor> devDesc =
2981 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2982 if (devDesc == 0) {
2983 return BAD_VALUE;
2984 }
2985
2986 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
2987 devDesc->mAddress,
2988 patch->sinks[0].sample_rate,
2989 NULL, /*updatedSampleRate*/
2990 patch->sinks[0].format,
2991 NULL, /*updatedFormat*/
2992 patch->sinks[0].channel_mask,
2993 NULL, /*updatedChannelMask*/
2994 // FIXME for the parameter type,
2995 // and the NONE
2996 (audio_output_flags_t)
2997 AUDIO_INPUT_FLAG_NONE)) {
2998 return INVALID_OPERATION;
2999 }
3000 // TODO: reconfigure output format and channels here
3001 ALOGV("createAudioPatch() setting device %08x on output %d",
3002 devDesc->type(), inputDesc->mIoHandle);
3003 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
3004 index = mAudioPatches.indexOfKey(*handle);
3005 if (index >= 0) {
3006 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3007 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3008 }
3009 patchDesc = mAudioPatches.valueAt(index);
3010 patchDesc->mUid = uid;
3011 ALOGV("createAudioPatch() success");
3012 } else {
3013 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3014 return INVALID_OPERATION;
3015 }
3016 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3017 // device to device connection
3018 if (patchDesc != 0) {
3019 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3020 return BAD_VALUE;
3021 }
3022 }
3023 sp<DeviceDescriptor> srcDeviceDesc =
3024 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3025 if (srcDeviceDesc == 0) {
3026 return BAD_VALUE;
3027 }
3028
3029 //update source and sink with our own data as the data passed in the patch may
3030 // be incomplete.
3031 struct audio_patch newPatch = *patch;
3032 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
3033
3034 for (size_t i = 0; i < patch->num_sinks; i++) {
3035 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3036 ALOGV("createAudioPatch() source device but one sink is not a device");
3037 return INVALID_OPERATION;
3038 }
3039
3040 sp<DeviceDescriptor> sinkDeviceDesc =
3041 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3042 if (sinkDeviceDesc == 0) {
3043 return BAD_VALUE;
3044 }
3045 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3046
3047 // create a software bridge in PatchPanel if:
3048 // - source and sink devices are on different HW modules OR
3049 // - audio HAL version is < 3.0
3050 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
3051 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
3052 // support only one sink device for now to simplify output selection logic
3053 if (patch->num_sinks > 1) {
3054 return INVALID_OPERATION;
3055 }
3056 SortedVector<audio_io_handle_t> outputs =
3057 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
3058 // if the sink device is reachable via an opened output stream, request to go via
3059 // this output stream by adding a second source to the patch description
3060 audio_io_handle_t output = selectOutput(outputs,
3061 AUDIO_OUTPUT_FLAG_NONE,
3062 AUDIO_FORMAT_INVALID);
3063 if (output != AUDIO_IO_HANDLE_NONE) {
3064 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3065 if (outputDesc->isDuplicated()) {
3066 return INVALID_OPERATION;
3067 }
3068 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
3069 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
3070 newPatch.num_sources = 2;
3071 }
3072 }
3073 }
3074 // TODO: check from routing capabilities in config file and other conflicting patches
3075
3076 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3077 if (index >= 0) {
3078 afPatchHandle = patchDesc->mAfPatchHandle;
3079 }
3080
3081 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3082 &afPatchHandle,
3083 0);
3084 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3085 status, afPatchHandle);
3086 if (status == NO_ERROR) {
3087 if (index < 0) {
3088 patchDesc = new AudioPatch(&newPatch, uid);
3089 addAudioPatch(patchDesc->mHandle, patchDesc);
3090 } else {
3091 patchDesc->mPatch = newPatch;
3092 }
3093 patchDesc->mAfPatchHandle = afPatchHandle;
3094 *handle = patchDesc->mHandle;
3095 nextAudioPortGeneration();
3096 mpClientInterface->onAudioPatchListUpdate();
3097 } else {
3098 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3099 status);
3100 return INVALID_OPERATION;
3101 }
3102 } else {
3103 return BAD_VALUE;
3104 }
3105 } else {
3106 return BAD_VALUE;
3107 }
3108 return NO_ERROR;
3109 }
3110
releaseAudioPatch(audio_patch_handle_t handle,uid_t uid)3111 status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3112 uid_t uid)
3113 {
3114 ALOGV("releaseAudioPatch() patch %d", handle);
3115
3116 ssize_t index = mAudioPatches.indexOfKey(handle);
3117
3118 if (index < 0) {
3119 return BAD_VALUE;
3120 }
3121 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3122 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3123 mUidCached, patchDesc->mUid, uid);
3124 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3125 return INVALID_OPERATION;
3126 }
3127
3128 struct audio_patch *patch = &patchDesc->mPatch;
3129 patchDesc->mUid = mUidCached;
3130 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
3131 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
3132 if (outputDesc == NULL) {
3133 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3134 return BAD_VALUE;
3135 }
3136
3137 setOutputDevice(outputDesc,
3138 getNewOutputDevice(outputDesc, true /*fromCache*/),
3139 true,
3140 0,
3141 NULL);
3142 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3143 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3144 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
3145 if (inputDesc == NULL) {
3146 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3147 return BAD_VALUE;
3148 }
3149 setInputDevice(inputDesc->mIoHandle,
3150 getNewInputDevice(inputDesc),
3151 true,
3152 NULL);
3153 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3154 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3155 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3156 status, patchDesc->mAfPatchHandle);
3157 removeAudioPatch(patchDesc->mHandle);
3158 nextAudioPortGeneration();
3159 mpClientInterface->onAudioPatchListUpdate();
3160 } else {
3161 return BAD_VALUE;
3162 }
3163 } else {
3164 return BAD_VALUE;
3165 }
3166 return NO_ERROR;
3167 }
3168
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)3169 status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3170 struct audio_patch *patches,
3171 unsigned int *generation)
3172 {
3173 if (generation == NULL) {
3174 return BAD_VALUE;
3175 }
3176 *generation = curAudioPortGeneration();
3177 return mAudioPatches.listAudioPatches(num_patches, patches);
3178 }
3179
setAudioPortConfig(const struct audio_port_config * config)3180 status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
3181 {
3182 ALOGV("setAudioPortConfig()");
3183
3184 if (config == NULL) {
3185 return BAD_VALUE;
3186 }
3187 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3188 // Only support gain configuration for now
3189 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3190 return INVALID_OPERATION;
3191 }
3192
3193 sp<AudioPortConfig> audioPortConfig;
3194 if (config->type == AUDIO_PORT_TYPE_MIX) {
3195 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3196 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
3197 if (outputDesc == NULL) {
3198 return BAD_VALUE;
3199 }
3200 ALOG_ASSERT(!outputDesc->isDuplicated(),
3201 "setAudioPortConfig() called on duplicated output %d",
3202 outputDesc->mIoHandle);
3203 audioPortConfig = outputDesc;
3204 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3205 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
3206 if (inputDesc == NULL) {
3207 return BAD_VALUE;
3208 }
3209 audioPortConfig = inputDesc;
3210 } else {
3211 return BAD_VALUE;
3212 }
3213 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3214 sp<DeviceDescriptor> deviceDesc;
3215 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3216 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3217 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3218 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3219 } else {
3220 return BAD_VALUE;
3221 }
3222 if (deviceDesc == NULL) {
3223 return BAD_VALUE;
3224 }
3225 audioPortConfig = deviceDesc;
3226 } else {
3227 return BAD_VALUE;
3228 }
3229
3230 struct audio_port_config backupConfig;
3231 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3232 if (status == NO_ERROR) {
3233 struct audio_port_config newConfig;
3234 audioPortConfig->toAudioPortConfig(&newConfig, config);
3235 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
3236 }
3237 if (status != NO_ERROR) {
3238 audioPortConfig->applyAudioPortConfig(&backupConfig);
3239 }
3240
3241 return status;
3242 }
3243
releaseResourcesForUid(uid_t uid)3244 void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3245 {
3246 clearAudioSources(uid);
3247 clearAudioPatches(uid);
3248 clearSessionRoutes(uid);
3249 }
3250
clearAudioPatches(uid_t uid)3251 void AudioPolicyManager::clearAudioPatches(uid_t uid)
3252 {
3253 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
3254 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3255 if (patchDesc->mUid == uid) {
3256 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
3257 }
3258 }
3259 }
3260
checkStrategyRoute(routing_strategy strategy,audio_io_handle_t ouptutToSkip)3261 void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3262 audio_io_handle_t ouptutToSkip)
3263 {
3264 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3265 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3266 for (size_t j = 0; j < mOutputs.size(); j++) {
3267 if (mOutputs.keyAt(j) == ouptutToSkip) {
3268 continue;
3269 }
3270 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3271 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3272 continue;
3273 }
3274 // If the default device for this strategy is on another output mix,
3275 // invalidate all tracks in this strategy to force re connection.
3276 // Otherwise select new device on the output mix.
3277 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
3278 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
3279 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3280 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3281 }
3282 }
3283 } else {
3284 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3285 setOutputDevice(outputDesc, newDevice, false);
3286 }
3287 }
3288 }
3289
clearSessionRoutes(uid_t uid)3290 void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3291 {
3292 // remove output routes associated with this uid
3293 SortedVector<routing_strategy> affectedStrategies;
3294 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3295 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3296 if (route->mUid == uid) {
3297 mOutputRoutes.removeItemsAt(i);
3298 if (route->mDeviceDescriptor != 0) {
3299 affectedStrategies.add(getStrategy(route->mStreamType));
3300 }
3301 }
3302 }
3303 // reroute outputs if necessary
3304 for (const auto& strategy : affectedStrategies) {
3305 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
3306 }
3307
3308 // remove input routes associated with this uid
3309 SortedVector<audio_source_t> affectedSources;
3310 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3311 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3312 if (route->mUid == uid) {
3313 mInputRoutes.removeItemsAt(i);
3314 if (route->mDeviceDescriptor != 0) {
3315 affectedSources.add(route->mSource);
3316 }
3317 }
3318 }
3319 // reroute inputs if necessary
3320 SortedVector<audio_io_handle_t> inputsToClose;
3321 for (size_t i = 0; i < mInputs.size(); i++) {
3322 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3323 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
3324 inputsToClose.add(inputDesc->mIoHandle);
3325 }
3326 }
3327 for (const auto& input : inputsToClose) {
3328 closeInput(input);
3329 }
3330 }
3331
clearAudioSources(uid_t uid)3332 void AudioPolicyManager::clearAudioSources(uid_t uid)
3333 {
3334 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3335 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3336 if (sourceDesc->mUid == uid) {
3337 stopAudioSource(mAudioSources.keyAt(i));
3338 }
3339 }
3340 }
3341
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)3342 status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3343 audio_io_handle_t *ioHandle,
3344 audio_devices_t *device)
3345 {
3346 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3347 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
3348 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
3349
3350 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
3351 }
3352
startAudioSource(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_patch_handle_t * handle,uid_t uid)3353 status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3354 const audio_attributes_t *attributes,
3355 audio_patch_handle_t *handle,
3356 uid_t uid)
3357 {
3358 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3359 if (source == NULL || attributes == NULL || handle == NULL) {
3360 return BAD_VALUE;
3361 }
3362
3363 *handle = AUDIO_PATCH_HANDLE_NONE;
3364
3365 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3366 source->type != AUDIO_PORT_TYPE_DEVICE) {
3367 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3368 return INVALID_OPERATION;
3369 }
3370
3371 sp<DeviceDescriptor> srcDeviceDesc =
3372 mAvailableInputDevices.getDevice(source->ext.device.type,
3373 String8(source->ext.device.address));
3374 if (srcDeviceDesc == 0) {
3375 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3376 return BAD_VALUE;
3377 }
3378 sp<AudioSourceDescriptor> sourceDesc =
3379 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3380
3381 struct audio_patch dummyPatch;
3382 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3383 sourceDesc->mPatchDesc = patchDesc;
3384
3385 status_t status = connectAudioSource(sourceDesc);
3386 if (status == NO_ERROR) {
3387 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3388 *handle = sourceDesc->getHandle();
3389 }
3390 return status;
3391 }
3392
connectAudioSource(const sp<AudioSourceDescriptor> & sourceDesc)3393 status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3394 {
3395 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3396
3397 // make sure we only have one patch per source.
3398 disconnectAudioSource(sourceDesc);
3399
3400 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3401 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
3402 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3403
3404 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3405 sp<DeviceDescriptor> sinkDeviceDesc =
3406 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3407
3408 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3409 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3410
3411 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3412 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
3413 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
3414 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3415 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3416 // create patch between src device and output device
3417 // create Hwoutput and add to mHwOutputs
3418 } else {
3419 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3420 audio_io_handle_t output =
3421 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3422 if (output == AUDIO_IO_HANDLE_NONE) {
3423 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3424 return INVALID_OPERATION;
3425 }
3426 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3427 if (outputDesc->isDuplicated()) {
3428 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3429 return INVALID_OPERATION;
3430 }
3431 status_t status = outputDesc->start();
3432 if (status != NO_ERROR) {
3433 return status;
3434 }
3435
3436 // create a special patch with no sink and two sources:
3437 // - the second source indicates to PatchPanel through which output mix this patch should
3438 // be connected as well as the stream type for volume control
3439 // - the sink is defined by whatever output device is currently selected for the output
3440 // though which this patch is routed.
3441 patch->num_sinks = 0;
3442 patch->num_sources = 2;
3443 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3444 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3445 patch->sources[1].ext.mix.usecase.stream = stream;
3446 status = mpClientInterface->createAudioPatch(patch,
3447 &afPatchHandle,
3448 0);
3449 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3450 status, afPatchHandle);
3451 if (status != NO_ERROR) {
3452 ALOGW("%s patch panel could not connect device patch, error %d",
3453 __FUNCTION__, status);
3454 return INVALID_OPERATION;
3455 }
3456 uint32_t delayMs = 0;
3457 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
3458
3459 if (status != NO_ERROR) {
3460 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3461 return status;
3462 }
3463 sourceDesc->mSwOutput = outputDesc;
3464 if (delayMs != 0) {
3465 usleep(delayMs * 1000);
3466 }
3467 }
3468
3469 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3470 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3471
3472 return NO_ERROR;
3473 }
3474
stopAudioSource(audio_patch_handle_t handle __unused)3475 status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
3476 {
3477 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3478 ALOGV("%s handle %d", __FUNCTION__, handle);
3479 if (sourceDesc == 0) {
3480 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3481 return BAD_VALUE;
3482 }
3483 status_t status = disconnectAudioSource(sourceDesc);
3484
3485 mAudioSources.removeItem(handle);
3486 return status;
3487 }
3488
setMasterMono(bool mono)3489 status_t AudioPolicyManager::setMasterMono(bool mono)
3490 {
3491 if (mMasterMono == mono) {
3492 return NO_ERROR;
3493 }
3494 mMasterMono = mono;
3495 // if enabling mono we close all offloaded devices, which will invalidate the
3496 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3497 // for recreating the new AudioTrack as non-offloaded PCM.
3498 //
3499 // If disabling mono, we leave all tracks as is: we don't know which clients
3500 // and tracks are able to be recreated as offloaded. The next "song" should
3501 // play back offloaded.
3502 if (mMasterMono) {
3503 Vector<audio_io_handle_t> offloaded;
3504 for (size_t i = 0; i < mOutputs.size(); ++i) {
3505 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3506 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3507 offloaded.push(desc->mIoHandle);
3508 }
3509 }
3510 for (const auto& handle : offloaded) {
3511 closeOutput(handle);
3512 }
3513 }
3514 // update master mono for all remaining outputs
3515 for (size_t i = 0; i < mOutputs.size(); ++i) {
3516 updateMono(mOutputs.keyAt(i));
3517 }
3518 return NO_ERROR;
3519 }
3520
getMasterMono(bool * mono)3521 status_t AudioPolicyManager::getMasterMono(bool *mono)
3522 {
3523 *mono = mMasterMono;
3524 return NO_ERROR;
3525 }
3526
getStreamVolumeDB(audio_stream_type_t stream,int index,audio_devices_t device)3527 float AudioPolicyManager::getStreamVolumeDB(
3528 audio_stream_type_t stream, int index, audio_devices_t device)
3529 {
3530 return computeVolume(stream, index, device);
3531 }
3532
getSupportedFormats(audio_io_handle_t ioHandle,FormatVector & formats)3533 status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3534 FormatVector& formats) {
3535 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3536 return BAD_VALUE;
3537 }
3538 String8 reply;
3539 reply = mpClientInterface->getParameters(
3540 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3541 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3542 AudioParameter repliedParameters(reply);
3543 if (repliedParameters.get(
3544 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3545 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3546 return BAD_VALUE;
3547 }
3548 for (auto format : formatsFromString(reply.string())) {
3549 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3550 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3551 if (format == AAC_FORMATS[i]) {
3552 format = AUDIO_FORMAT_AAC_LC;
3553 break;
3554 }
3555 }
3556 bool exist = false;
3557 for (size_t i = 0; i < formats.size(); i++) {
3558 if (format == formats[i]) {
3559 exist = true;
3560 break;
3561 }
3562 }
3563 bool isSurroundFormat = false;
3564 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3565 if (SURROUND_FORMATS[i] == format) {
3566 isSurroundFormat = true;
3567 break;
3568 }
3569 }
3570 if (!exist && isSurroundFormat) {
3571 formats.add(format);
3572 }
3573 }
3574 return NO_ERROR;
3575 }
3576
getSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats,bool * surroundFormatsEnabled,bool reported)3577 status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3578 audio_format_t *surroundFormats,
3579 bool *surroundFormatsEnabled,
3580 bool reported)
3581 {
3582 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3583 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3584 return BAD_VALUE;
3585 }
3586 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3587 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3588
3589 // Only return value if there is HDMI output.
3590 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3591 return INVALID_OPERATION;
3592 }
3593
3594 size_t formatsWritten = 0;
3595 size_t formatsMax = *numSurroundFormats;
3596 *numSurroundFormats = 0;
3597 FormatVector formats;
3598 if (reported) {
3599 // Only get surround formats which are reported by device.
3600 // First list already open outputs that can be routed to this device
3601 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3602 SortedVector<audio_io_handle_t> outputs;
3603 bool reportedFormatFound = false;
3604 status_t status;
3605 sp<SwAudioOutputDescriptor> desc;
3606 for (size_t i = 0; i < mOutputs.size(); i++) {
3607 desc = mOutputs.valueAt(i);
3608 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3609 outputs.add(mOutputs.keyAt(i));
3610 }
3611 }
3612 // Open an output to query dynamic parameters.
3613 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3614 AUDIO_DEVICE_OUT_HDMI);
3615 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3616 String8 address = hdmiOutputDevices[i]->mAddress;
3617 for (const auto& hwModule : mHwModules) {
3618 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3619 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3620 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3621 profile->supportDeviceAddress(address)) {
3622 size_t j;
3623 for (j = 0; j < outputs.size(); j++) {
3624 desc = mOutputs.valueFor(outputs.itemAt(j));
3625 if (!desc->isDuplicated() && desc->mProfile == profile) {
3626 break;
3627 }
3628 }
3629 if (j != outputs.size()) {
3630 status = getSupportedFormats(outputs.itemAt(j), formats);
3631 reportedFormatFound |= (status == NO_ERROR);
3632 continue;
3633 }
3634
3635 if (!profile->canOpenNewIo()) {
3636 ALOGW("Max Output number %u already opened for this profile %s",
3637 profile->maxOpenCount, profile->getTagName().c_str());
3638 continue;
3639 }
3640
3641 ALOGV("opening output for device %08x with params %s profile %p name %s",
3642 device, address.string(), profile.get(), profile->getName().string());
3643 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3644 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3645 status_t status = desc->open(nullptr, device, address,
3646 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3647 &output);
3648
3649 if (status == NO_ERROR) {
3650 status = getSupportedFormats(output, formats);
3651 reportedFormatFound |= (status == NO_ERROR);
3652 desc->close();
3653 output = AUDIO_IO_HANDLE_NONE;
3654 }
3655 }
3656 }
3657 }
3658 }
3659
3660 if (!reportedFormatFound) {
3661 return UNKNOWN_ERROR;
3662 }
3663 } else {
3664 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3665 formats.add(SURROUND_FORMATS[i]);
3666 }
3667 }
3668 for (size_t i = 0; i < formats.size(); i++) {
3669 if (formatsWritten < formatsMax) {
3670 surroundFormats[formatsWritten] = formats[i];
3671 bool formatEnabled = false;
3672 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3673 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3674 formatEnabled =
3675 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3676 break;
3677 }
3678 } else {
3679 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3680 }
3681 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3682 }
3683 (*numSurroundFormats)++;
3684 }
3685 return NO_ERROR;
3686 }
3687
setSurroundFormatEnabled(audio_format_t audioFormat,bool enabled)3688 status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3689 {
3690 // Check if audio format is a surround formats.
3691 bool isSurroundFormat = false;
3692 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3693 if (audioFormat == SURROUND_FORMATS[i]) {
3694 isSurroundFormat = true;
3695 break;
3696 }
3697 }
3698 if (!isSurroundFormat) {
3699 return BAD_VALUE;
3700 }
3701
3702 // Should only be called when MANUAL.
3703 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3704 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3705 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3706 return INVALID_OPERATION;
3707 }
3708
3709 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3710 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3711 return NO_ERROR;
3712 }
3713
3714 // The operation is valid only when there is HDMI output available.
3715 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3716 return INVALID_OPERATION;
3717 }
3718
3719 if (enabled) {
3720 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3721 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3722 mSurroundFormats.insert(AAC_FORMATS[i]);
3723 }
3724 } else {
3725 mSurroundFormats.insert(audioFormat);
3726 }
3727 } else {
3728 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3729 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3730 mSurroundFormats.erase(AAC_FORMATS[i]);
3731 }
3732 } else {
3733 mSurroundFormats.erase(audioFormat);
3734 }
3735 }
3736
3737 sp<SwAudioOutputDescriptor> outputDesc;
3738 bool profileUpdated = false;
3739 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3740 AUDIO_DEVICE_OUT_HDMI);
3741 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3742 // Simulate reconnection to update enabled surround sound formats.
3743 String8 address = hdmiOutputDevices[i]->mAddress;
3744 String8 name = hdmiOutputDevices[i]->getName();
3745 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3746 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3747 address.c_str(),
3748 name.c_str());
3749 if (status != NO_ERROR) {
3750 continue;
3751 }
3752 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3753 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3754 address.c_str(),
3755 name.c_str());
3756 profileUpdated |= (status == NO_ERROR);
3757 }
3758 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
3759 AUDIO_DEVICE_IN_HDMI);
3760 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3761 // Simulate reconnection to update enabled surround sound formats.
3762 String8 address = hdmiInputDevices[i]->mAddress;
3763 String8 name = hdmiInputDevices[i]->getName();
3764 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3765 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3766 address.c_str(),
3767 name.c_str());
3768 if (status != NO_ERROR) {
3769 continue;
3770 }
3771 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3772 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3773 address.c_str(),
3774 name.c_str());
3775 profileUpdated |= (status == NO_ERROR);
3776 }
3777
3778 // Undo the surround formats change due to no audio profiles updated.
3779 if (!profileUpdated) {
3780 if (enabled) {
3781 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3782 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3783 mSurroundFormats.erase(AAC_FORMATS[i]);
3784 }
3785 } else {
3786 mSurroundFormats.erase(audioFormat);
3787 }
3788 } else {
3789 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3790 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3791 mSurroundFormats.insert(AAC_FORMATS[i]);
3792 }
3793 } else {
3794 mSurroundFormats.insert(audioFormat);
3795 }
3796 }
3797 }
3798
3799 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3800 }
3801
setRecordSilenced(uid_t uid,bool silenced)3802 void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3803 {
3804 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3805
3806 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3807 for (size_t i = 0; i < activeInputs.size(); i++) {
3808 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3809 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3810 for (size_t j = 0; j < activeSessions.size(); j++) {
3811 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3812 if (activeSession->uid() == uid) {
3813 activeSession->setSilenced(silenced);
3814 }
3815 }
3816 }
3817 }
3818
disconnectAudioSource(const sp<AudioSourceDescriptor> & sourceDesc)3819 status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3820 {
3821 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3822
3823 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3824 if (patchDesc == 0) {
3825 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3826 sourceDesc->mPatchDesc->mHandle);
3827 return BAD_VALUE;
3828 }
3829 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3830
3831 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
3832 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3833 if (swOutputDesc != 0) {
3834 status_t status = stopSource(swOutputDesc, stream, false);
3835 if (status == NO_ERROR) {
3836 swOutputDesc->stop();
3837 }
3838 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3839 } else {
3840 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3841 if (hwOutputDesc != 0) {
3842 // release patch between src device and output device
3843 // close Hwoutput and remove from mHwOutputs
3844 } else {
3845 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3846 }
3847 }
3848 return NO_ERROR;
3849 }
3850
getSourceForStrategyOnOutput(audio_io_handle_t output,routing_strategy strategy)3851 sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3852 audio_io_handle_t output, routing_strategy strategy)
3853 {
3854 sp<AudioSourceDescriptor> source;
3855 for (size_t i = 0; i < mAudioSources.size(); i++) {
3856 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3857 routing_strategy sourceStrategy =
3858 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3859 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3860 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3861 source = sourceDesc;
3862 break;
3863 }
3864 }
3865 return source;
3866 }
3867
3868 // ----------------------------------------------------------------------------
3869 // AudioPolicyManager
3870 // ----------------------------------------------------------------------------
nextAudioPortGeneration()3871 uint32_t AudioPolicyManager::nextAudioPortGeneration()
3872 {
3873 return mAudioPortGeneration++;
3874 }
3875
3876 #ifdef USE_XML_AUDIO_POLICY_CONF
3877 // Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3878 static const char *kConfigLocationList[] =
3879 {"/odm/etc", "/vendor/etc", "/system/etc"};
3880 static const int kConfigLocationListSize =
3881 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3882
deserializeAudioPolicyXmlConfig(AudioPolicyConfig & config)3883 static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3884 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3885 std::vector<const char*> fileNames;
3886 status_t ret;
3887
3888 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3889 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3890 // A2DP offload supported but disabled: try to use special XML file
3891 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3892 }
3893 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3894
3895 for (const char* fileName : fileNames) {
3896 for (int i = 0; i < kConfigLocationListSize; i++) {
3897 PolicySerializer serializer;
3898 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3899 "%s/%s", kConfigLocationList[i], fileName);
3900 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3901 if (ret == NO_ERROR) {
3902 return ret;
3903 }
3904 }
3905 }
3906 return ret;
3907 }
3908 #endif
3909
AudioPolicyManager(AudioPolicyClientInterface * clientInterface,bool)3910 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3911 bool /*forTesting*/)
3912 :
3913 mUidCached(getuid()),
3914 mpClientInterface(clientInterface),
3915 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3916 mA2dpSuspended(false),
3917 #ifdef USE_XML_AUDIO_POLICY_CONF
3918 mVolumeCurves(new VolumeCurvesCollection()),
3919 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3920 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
3921 #else
3922 mVolumeCurves(new StreamDescriptorCollection()),
3923 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3924 mDefaultOutputDevice),
3925 #endif
3926 mAudioPortGeneration(1),
3927 mBeaconMuteRefCount(0),
3928 mBeaconPlayingRefCount(0),
3929 mBeaconMuted(false),
3930 mTtsOutputAvailable(false),
3931 mMasterMono(false),
3932 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3933 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
3934 {
3935 }
3936
AudioPolicyManager(AudioPolicyClientInterface * clientInterface)3937 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3938 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3939 {
3940 loadConfig();
3941 initialize();
3942 }
3943
loadConfig()3944 void AudioPolicyManager::loadConfig() {
3945 #ifdef USE_XML_AUDIO_POLICY_CONF
3946 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
3947 #else
3948 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3949 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
3950 #endif
3951 ALOGE("could not load audio policy configuration file, setting defaults");
3952 getConfig().setDefault();
3953 }
3954 }
3955
3956 status_t AudioPolicyManager::initialize() {
3957 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
3958
3959 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
3960 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3961 if (!engineInstance) {
3962 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3963 return NO_INIT;
3964 }
3965 // Retrieve the Policy Manager Interface
3966 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3967 if (mEngine == NULL) {
3968 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3969 return NO_INIT;
3970 }
3971 mEngine->setObserver(this);
3972 status_t status = mEngine->initCheck();
3973 if (status != NO_ERROR) {
3974 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3975 return status;
3976 }
3977
3978 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
3979 // open all output streams needed to access attached devices
3980 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3981 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
3982 for (const auto& hwModule : mHwModulesAll) {
3983 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
3984 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3985 ALOGW("could not open HW module %s", hwModule->getName());
3986 continue;
3987 }
3988 mHwModules.push_back(hwModule);
3989 // open all output streams needed to access attached devices
3990 // except for direct output streams that are only opened when they are actually
3991 // required by an app.
3992 // This also validates mAvailableOutputDevices list
3993 for (const auto& outProfile : hwModule->getOutputProfiles()) {
3994 if (!outProfile->canOpenNewIo()) {
3995 ALOGE("Invalid Output profile max open count %u for profile %s",
3996 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3997 continue;
3998 }
3999 if (!outProfile->hasSupportedDevices()) {
4000 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4001 continue;
4002 }
4003 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4004 mTtsOutputAvailable = true;
4005 }
4006
4007 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4008 continue;
4009 }
4010 audio_devices_t profileType = outProfile->getSupportedDevicesType();
4011 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4012 profileType = mDefaultOutputDevice->type();
4013 } else {
4014 // chose first device present in profile's SupportedDevices also part of
4015 // outputDeviceTypes
4016 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
4017 }
4018 if ((profileType & outputDeviceTypes) == 0) {
4019 continue;
4020 }
4021 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4022 mpClientInterface);
4023 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4024 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
4025 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4026 : String8("");
4027 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4028 status_t status = outputDesc->open(nullptr, profileType, address,
4029 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
4030
4031 if (status != NO_ERROR) {
4032 ALOGW("Cannot open output stream for device %08x on hw module %s",
4033 outputDesc->mDevice,
4034 hwModule->getName());
4035 } else {
4036 for (const auto& dev : supportedDevices) {
4037 ssize_t index = mAvailableOutputDevices.indexOf(dev);
4038 // give a valid ID to an attached device once confirmed it is reachable
4039 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
4040 mAvailableOutputDevices[index]->attach(hwModule);
4041 }
4042 }
4043 if (mPrimaryOutput == 0 &&
4044 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4045 mPrimaryOutput = outputDesc;
4046 }
4047 addOutput(output, outputDesc);
4048 setOutputDevice(outputDesc,
4049 profileType,
4050 true,
4051 0,
4052 NULL,
4053 address);
4054 }
4055 }
4056 // open input streams needed to access attached devices to validate
4057 // mAvailableInputDevices list
4058 for (const auto& inProfile : hwModule->getInputProfiles()) {
4059 if (!inProfile->canOpenNewIo()) {
4060 ALOGE("Invalid Input profile max open count %u for profile %s",
4061 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4062 continue;
4063 }
4064 if (!inProfile->hasSupportedDevices()) {
4065 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4066 continue;
4067 }
4068 // chose first device present in profile's SupportedDevices also part of
4069 // inputDeviceTypes
4070 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4071
4072 if ((profileType & inputDeviceTypes) == 0) {
4073 continue;
4074 }
4075 sp<AudioInputDescriptor> inputDesc =
4076 new AudioInputDescriptor(inProfile, mpClientInterface);
4077
4078 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
4079 // the inputs vector must be of size >= 1, but we don't want to crash here
4080 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4081 : String8("");
4082 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4083 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4084
4085 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4086 status_t status = inputDesc->open(nullptr,
4087 profileType,
4088 address,
4089 AUDIO_SOURCE_MIC,
4090 AUDIO_INPUT_FLAG_NONE,
4091 &input);
4092
4093 if (status == NO_ERROR) {
4094 for (const auto& dev : inProfile->getSupportedDevices()) {
4095 ssize_t index = mAvailableInputDevices.indexOf(dev);
4096 // give a valid ID to an attached device once confirmed it is reachable
4097 if (index >= 0) {
4098 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4099 if (!devDesc->isAttached()) {
4100 devDesc->attach(hwModule);
4101 devDesc->importAudioPort(inProfile, true);
4102 }
4103 }
4104 }
4105 inputDesc->close();
4106 } else {
4107 ALOGW("Cannot open input stream for device %08x on hw module %s",
4108 profileType,
4109 hwModule->getName());
4110 }
4111 }
4112 }
4113 // make sure all attached devices have been allocated a unique ID
4114 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
4115 if (!mAvailableOutputDevices[i]->isAttached()) {
4116 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
4117 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4118 continue;
4119 }
4120 // The device is now validated and can be appended to the available devices of the engine
4121 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4122 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4123 i++;
4124 }
4125 for (size_t i = 0; i < mAvailableInputDevices.size();) {
4126 if (!mAvailableInputDevices[i]->isAttached()) {
4127 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
4128 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4129 continue;
4130 }
4131 // The device is now validated and can be appended to the available devices of the engine
4132 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4133 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4134 i++;
4135 }
4136 // make sure default device is reachable
4137 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
4138 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
4139 status = NO_INIT;
4140 }
4141 // If microphones address is empty, set it according to device type
4142 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4143 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4144 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4145 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4146 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4147 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4148 }
4149 }
4150 }
4151
4152 if (mPrimaryOutput == 0) {
4153 ALOGE("Failed to open primary output");
4154 status = NO_INIT;
4155 }
4156
4157 updateDevicesAndOutputs();
4158 return status;
4159 }
4160
4161 AudioPolicyManager::~AudioPolicyManager()
4162 {
4163 for (size_t i = 0; i < mOutputs.size(); i++) {
4164 mOutputs.valueAt(i)->close();
4165 }
4166 for (size_t i = 0; i < mInputs.size(); i++) {
4167 mInputs.valueAt(i)->close();
4168 }
4169 mAvailableOutputDevices.clear();
4170 mAvailableInputDevices.clear();
4171 mOutputs.clear();
4172 mInputs.clear();
4173 mHwModules.clear();
4174 mHwModulesAll.clear();
4175 mSurroundFormats.clear();
4176 }
4177
4178 status_t AudioPolicyManager::initCheck()
4179 {
4180 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
4181 }
4182
4183 // ---
4184
4185 void AudioPolicyManager::addOutput(audio_io_handle_t output,
4186 const sp<SwAudioOutputDescriptor>& outputDesc)
4187 {
4188 mOutputs.add(output, outputDesc);
4189 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
4190 updateMono(output); // update mono status when adding to output list
4191 selectOutputForMusicEffects();
4192 nextAudioPortGeneration();
4193 }
4194
4195 void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4196 {
4197 mOutputs.removeItem(output);
4198 selectOutputForMusicEffects();
4199 }
4200
4201 void AudioPolicyManager::addInput(audio_io_handle_t input,
4202 const sp<AudioInputDescriptor>& inputDesc)
4203 {
4204 mInputs.add(input, inputDesc);
4205 nextAudioPortGeneration();
4206 }
4207
4208 void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
4209 const audio_devices_t device /*in*/,
4210 const String8& address /*in*/,
4211 SortedVector<audio_io_handle_t>& outputs /*out*/) {
4212 sp<DeviceDescriptor> devDesc =
4213 desc->mProfile->getSupportedDeviceByAddress(device, address);
4214 if (devDesc != 0) {
4215 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4216 desc->mIoHandle, address.string());
4217 outputs.add(desc->mIoHandle);
4218 }
4219 }
4220
4221 status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
4222 audio_policy_dev_state_t state,
4223 SortedVector<audio_io_handle_t>& outputs,
4224 const String8& address)
4225 {
4226 audio_devices_t device = devDesc->type();
4227 sp<SwAudioOutputDescriptor> desc;
4228
4229 if (audio_device_is_digital(device)) {
4230 // erase all current sample rates, formats and channel masks
4231 devDesc->clearAudioProfiles();
4232 }
4233
4234 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4235 // first list already open outputs that can be routed to this device
4236 for (size_t i = 0; i < mOutputs.size(); i++) {
4237 desc = mOutputs.valueAt(i);
4238 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
4239 if (!device_distinguishes_on_address(device)) {
4240 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4241 outputs.add(mOutputs.keyAt(i));
4242 } else {
4243 ALOGV(" checking address match due to device 0x%x", device);
4244 findIoHandlesByAddress(desc, device, address, outputs);
4245 }
4246 }
4247 }
4248 // then look for output profiles that can be routed to this device
4249 SortedVector< sp<IOProfile> > profiles;
4250 for (const auto& hwModule : mHwModules) {
4251 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4252 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
4253 if (profile->supportDevice(device)) {
4254 if (!device_distinguishes_on_address(device) ||
4255 profile->supportDeviceAddress(address)) {
4256 profiles.add(profile);
4257 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4258 j, hwModule->getName());
4259 }
4260 }
4261 }
4262 }
4263
4264 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
4265
4266 if (profiles.isEmpty() && outputs.isEmpty()) {
4267 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4268 return BAD_VALUE;
4269 }
4270
4271 // open outputs for matching profiles if needed. Direct outputs are also opened to
4272 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4273 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4274 sp<IOProfile> profile = profiles[profile_index];
4275
4276 // nothing to do if one output is already opened for this profile
4277 size_t j;
4278 for (j = 0; j < outputs.size(); j++) {
4279 desc = mOutputs.valueFor(outputs.itemAt(j));
4280 if (!desc->isDuplicated() && desc->mProfile == profile) {
4281 // matching profile: save the sample rates, format and channel masks supported
4282 // by the profile in our device descriptor
4283 if (audio_device_is_digital(device)) {
4284 devDesc->importAudioPort(profile);
4285 }
4286 break;
4287 }
4288 }
4289 if (j != outputs.size()) {
4290 continue;
4291 }
4292
4293 if (!profile->canOpenNewIo()) {
4294 ALOGW("Max Output number %u already opened for this profile %s",
4295 profile->maxOpenCount, profile->getTagName().c_str());
4296 continue;
4297 }
4298
4299 ALOGV("opening output for device %08x with params %s profile %p name %s",
4300 device, address.string(), profile.get(), profile->getName().string());
4301 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
4302 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4303 status_t status = desc->open(nullptr, device, address,
4304 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
4305
4306 if (status == NO_ERROR) {
4307 // Here is where the out_set_parameters() for card & device gets called
4308 if (!address.isEmpty()) {
4309 char *param = audio_device_address_to_parameter(device, address);
4310 mpClientInterface->setParameters(output, String8(param));
4311 free(param);
4312 }
4313 updateAudioProfiles(device, output, profile->getAudioProfiles());
4314 if (!profile->hasValidAudioProfile()) {
4315 ALOGW("checkOutputsForDevice() missing param");
4316 desc->close();
4317 output = AUDIO_IO_HANDLE_NONE;
4318 } else if (profile->hasDynamicAudioProfile()) {
4319 desc->close();
4320 output = AUDIO_IO_HANDLE_NONE;
4321 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4322 profile->pickAudioProfile(
4323 config.sample_rate, config.channel_mask, config.format);
4324 config.offload_info.sample_rate = config.sample_rate;
4325 config.offload_info.channel_mask = config.channel_mask;
4326 config.offload_info.format = config.format;
4327
4328 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4329 AUDIO_OUTPUT_FLAG_NONE, &output);
4330 if (status != NO_ERROR) {
4331 output = AUDIO_IO_HANDLE_NONE;
4332 }
4333 }
4334
4335 if (output != AUDIO_IO_HANDLE_NONE) {
4336 addOutput(output, desc);
4337 if (device_distinguishes_on_address(device) && address != "0") {
4338 sp<AudioPolicyMix> policyMix;
4339 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
4340 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4341 address.string());
4342 }
4343 policyMix->setOutput(desc);
4344 desc->mPolicyMix = policyMix->getMix();
4345
4346 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4347 hasPrimaryOutput()) {
4348 // no duplicated output for direct outputs and
4349 // outputs used by dynamic policy mixes
4350 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
4351
4352 //TODO: configure audio effect output stage here
4353
4354 // open a duplicating output thread for the new output and the primary output
4355 sp<SwAudioOutputDescriptor> dupOutputDesc =
4356 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4357 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4358 &duplicatedOutput);
4359 if (status == NO_ERROR) {
4360 // add duplicated output descriptor
4361 addOutput(duplicatedOutput, dupOutputDesc);
4362 } else {
4363 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
4364 mPrimaryOutput->mIoHandle, output);
4365 desc->close();
4366 removeOutput(output);
4367 nextAudioPortGeneration();
4368 output = AUDIO_IO_HANDLE_NONE;
4369 }
4370 }
4371 }
4372 } else {
4373 output = AUDIO_IO_HANDLE_NONE;
4374 }
4375 if (output == AUDIO_IO_HANDLE_NONE) {
4376 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
4377 profiles.removeAt(profile_index);
4378 profile_index--;
4379 } else {
4380 outputs.add(output);
4381 // Load digital format info only for digital devices
4382 if (audio_device_is_digital(device)) {
4383 devDesc->importAudioPort(profile);
4384 }
4385
4386 if (device_distinguishes_on_address(device)) {
4387 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4388 device, address.string());
4389 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
4390 NULL/*patch handle*/, address.string());
4391 }
4392 ALOGV("checkOutputsForDevice(): adding output %d", output);
4393 }
4394 }
4395
4396 if (profiles.isEmpty()) {
4397 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4398 return BAD_VALUE;
4399 }
4400 } else { // Disconnect
4401 // check if one opened output is not needed any more after disconnecting one device
4402 for (size_t i = 0; i < mOutputs.size(); i++) {
4403 desc = mOutputs.valueAt(i);
4404 if (!desc->isDuplicated()) {
4405 // exact match on device
4406 if (device_distinguishes_on_address(device) &&
4407 (desc->supportedDevices() == device)) {
4408 findIoHandlesByAddress(desc, device, address, outputs);
4409 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
4410 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4411 mOutputs.keyAt(i));
4412 outputs.add(mOutputs.keyAt(i));
4413 }
4414 }
4415 }
4416 // Clear any profiles associated with the disconnected device.
4417 for (const auto& hwModule : mHwModules) {
4418 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4419 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
4420 if (profile->supportDevice(device)) {
4421 ALOGV("checkOutputsForDevice(): "
4422 "clearing direct output profile %zu on module %s",
4423 j, hwModule->getName());
4424 profile->clearAudioProfiles();
4425 }
4426 }
4427 }
4428 }
4429 return NO_ERROR;
4430 }
4431
4432 status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
4433 audio_policy_dev_state_t state,
4434 SortedVector<audio_io_handle_t>& inputs,
4435 const String8& address)
4436 {
4437 audio_devices_t device = devDesc->type();
4438 sp<AudioInputDescriptor> desc;
4439
4440 if (audio_device_is_digital(device)) {
4441 // erase all current sample rates, formats and channel masks
4442 devDesc->clearAudioProfiles();
4443 }
4444
4445 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4446 // first list already open inputs that can be routed to this device
4447 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4448 desc = mInputs.valueAt(input_index);
4449 if (desc->mProfile->supportDevice(device)) {
4450 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4451 inputs.add(mInputs.keyAt(input_index));
4452 }
4453 }
4454
4455 // then look for input profiles that can be routed to this device
4456 SortedVector< sp<IOProfile> > profiles;
4457 for (const auto& hwModule : mHwModules) {
4458 for (size_t profile_index = 0;
4459 profile_index < hwModule->getInputProfiles().size();
4460 profile_index++) {
4461 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
4462
4463 if (profile->supportDevice(device)) {
4464 if (!device_distinguishes_on_address(device) ||
4465 profile->supportDeviceAddress(address)) {
4466 profiles.add(profile);
4467 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4468 profile_index, hwModule->getName());
4469 }
4470 }
4471 }
4472 }
4473
4474 if (profiles.isEmpty() && inputs.isEmpty()) {
4475 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4476 return BAD_VALUE;
4477 }
4478
4479 // open inputs for matching profiles if needed. Direct inputs are also opened to
4480 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4481 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4482
4483 sp<IOProfile> profile = profiles[profile_index];
4484
4485 // nothing to do if one input is already opened for this profile
4486 size_t input_index;
4487 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4488 desc = mInputs.valueAt(input_index);
4489 if (desc->mProfile == profile) {
4490 if (audio_device_is_digital(device)) {
4491 devDesc->importAudioPort(profile);
4492 }
4493 break;
4494 }
4495 }
4496 if (input_index != mInputs.size()) {
4497 continue;
4498 }
4499
4500 if (!profile->canOpenNewIo()) {
4501 ALOGW("Max Input number %u already opened for this profile %s",
4502 profile->maxOpenCount, profile->getTagName().c_str());
4503 continue;
4504 }
4505
4506 desc = new AudioInputDescriptor(profile, mpClientInterface);
4507 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4508 status_t status = desc->open(nullptr,
4509 device,
4510 address,
4511 AUDIO_SOURCE_MIC,
4512 AUDIO_INPUT_FLAG_NONE,
4513 &input);
4514
4515 if (status == NO_ERROR) {
4516 if (!address.isEmpty()) {
4517 char *param = audio_device_address_to_parameter(device, address);
4518 mpClientInterface->setParameters(input, String8(param));
4519 free(param);
4520 }
4521 updateAudioProfiles(device, input, profile->getAudioProfiles());
4522 if (!profile->hasValidAudioProfile()) {
4523 ALOGW("checkInputsForDevice() direct input missing param");
4524 desc->close();
4525 input = AUDIO_IO_HANDLE_NONE;
4526 }
4527
4528 if (input != 0) {
4529 addInput(input, desc);
4530 }
4531 } // endif input != 0
4532
4533 if (input == AUDIO_IO_HANDLE_NONE) {
4534 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
4535 profiles.removeAt(profile_index);
4536 profile_index--;
4537 } else {
4538 inputs.add(input);
4539 if (audio_device_is_digital(device)) {
4540 devDesc->importAudioPort(profile);
4541 }
4542 ALOGV("checkInputsForDevice(): adding input %d", input);
4543 }
4544 } // end scan profiles
4545
4546 if (profiles.isEmpty()) {
4547 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4548 return BAD_VALUE;
4549 }
4550 } else {
4551 // Disconnect
4552 // check if one opened input is not needed any more after disconnecting one device
4553 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4554 desc = mInputs.valueAt(input_index);
4555 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
4556 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4557 mInputs.keyAt(input_index));
4558 inputs.add(mInputs.keyAt(input_index));
4559 }
4560 }
4561 // Clear any profiles associated with the disconnected device.
4562 for (const auto& hwModule : mHwModules) {
4563 for (size_t profile_index = 0;
4564 profile_index < hwModule->getInputProfiles().size();
4565 profile_index++) {
4566 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
4567 if (profile->supportDevice(device)) {
4568 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4569 profile_index, hwModule->getName());
4570 profile->clearAudioProfiles();
4571 }
4572 }
4573 }
4574 } // end disconnect
4575
4576 return NO_ERROR;
4577 }
4578
4579
4580 void AudioPolicyManager::closeOutput(audio_io_handle_t output)
4581 {
4582 ALOGV("closeOutput(%d)", output);
4583
4584 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
4585 if (outputDesc == NULL) {
4586 ALOGW("closeOutput() unknown output %d", output);
4587 return;
4588 }
4589 mPolicyMixes.closeOutput(outputDesc);
4590
4591 // look for duplicated outputs connected to the output being removed.
4592 for (size_t i = 0; i < mOutputs.size(); i++) {
4593 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
4594 if (dupOutputDesc->isDuplicated() &&
4595 (dupOutputDesc->mOutput1 == outputDesc ||
4596 dupOutputDesc->mOutput2 == outputDesc)) {
4597 sp<SwAudioOutputDescriptor> outputDesc2;
4598 if (dupOutputDesc->mOutput1 == outputDesc) {
4599 outputDesc2 = dupOutputDesc->mOutput2;
4600 } else {
4601 outputDesc2 = dupOutputDesc->mOutput1;
4602 }
4603 // As all active tracks on duplicated output will be deleted,
4604 // and as they were also referenced on the other output, the reference
4605 // count for their stream type must be adjusted accordingly on
4606 // the other output.
4607 bool wasActive = outputDesc2->isActive();
4608 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
4609 int refCount = dupOutputDesc->mRefCount[j];
4610 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
4611 }
4612 // stop() will be a no op if the output is still active but is needed in case all
4613 // active streams refcounts where cleared above
4614 if (wasActive) {
4615 outputDesc2->stop();
4616 }
4617 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4618 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4619
4620 mpClientInterface->closeOutput(duplicatedOutput);
4621 removeOutput(duplicatedOutput);
4622 }
4623 }
4624
4625 nextAudioPortGeneration();
4626
4627 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
4628 if (index >= 0) {
4629 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4630 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4631 mAudioPatches.removeItemsAt(index);
4632 mpClientInterface->onAudioPatchListUpdate();
4633 }
4634
4635 outputDesc->close();
4636
4637 removeOutput(output);
4638 mPreviousOutputs = mOutputs;
4639 }
4640
4641 void AudioPolicyManager::closeInput(audio_io_handle_t input)
4642 {
4643 ALOGV("closeInput(%d)", input);
4644
4645 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4646 if (inputDesc == NULL) {
4647 ALOGW("closeInput() unknown input %d", input);
4648 return;
4649 }
4650
4651 nextAudioPortGeneration();
4652
4653 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
4654 if (index >= 0) {
4655 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4656 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4657 mAudioPatches.removeItemsAt(index);
4658 mpClientInterface->onAudioPatchListUpdate();
4659 }
4660
4661 inputDesc->close();
4662 mInputs.removeItem(input);
4663 }
4664
4665 SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4666 audio_devices_t device,
4667 const SwAudioOutputCollection& openOutputs)
4668 {
4669 SortedVector<audio_io_handle_t> outputs;
4670
4671 ALOGVV("getOutputsForDevice() device %04x", device);
4672 for (size_t i = 0; i < openOutputs.size(); i++) {
4673 ALOGVV("output %zu isDuplicated=%d device=%04x",
4674 i, openOutputs.valueAt(i)->isDuplicated(),
4675 openOutputs.valueAt(i)->supportedDevices());
4676 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4677 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4678 outputs.add(openOutputs.keyAt(i));
4679 }
4680 }
4681 return outputs;
4682 }
4683
4684 bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
4685 SortedVector<audio_io_handle_t>& outputs2)
4686 {
4687 if (outputs1.size() != outputs2.size()) {
4688 return false;
4689 }
4690 for (size_t i = 0; i < outputs1.size(); i++) {
4691 if (outputs1[i] != outputs2[i]) {
4692 return false;
4693 }
4694 }
4695 return true;
4696 }
4697
4698 void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
4699 {
4700 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4701 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4702 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4703 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4704
4705 // also take into account external policy-related changes: add all outputs which are
4706 // associated with policies in the "before" and "after" output vectors
4707 ALOGVV("checkOutputForStrategy(): policy related outputs");
4708 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4709 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4710 if (desc != 0 && desc->mPolicyMix != NULL) {
4711 srcOutputs.add(desc->mIoHandle);
4712 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4713 }
4714 }
4715 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4716 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4717 if (desc != 0 && desc->mPolicyMix != NULL) {
4718 dstOutputs.add(desc->mIoHandle);
4719 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4720 }
4721 }
4722
4723 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4724 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4725 // audio from invalidated tracks will be rendered when unmuting
4726 uint32_t maxLatency = 0;
4727 for (audio_io_handle_t srcOut : srcOutputs) {
4728 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4729 if (desc != 0 && maxLatency < desc->latency()) {
4730 maxLatency = desc->latency();
4731 }
4732 }
4733 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4734 strategy, srcOutputs[0], dstOutputs[0]);
4735 // mute strategy while moving tracks from one output to another
4736 for (audio_io_handle_t srcOut : srcOutputs) {
4737 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4738 if (desc != 0 && isStrategyActive(desc, strategy)) {
4739 setStrategyMute(strategy, true, desc);
4740 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
4741 }
4742 sp<AudioSourceDescriptor> source =
4743 getSourceForStrategyOnOutput(srcOut, strategy);
4744 if (source != 0){
4745 connectAudioSource(source);
4746 }
4747 }
4748
4749 // Move effects associated to this strategy from previous output to new output
4750 if (strategy == STRATEGY_MEDIA) {
4751 selectOutputForMusicEffects();
4752 }
4753 // Move tracks associated to this strategy from previous output to new output
4754 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
4755 if (getStrategy((audio_stream_type_t)i) == strategy) {
4756 mpClientInterface->invalidateStream((audio_stream_type_t)i);
4757 }
4758 }
4759 }
4760 }
4761
4762 void AudioPolicyManager::checkOutputForAllStrategies()
4763 {
4764 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4765 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
4766 checkOutputForStrategy(STRATEGY_PHONE);
4767 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4768 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
4769 checkOutputForStrategy(STRATEGY_SONIFICATION);
4770 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4771 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
4772 checkOutputForStrategy(STRATEGY_MEDIA);
4773 checkOutputForStrategy(STRATEGY_DTMF);
4774 checkOutputForStrategy(STRATEGY_REROUTING);
4775 }
4776
4777 void AudioPolicyManager::checkA2dpSuspend()
4778 {
4779 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
4780 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
4781 mA2dpSuspended = false;
4782 return;
4783 }
4784
4785 bool isScoConnected =
4786 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4787 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4788 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
4789
4790 // if suspended, restore A2DP output if:
4791 // ((SCO device is NOT connected) ||
4792 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4793 // (phone state is NOT in call) && (phone state is NOT ringing)))
4794 //
4795 // if not suspended, suspend A2DP output if:
4796 // (SCO device is connected) &&
4797 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4798 // ((phone state is in call) || (phone state is ringing)))
4799 //
4800 if (mA2dpSuspended) {
4801 if (!isScoConnected ||
4802 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4803 AUDIO_POLICY_FORCE_BT_SCO) &&
4804 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4805 AUDIO_POLICY_FORCE_BT_SCO) &&
4806 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4807 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
4808
4809 mpClientInterface->restoreOutput(a2dpOutput);
4810 mA2dpSuspended = false;
4811 }
4812 } else {
4813 if (isScoConnected &&
4814 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4815 AUDIO_POLICY_FORCE_BT_SCO) ||
4816 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4817 AUDIO_POLICY_FORCE_BT_SCO) ||
4818 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4819 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
4820
4821 mpClientInterface->suspendOutput(a2dpOutput);
4822 mA2dpSuspended = true;
4823 }
4824 }
4825 }
4826
4827 audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4828 bool fromCache)
4829 {
4830 audio_devices_t device = AUDIO_DEVICE_NONE;
4831
4832 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
4833 if (index >= 0) {
4834 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4835 if (patchDesc->mUid != mUidCached) {
4836 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4837 outputDesc->device(), outputDesc->getPatchHandle());
4838 return outputDesc->device();
4839 }
4840 }
4841
4842 // Check if an explicit routing request exists for an active stream on this output and
4843 // use it in priority before any other rule
4844 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4845 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4846 audio_devices_t forcedDevice =
4847 mOutputRoutes.getActiveDeviceForStream(
4848 (audio_stream_type_t)stream, mAvailableOutputDevices);
4849
4850 if (forcedDevice != AUDIO_DEVICE_NONE) {
4851 return forcedDevice;
4852 }
4853 }
4854 }
4855
4856 // check the following by order of priority to request a routing change if necessary:
4857 // 1: the strategy enforced audible is active and enforced on the output:
4858 // use device for strategy enforced audible
4859 // 2: we are in call or the strategy phone is active on the output:
4860 // use device for strategy phone
4861 // 3: the strategy sonification is active on the output:
4862 // use device for strategy sonification
4863 // 4: the strategy for enforced audible is active but not enforced on the output:
4864 // use the device for strategy enforced audible
4865 // 5: the strategy accessibility is active on the output:
4866 // use device for strategy accessibility
4867 // 6: the strategy "respectful" sonification is active on the output:
4868 // use device for strategy "respectful" sonification
4869 // 7: the strategy media is active on the output:
4870 // use device for strategy media
4871 // 8: the strategy DTMF is active on the output:
4872 // use device for strategy DTMF
4873 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
4874 // use device for strategy t-t-s
4875 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
4876 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
4877 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4878 } else if (isInCall() ||
4879 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
4880 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
4881 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
4882 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4883 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4884 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4885 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4886 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
4887 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
4888 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
4889 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
4890 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4891 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
4892 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
4893 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4894 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
4895 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
4896 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
4897 }
4898
4899 ALOGV("getNewOutputDevice() selected device %x", device);
4900 return device;
4901 }
4902
4903 audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
4904 {
4905 audio_devices_t device = AUDIO_DEVICE_NONE;
4906
4907 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
4908 if (index >= 0) {
4909 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4910 if (patchDesc->mUid != mUidCached) {
4911 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4912 inputDesc->mDevice, inputDesc->getPatchHandle());
4913 return inputDesc->mDevice;
4914 }
4915 }
4916
4917 // If we are not in call and no client is active on this input, this methods returns
4918 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
4919 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4920 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4921 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4922 }
4923 if (source != AUDIO_SOURCE_DEFAULT) {
4924 device = getDeviceAndMixForInputSource(source);
4925 }
4926
4927 return device;
4928 }
4929
4930 bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4931 audio_stream_type_t stream2) {
4932 return (stream1 == stream2);
4933 }
4934
4935 uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
4936 return (uint32_t)getStrategy(stream);
4937 }
4938
4939 audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
4940 // By checking the range of stream before calling getStrategy, we avoid
4941 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4942 // and then return STRATEGY_MEDIA, but we want to return the empty set.
4943 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
4944 return AUDIO_DEVICE_NONE;
4945 }
4946 audio_devices_t devices = AUDIO_DEVICE_NONE;
4947 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4948 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
4949 continue;
4950 }
4951 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
4952 audio_devices_t curDevices =
4953 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
4954 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4955 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
4956 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
4957 curDevices |= outputDesc->device();
4958 }
4959 }
4960 devices |= curDevices;
4961 }
4962
4963 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4964 and doesn't really need to.*/
4965 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4966 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4967 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4968 }
4969 return devices;
4970 }
4971
4972 routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4973 {
4974 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4975 return mEngine->getStrategyForStream(stream);
4976 }
4977
4978 uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4979 // flags to strategy mapping
4980 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4981 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4982 }
4983 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4984 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4985 }
4986 // usage to strategy mapping
4987 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
4988 }
4989
4990 void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
4991 switch(stream) {
4992 case AUDIO_STREAM_MUSIC:
4993 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4994 updateDevicesAndOutputs();
4995 break;
4996 default:
4997 break;
4998 }
4999 }
5000
5001 uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
5002
5003 // skip beacon mute management if a dedicated TTS output is available
5004 if (mTtsOutputAvailable) {
5005 return 0;
5006 }
5007
5008 switch(event) {
5009 case STARTING_OUTPUT:
5010 mBeaconMuteRefCount++;
5011 break;
5012 case STOPPING_OUTPUT:
5013 if (mBeaconMuteRefCount > 0) {
5014 mBeaconMuteRefCount--;
5015 }
5016 break;
5017 case STARTING_BEACON:
5018 mBeaconPlayingRefCount++;
5019 break;
5020 case STOPPING_BEACON:
5021 if (mBeaconPlayingRefCount > 0) {
5022 mBeaconPlayingRefCount--;
5023 }
5024 break;
5025 }
5026
5027 if (mBeaconMuteRefCount > 0) {
5028 // any playback causes beacon to be muted
5029 return setBeaconMute(true);
5030 } else {
5031 // no other playback: unmute when beacon starts playing, mute when it stops
5032 return setBeaconMute(mBeaconPlayingRefCount == 0);
5033 }
5034 }
5035
5036 uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5037 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5038 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5039 // keep track of muted state to avoid repeating mute/unmute operations
5040 if (mBeaconMuted != mute) {
5041 // mute/unmute AUDIO_STREAM_TTS on all outputs
5042 ALOGV("\t muting %d", mute);
5043 uint32_t maxLatency = 0;
5044 for (size_t i = 0; i < mOutputs.size(); i++) {
5045 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5046 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
5047 desc,
5048 0 /*delay*/, AUDIO_DEVICE_NONE);
5049 const uint32_t latency = desc->latency() * 2;
5050 if (latency > maxLatency) {
5051 maxLatency = latency;
5052 }
5053 }
5054 mBeaconMuted = mute;
5055 return maxLatency;
5056 }
5057 return 0;
5058 }
5059
5060 audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
5061 bool fromCache)
5062 {
5063 // Check if an explicit routing request exists for a stream type corresponding to the
5064 // specified strategy and use it in priority over default routing rules.
5065 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5066 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5067 audio_devices_t forcedDevice =
5068 mOutputRoutes.getActiveDeviceForStream(
5069 (audio_stream_type_t)stream, mAvailableOutputDevices);
5070 if (forcedDevice != AUDIO_DEVICE_NONE) {
5071 return forcedDevice;
5072 }
5073 }
5074 }
5075
5076 if (fromCache) {
5077 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5078 strategy, mDeviceForStrategy[strategy]);
5079 return mDeviceForStrategy[strategy];
5080 }
5081 return mEngine->getDeviceForStrategy(strategy);
5082 }
5083
5084 void AudioPolicyManager::updateDevicesAndOutputs()
5085 {
5086 for (int i = 0; i < NUM_STRATEGIES; i++) {
5087 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5088 }
5089 mPreviousOutputs = mOutputs;
5090 }
5091
5092 uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
5093 audio_devices_t prevDevice,
5094 uint32_t delayMs)
5095 {
5096 // mute/unmute strategies using an incompatible device combination
5097 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5098 // if unmuting, unmute only after the specified delay
5099 if (outputDesc->isDuplicated()) {
5100 return 0;
5101 }
5102
5103 uint32_t muteWaitMs = 0;
5104 audio_devices_t device = outputDesc->device();
5105 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
5106
5107 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5108 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5109 curDevice = curDevice & outputDesc->supportedDevices();
5110 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5111 bool doMute = false;
5112
5113 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5114 doMute = true;
5115 outputDesc->mStrategyMutedByDevice[i] = true;
5116 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5117 doMute = true;
5118 outputDesc->mStrategyMutedByDevice[i] = false;
5119 }
5120 if (doMute) {
5121 for (size_t j = 0; j < mOutputs.size(); j++) {
5122 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
5123 // skip output if it does not share any device with current output
5124 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5125 == AUDIO_DEVICE_NONE) {
5126 continue;
5127 }
5128 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
5129 mute ? "muting" : "unmuting", i, curDevice);
5130 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
5131 if (isStrategyActive(desc, (routing_strategy)i)) {
5132 if (mute) {
5133 // FIXME: should not need to double latency if volume could be applied
5134 // immediately by the audioflinger mixer. We must account for the delay
5135 // between now and the next time the audioflinger thread for this output
5136 // will process a buffer (which corresponds to one buffer size,
5137 // usually 1/2 or 1/4 of the latency).
5138 if (muteWaitMs < desc->latency() * 2) {
5139 muteWaitMs = desc->latency() * 2;
5140 }
5141 }
5142 }
5143 }
5144 }
5145 }
5146
5147 // temporary mute output if device selection changes to avoid volume bursts due to
5148 // different per device volumes
5149 if (outputDesc->isActive() && (device != prevDevice)) {
5150 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5151 // temporary mute duration is conservatively set to 4 times the reported latency
5152 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5153 if (muteWaitMs < tempMuteWaitMs) {
5154 muteWaitMs = tempMuteWaitMs;
5155 }
5156
5157 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5158 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
5159 // make sure that we do not start the temporary mute period too early in case of
5160 // delayed device change
5161 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
5162 setStrategyMute((routing_strategy)i, false, outputDesc,
5163 delayMs + tempMuteDurationMs, device);
5164 }
5165 }
5166 }
5167
5168 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5169 if (muteWaitMs > delayMs) {
5170 muteWaitMs -= delayMs;
5171 usleep(muteWaitMs * 1000);
5172 return muteWaitMs;
5173 }
5174 return 0;
5175 }
5176
5177 uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
5178 audio_devices_t device,
5179 bool force,
5180 int delayMs,
5181 audio_patch_handle_t *patchHandle,
5182 const char *address,
5183 bool requiresMuteCheck)
5184 {
5185 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
5186 AudioParameter param;
5187 uint32_t muteWaitMs;
5188
5189 if (outputDesc->isDuplicated()) {
5190 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5191 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5192 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5193 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5194 return muteWaitMs;
5195 }
5196 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5197 // output profile
5198 if ((device != AUDIO_DEVICE_NONE) &&
5199 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
5200 return 0;
5201 }
5202
5203 // filter devices according to output selected
5204 device = (audio_devices_t)(device & outputDesc->supportedDevices());
5205
5206 audio_devices_t prevDevice = outputDesc->mDevice;
5207
5208 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
5209
5210 if (device != AUDIO_DEVICE_NONE) {
5211 outputDesc->mDevice = device;
5212 }
5213
5214 // if the outputs are not materially active, there is no need to mute.
5215 if (requiresMuteCheck) {
5216 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5217 } else {
5218 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5219 muteWaitMs = 0;
5220 }
5221
5222 // Do not change the routing if:
5223 // the requested device is AUDIO_DEVICE_NONE
5224 // OR the requested device is the same as current device
5225 // AND force is not specified
5226 // AND the output is connected by a valid audio patch.
5227 // Doing this check here allows the caller to call setOutputDevice() without conditions
5228 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5229 !force &&
5230 outputDesc->getPatchHandle() != 0) {
5231 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
5232 return muteWaitMs;
5233 }
5234
5235 ALOGV("setOutputDevice() changing device");
5236
5237 // do the routing
5238 if (device == AUDIO_DEVICE_NONE) {
5239 resetOutputDevice(outputDesc, delayMs, NULL);
5240 } else {
5241 DeviceVector deviceList;
5242 if ((address == NULL) || (strlen(address) == 0)) {
5243 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5244 } else {
5245 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5246 }
5247
5248 if (!deviceList.isEmpty()) {
5249 struct audio_patch patch;
5250 outputDesc->toAudioPortConfig(&patch.sources[0]);
5251 patch.num_sources = 1;
5252 patch.num_sinks = 0;
5253 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5254 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
5255 patch.num_sinks++;
5256 }
5257 ssize_t index;
5258 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5259 index = mAudioPatches.indexOfKey(*patchHandle);
5260 } else {
5261 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
5262 }
5263 sp< AudioPatch> patchDesc;
5264 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5265 if (index >= 0) {
5266 patchDesc = mAudioPatches.valueAt(index);
5267 afPatchHandle = patchDesc->mAfPatchHandle;
5268 }
5269
5270 status_t status = mpClientInterface->createAudioPatch(&patch,
5271 &afPatchHandle,
5272 delayMs);
5273 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5274 "num_sources %d num_sinks %d",
5275 status, afPatchHandle, patch.num_sources, patch.num_sinks);
5276 if (status == NO_ERROR) {
5277 if (index < 0) {
5278 patchDesc = new AudioPatch(&patch, mUidCached);
5279 addAudioPatch(patchDesc->mHandle, patchDesc);
5280 } else {
5281 patchDesc->mPatch = patch;
5282 }
5283 patchDesc->mAfPatchHandle = afPatchHandle;
5284 if (patchHandle) {
5285 *patchHandle = patchDesc->mHandle;
5286 }
5287 outputDesc->setPatchHandle(patchDesc->mHandle);
5288 nextAudioPortGeneration();
5289 mpClientInterface->onAudioPatchListUpdate();
5290 }
5291 }
5292
5293 // inform all input as well
5294 for (size_t i = 0; i < mInputs.size(); i++) {
5295 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
5296 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
5297 AudioParameter inputCmd = AudioParameter();
5298 ALOGV("%s: inform input %d of device:%d", __func__,
5299 inputDescriptor->mIoHandle, device);
5300 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5301 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5302 inputCmd.toString(),
5303 delayMs);
5304 }
5305 }
5306 }
5307
5308 // update stream volumes according to new device
5309 applyStreamVolumes(outputDesc, device, delayMs);
5310
5311 return muteWaitMs;
5312 }
5313
5314 status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
5315 int delayMs,
5316 audio_patch_handle_t *patchHandle)
5317 {
5318 ssize_t index;
5319 if (patchHandle) {
5320 index = mAudioPatches.indexOfKey(*patchHandle);
5321 } else {
5322 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
5323 }
5324 if (index < 0) {
5325 return INVALID_OPERATION;
5326 }
5327 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5328 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
5329 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5330 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
5331 removeAudioPatch(patchDesc->mHandle);
5332 nextAudioPortGeneration();
5333 mpClientInterface->onAudioPatchListUpdate();
5334 return status;
5335 }
5336
5337 status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5338 audio_devices_t device,
5339 bool force,
5340 audio_patch_handle_t *patchHandle)
5341 {
5342 status_t status = NO_ERROR;
5343
5344 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5345 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5346 inputDesc->mDevice = device;
5347
5348 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5349 if (!deviceList.isEmpty()) {
5350 struct audio_patch patch;
5351 inputDesc->toAudioPortConfig(&patch.sinks[0]);
5352 // AUDIO_SOURCE_HOTWORD is for internal use only:
5353 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
5354 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5355 !inputDesc->isSoundTrigger()) {
5356 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5357 }
5358 patch.num_sinks = 1;
5359 //only one input device for now
5360 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
5361 patch.num_sources = 1;
5362 ssize_t index;
5363 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5364 index = mAudioPatches.indexOfKey(*patchHandle);
5365 } else {
5366 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
5367 }
5368 sp< AudioPatch> patchDesc;
5369 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5370 if (index >= 0) {
5371 patchDesc = mAudioPatches.valueAt(index);
5372 afPatchHandle = patchDesc->mAfPatchHandle;
5373 }
5374
5375 status_t status = mpClientInterface->createAudioPatch(&patch,
5376 &afPatchHandle,
5377 0);
5378 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
5379 status, afPatchHandle);
5380 if (status == NO_ERROR) {
5381 if (index < 0) {
5382 patchDesc = new AudioPatch(&patch, mUidCached);
5383 addAudioPatch(patchDesc->mHandle, patchDesc);
5384 } else {
5385 patchDesc->mPatch = patch;
5386 }
5387 patchDesc->mAfPatchHandle = afPatchHandle;
5388 if (patchHandle) {
5389 *patchHandle = patchDesc->mHandle;
5390 }
5391 inputDesc->setPatchHandle(patchDesc->mHandle);
5392 nextAudioPortGeneration();
5393 mpClientInterface->onAudioPatchListUpdate();
5394 }
5395 }
5396 }
5397 return status;
5398 }
5399
5400 status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5401 audio_patch_handle_t *patchHandle)
5402 {
5403 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5404 ssize_t index;
5405 if (patchHandle) {
5406 index = mAudioPatches.indexOfKey(*patchHandle);
5407 } else {
5408 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
5409 }
5410 if (index < 0) {
5411 return INVALID_OPERATION;
5412 }
5413 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5414 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
5415 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5416 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
5417 removeAudioPatch(patchDesc->mHandle);
5418 nextAudioPortGeneration();
5419 mpClientInterface->onAudioPatchListUpdate();
5420 return status;
5421 }
5422
5423 sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
5424 const String8& address,
5425 uint32_t& samplingRate,
5426 audio_format_t& format,
5427 audio_channel_mask_t& channelMask,
5428 audio_input_flags_t flags)
5429 {
5430 // Choose an input profile based on the requested capture parameters: select the first available
5431 // profile supporting all requested parameters.
5432 //
5433 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5434 // the best matching profile, not the first one.
5435
5436 sp<IOProfile> firstInexact;
5437 uint32_t updatedSamplingRate = 0;
5438 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5439 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
5440 for (const auto& hwModule : mHwModules) {
5441 for (const auto& profile : hwModule->getInputProfiles()) {
5442 // profile->log();
5443 //updatedFormat = format;
5444 if (profile->isCompatibleProfile(device, address, samplingRate,
5445 &samplingRate /*updatedSamplingRate*/,
5446 format,
5447 &format, /*updatedFormat*/
5448 channelMask,
5449 &channelMask /*updatedChannelMask*/,
5450 // FIXME ugly cast
5451 (audio_output_flags_t) flags,
5452 true /*exactMatchRequiredForInputFlags*/)) {
5453 return profile;
5454 }
5455 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5456 samplingRate,
5457 &updatedSamplingRate,
5458 format,
5459 &updatedFormat,
5460 channelMask,
5461 &updatedChannelMask,
5462 // FIXME ugly cast
5463 (audio_output_flags_t) flags,
5464 false /*exactMatchRequiredForInputFlags*/)) {
5465 firstInexact = profile;
5466 }
5467
5468 }
5469 }
5470 if (firstInexact != nullptr) {
5471 samplingRate = updatedSamplingRate;
5472 format = updatedFormat;
5473 channelMask = updatedChannelMask;
5474 return firstInexact;
5475 }
5476 return NULL;
5477 }
5478
5479
5480 audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
5481 AudioMix **policyMix)
5482 {
5483 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5484 audio_devices_t selectedDeviceFromMix =
5485 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
5486
5487 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5488 return selectedDeviceFromMix;
5489 }
5490 return getDeviceForInputSource(inputSource);
5491 }
5492
5493 audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5494 {
5495 // Routing
5496 // Scan the whole RouteMap to see if we have an explicit route:
5497 // if the input source in the RouteMap is the same as the argument above,
5498 // and activity count is non-zero and the device in the route descriptor is available
5499 // then select this device.
5500 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5501 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
5502 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
5503 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
5504 return route->mDeviceDescriptor->type();
5505 }
5506 }
5507
5508 return mEngine->getDeviceForInputSource(inputSource);
5509 }
5510
5511 float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
5512 int index,
5513 audio_devices_t device)
5514 {
5515 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
5516
5517 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5518 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5519 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5520 // the ringtone volume
5521 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5522 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5523 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5524 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5525 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5526 }
5527
5528 // in-call: always cap earpiece volume by voice volume + some low headroom
5529 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5530 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
5531 switch (stream) {
5532 case AUDIO_STREAM_SYSTEM:
5533 case AUDIO_STREAM_RING:
5534 case AUDIO_STREAM_MUSIC:
5535 case AUDIO_STREAM_ALARM:
5536 case AUDIO_STREAM_NOTIFICATION:
5537 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5538 case AUDIO_STREAM_DTMF:
5539 case AUDIO_STREAM_ACCESSIBILITY: {
5540 int voiceVolumeIndex =
5541 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5542 const float maxVoiceVolDb =
5543 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5544 + IN_CALL_EARPIECE_HEADROOM_DB;
5545 if (volumeDB > maxVoiceVolDb) {
5546 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5547 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5548 volumeDB = maxVoiceVolDb;
5549 }
5550 } break;
5551 default:
5552 break;
5553 }
5554 }
5555
5556 // if a headset is connected, apply the following rules to ring tones and notifications
5557 // to avoid sound level bursts in user's ears:
5558 // - always attenuate notifications volume by 6dB
5559 // - attenuate ring tones volume by 6dB unless music is not playing and
5560 // speaker is part of the select devices
5561 // - if music is playing, always limit the volume to current music volume,
5562 // with a minimum threshold at -36dB so that notification is always perceived.
5563 const routing_strategy stream_strategy = getStrategy(stream);
5564 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5565 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5566 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5567 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5568 AUDIO_DEVICE_OUT_USB_HEADSET |
5569 AUDIO_DEVICE_OUT_HEARING_AID)) &&
5570 ((stream_strategy == STRATEGY_SONIFICATION)
5571 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
5572 || (stream == AUDIO_STREAM_SYSTEM)
5573 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
5574 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
5575 mVolumeCurves->canBeMuted(stream)) {
5576 // when the phone is ringing we must consider that music could have been paused just before
5577 // by the music application and behave as if music was active if the last music track was
5578 // just stopped
5579 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
5580 mLimitRingtoneVolume) {
5581 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
5582 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
5583 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
5584 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5585 musicDevice),
5586 musicDevice);
5587 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5588 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
5589 if (volumeDB > minVolDB) {
5590 volumeDB = minVolDB;
5591 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
5592 }
5593 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5594 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5595 // on A2DP, also ensure notification volume is not too low compared to media when
5596 // intended to be played
5597 if ((volumeDB > -96.0f) &&
5598 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5599 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5600 stream, device,
5601 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5602 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5603 }
5604 }
5605 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5606 stream_strategy != STRATEGY_SONIFICATION) {
5607 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
5608 }
5609 }
5610
5611 return volumeDB;
5612 }
5613
5614 status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
5615 int index,
5616 const sp<AudioOutputDescriptor>& outputDesc,
5617 audio_devices_t device,
5618 int delayMs,
5619 bool force)
5620 {
5621 // do not change actual stream volume if the stream is muted
5622 if (outputDesc->mMuteCount[stream] != 0) {
5623 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5624 stream, outputDesc->mMuteCount[stream]);
5625 return NO_ERROR;
5626 }
5627 audio_policy_forced_cfg_t forceUseForComm =
5628 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
5629 // do not change in call volume if bluetooth is connected and vice versa
5630 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5631 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
5632 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
5633 stream, forceUseForComm);
5634 return INVALID_OPERATION;
5635 }
5636
5637 if (device == AUDIO_DEVICE_NONE) {
5638 device = outputDesc->device();
5639 }
5640
5641 float volumeDb = computeVolume(stream, index, device);
5642 if (outputDesc->isFixedVolume(device) ||
5643 // Force VoIP volume to max for bluetooth SCO
5644 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5645 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
5646 volumeDb = 0.0f;
5647 }
5648
5649 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
5650
5651 if (stream == AUDIO_STREAM_VOICE_CALL ||
5652 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5653 float voiceVolume;
5654 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
5655 if (stream == AUDIO_STREAM_VOICE_CALL) {
5656 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
5657 } else {
5658 voiceVolume = 1.0;
5659 }
5660
5661 if (voiceVolume != mLastVoiceVolume) {
5662 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5663 mLastVoiceVolume = voiceVolume;
5664 }
5665 }
5666
5667 return NO_ERROR;
5668 }
5669
5670 void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5671 audio_devices_t device,
5672 int delayMs,
5673 bool force)
5674 {
5675 ALOGVV("applyStreamVolumes() for device %08x", device);
5676
5677 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5678 checkAndSetVolume((audio_stream_type_t)stream,
5679 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
5680 outputDesc,
5681 device,
5682 delayMs,
5683 force);
5684 }
5685 }
5686
5687 void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
5688 bool on,
5689 const sp<AudioOutputDescriptor>& outputDesc,
5690 int delayMs,
5691 audio_devices_t device)
5692 {
5693 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5694 strategy, on, outputDesc->getId());
5695 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5696 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5697 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
5698 }
5699 }
5700 }
5701
5702 void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
5703 bool on,
5704 const sp<AudioOutputDescriptor>& outputDesc,
5705 int delayMs,
5706 audio_devices_t device)
5707 {
5708 if (device == AUDIO_DEVICE_NONE) {
5709 device = outputDesc->device();
5710 }
5711
5712 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5713 stream, on, outputDesc->mMuteCount[stream], device);
5714
5715 if (on) {
5716 if (outputDesc->mMuteCount[stream] == 0) {
5717 if (mVolumeCurves->canBeMuted(stream) &&
5718 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5719 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
5720 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
5721 }
5722 }
5723 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5724 outputDesc->mMuteCount[stream]++;
5725 } else {
5726 if (outputDesc->mMuteCount[stream] == 0) {
5727 ALOGV("setStreamMute() unmuting non muted stream!");
5728 return;
5729 }
5730 if (--outputDesc->mMuteCount[stream] == 0) {
5731 checkAndSetVolume(stream,
5732 mVolumeCurves->getVolumeIndex(stream, device),
5733 outputDesc,
5734 device,
5735 delayMs);
5736 }
5737 }
5738 }
5739
5740 void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
5741 bool starting, bool stateChange)
5742 {
5743 if(!hasPrimaryOutput()) {
5744 return;
5745 }
5746
5747 // if the stream pertains to sonification strategy and we are in call we must
5748 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5749 // in the device used for phone strategy and play the tone if the selected device does not
5750 // interfere with the device used for phone strategy
5751 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5752 // many times as there are active tracks on the output
5753 const routing_strategy stream_strategy = getStrategy(stream);
5754 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5755 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
5756 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
5757 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5758 stream, starting, outputDesc->mDevice, stateChange);
5759 if (outputDesc->mRefCount[stream]) {
5760 int muteCount = 1;
5761 if (stateChange) {
5762 muteCount = outputDesc->mRefCount[stream];
5763 }
5764 if (audio_is_low_visibility(stream)) {
5765 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5766 for (int i = 0; i < muteCount; i++) {
5767 setStreamMute(stream, starting, mPrimaryOutput);
5768 }
5769 } else {
5770 ALOGV("handleIncallSonification() high visibility");
5771 if (outputDesc->device() &
5772 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5773 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5774 for (int i = 0; i < muteCount; i++) {
5775 setStreamMute(stream, starting, mPrimaryOutput);
5776 }
5777 }
5778 if (starting) {
5779 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5780 AUDIO_STREAM_VOICE_CALL);
5781 } else {
5782 mpClientInterface->stopTone();
5783 }
5784 }
5785 }
5786 }
5787 }
5788
5789 audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5790 {
5791 // flags to stream type mapping
5792 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5793 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5794 }
5795 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5796 return AUDIO_STREAM_BLUETOOTH_SCO;
5797 }
5798 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5799 return AUDIO_STREAM_TTS;
5800 }
5801
5802 // usage to stream type mapping
5803 switch (attr->usage) {
5804 case AUDIO_USAGE_MEDIA:
5805 case AUDIO_USAGE_GAME:
5806 case AUDIO_USAGE_ASSISTANT:
5807 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5808 return AUDIO_STREAM_MUSIC;
5809 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5810 return AUDIO_STREAM_ACCESSIBILITY;
5811 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5812 return AUDIO_STREAM_SYSTEM;
5813 case AUDIO_USAGE_VOICE_COMMUNICATION:
5814 return AUDIO_STREAM_VOICE_CALL;
5815
5816 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5817 return AUDIO_STREAM_DTMF;
5818
5819 case AUDIO_USAGE_ALARM:
5820 return AUDIO_STREAM_ALARM;
5821 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5822 return AUDIO_STREAM_RING;
5823
5824 case AUDIO_USAGE_NOTIFICATION:
5825 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5826 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5827 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5828 case AUDIO_USAGE_NOTIFICATION_EVENT:
5829 return AUDIO_STREAM_NOTIFICATION;
5830
5831 case AUDIO_USAGE_UNKNOWN:
5832 default:
5833 return AUDIO_STREAM_MUSIC;
5834 }
5835 }
5836
5837 bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5838 {
5839 // has flags that map to a strategy?
5840 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5841 return true;
5842 }
5843
5844 // has known usage?
5845 switch (paa->usage) {
5846 case AUDIO_USAGE_UNKNOWN:
5847 case AUDIO_USAGE_MEDIA:
5848 case AUDIO_USAGE_VOICE_COMMUNICATION:
5849 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5850 case AUDIO_USAGE_ALARM:
5851 case AUDIO_USAGE_NOTIFICATION:
5852 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5853 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5854 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5855 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5856 case AUDIO_USAGE_NOTIFICATION_EVENT:
5857 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5858 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5859 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5860 case AUDIO_USAGE_GAME:
5861 case AUDIO_USAGE_VIRTUAL_SOURCE:
5862 case AUDIO_USAGE_ASSISTANT:
5863 break;
5864 default:
5865 return false;
5866 }
5867 return true;
5868 }
5869
5870 bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
5871 routing_strategy strategy, uint32_t inPastMs,
5872 nsecs_t sysTime) const
5873 {
5874 if ((sysTime == 0) && (inPastMs != 0)) {
5875 sysTime = systemTime();
5876 }
5877 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
5878 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5879 (NUM_STRATEGIES == strategy)) &&
5880 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5881 return true;
5882 }
5883 }
5884 return false;
5885 }
5886
5887 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5888 {
5889 return mEngine->getForceUse(usage);
5890 }
5891
5892 bool AudioPolicyManager::isInCall()
5893 {
5894 return isStateInCall(mEngine->getPhoneState());
5895 }
5896
5897 bool AudioPolicyManager::isStateInCall(int state)
5898 {
5899 return is_state_in_call(state);
5900 }
5901
5902 void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5903 {
5904 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5905 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5906 if (sourceDesc->mDevice->equals(deviceDesc)) {
5907 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5908 stopAudioSource(sourceDesc->getHandle());
5909 }
5910 }
5911
5912 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5913 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5914 bool release = false;
5915 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5916 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5917 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5918 source->ext.device.type == deviceDesc->type()) {
5919 release = true;
5920 }
5921 }
5922 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5923 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5924 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5925 sink->ext.device.type == deviceDesc->type()) {
5926 release = true;
5927 }
5928 }
5929 if (release) {
5930 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5931 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5932 }
5933 }
5934 }
5935
5936 // Modify the list of surround sound formats supported.
5937 void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5938 FormatVector &formats = *formatsPtr;
5939 // TODO Set this based on Config properties.
5940 const bool alwaysForceAC3 = true;
5941
5942 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5943 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5944 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
5945
5946 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5947 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5948 formats.clear();
5949 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5950 formats.add(*it);
5951 }
5952 // Always enable IEC61937 when in MANUAL mode.
5953 formats.add(AUDIO_FORMAT_IEC61937);
5954 } else { // NEVER, AUTO or ALWAYS
5955 // Analyze original support for various formats.
5956 bool supportsAC3 = false;
5957 bool supportsOtherSurround = false;
5958 bool supportsIEC61937 = false;
5959 mSurroundFormats.clear();
5960 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5961 audio_format_t format = formats[formatIndex];
5962 switch (format) {
5963 case AUDIO_FORMAT_AC3:
5964 supportsAC3 = true;
5965 break;
5966 case AUDIO_FORMAT_E_AC3:
5967 case AUDIO_FORMAT_DTS:
5968 case AUDIO_FORMAT_DTS_HD:
5969 // If ALWAYS, remove all other surround formats here
5970 // since we will add them later.
5971 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5972 formats.removeAt(formatIndex);
5973 formatIndex--;
5974 }
5975 supportsOtherSurround = true;
5976 break;
5977 case AUDIO_FORMAT_IEC61937:
5978 supportsIEC61937 = true;
5979 break;
5980 default:
5981 break;
5982 }
5983 }
5984
5985 // Modify formats based on surround preferences.
5986 // If NEVER, remove support for surround formats.
5987 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5988 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5989 // Remove surround sound related formats.
5990 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5991 audio_format_t format = formats[formatIndex];
5992 switch(format) {
5993 case AUDIO_FORMAT_AC3:
5994 case AUDIO_FORMAT_E_AC3:
5995 case AUDIO_FORMAT_DTS:
5996 case AUDIO_FORMAT_DTS_HD:
5997 case AUDIO_FORMAT_IEC61937:
5998 formats.removeAt(formatIndex);
5999 break;
6000 default:
6001 formatIndex++; // keep it
6002 break;
6003 }
6004 }
6005 supportsAC3 = false;
6006 supportsOtherSurround = false;
6007 supportsIEC61937 = false;
6008 }
6009 } else { // AUTO or ALWAYS
6010 // Most TVs support AC3 even if they do not report it in the EDID.
6011 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6012 && !supportsAC3) {
6013 formats.add(AUDIO_FORMAT_AC3);
6014 supportsAC3 = true;
6015 }
6016
6017 // If ALWAYS, add support for raw surround formats if all are missing.
6018 // This assumes that if any of these formats are reported by the HAL
6019 // then the report is valid and should not be modified.
6020 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6021 formats.add(AUDIO_FORMAT_E_AC3);
6022 formats.add(AUDIO_FORMAT_DTS);
6023 formats.add(AUDIO_FORMAT_DTS_HD);
6024 supportsOtherSurround = true;
6025 }
6026
6027 // Add support for IEC61937 if any raw surround supported.
6028 // The HAL could do this but add it here, just in case.
6029 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6030 formats.add(AUDIO_FORMAT_IEC61937);
6031 supportsIEC61937 = true;
6032 }
6033
6034 // Add reported surround sound formats to enabled surround formats.
6035 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
6036 audio_format_t format = formats[formatIndex];
6037 switch(format) {
6038 case AUDIO_FORMAT_AC3:
6039 case AUDIO_FORMAT_E_AC3:
6040 case AUDIO_FORMAT_DTS:
6041 case AUDIO_FORMAT_DTS_HD:
6042 case AUDIO_FORMAT_AAC_LC:
6043 case AUDIO_FORMAT_DOLBY_TRUEHD:
6044 case AUDIO_FORMAT_E_AC3_JOC:
6045 mSurroundFormats.insert(format);
6046 default:
6047 break;
6048 }
6049 }
6050 }
6051 }
6052 }
6053
6054 // Modify the list of channel masks supported.
6055 void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6056 ChannelsVector &channelMasks = *channelMasksPtr;
6057 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6058 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6059
6060 // If NEVER, then remove support for channelMasks > stereo.
6061 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6062 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6063 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6064 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6065 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6066 channelMasks.removeAt(maskIndex);
6067 } else {
6068 maskIndex++;
6069 }
6070 }
6071 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6072 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6073 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
6074 bool supports5dot1 = false;
6075 // Are there any channel masks that can be considered "surround"?
6076 for (audio_channel_mask_t channelMask : channelMasks) {
6077 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6078 supports5dot1 = true;
6079 break;
6080 }
6081 }
6082 // If not then add 5.1 support.
6083 if (!supports5dot1) {
6084 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6085 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6086 }
6087 }
6088 }
6089
6090 void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6091 audio_io_handle_t ioHandle,
6092 AudioProfileVector &profiles)
6093 {
6094 String8 reply;
6095
6096 // Format MUST be checked first to update the list of AudioProfile
6097 if (profiles.hasDynamicFormat()) {
6098 reply = mpClientInterface->getParameters(
6099 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
6100 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
6101 AudioParameter repliedParameters(reply);
6102 if (repliedParameters.get(
6103 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
6104 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6105 return;
6106 }
6107 FormatVector formats = formatsFromString(reply.string());
6108 if (device == AUDIO_DEVICE_OUT_HDMI) {
6109 filterSurroundFormats(&formats);
6110 }
6111 profiles.setFormats(formats);
6112 }
6113
6114 for (audio_format_t format : profiles.getSupportedFormats()) {
6115 ChannelsVector channelMasks;
6116 SampleRateVector samplingRates;
6117 AudioParameter requestedParameters;
6118 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
6119
6120 if (profiles.hasDynamicRateFor(format)) {
6121 reply = mpClientInterface->getParameters(
6122 ioHandle,
6123 requestedParameters.toString() + ";" +
6124 AudioParameter::keyStreamSupportedSamplingRates);
6125 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
6126 AudioParameter repliedParameters(reply);
6127 if (repliedParameters.get(
6128 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
6129 samplingRates = samplingRatesFromString(reply.string());
6130 }
6131 }
6132 if (profiles.hasDynamicChannelsFor(format)) {
6133 reply = mpClientInterface->getParameters(ioHandle,
6134 requestedParameters.toString() + ";" +
6135 AudioParameter::keyStreamSupportedChannels);
6136 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
6137 AudioParameter repliedParameters(reply);
6138 if (repliedParameters.get(
6139 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
6140 channelMasks = channelMasksFromString(reply.string());
6141 if (device == AUDIO_DEVICE_OUT_HDMI) {
6142 filterSurroundChannelMasks(&channelMasks);
6143 }
6144 }
6145 }
6146 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
6147 }
6148 }
6149
6150 } // namespace android
6151