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