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