• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <type_traits>
38 #include <unordered_set>
39 #include <vector>
40 
41 #include <Serializer.h>
42 #include <android/media/audio/common/AudioMMapPolicy.h>
43 #include <android/media/audio/common/AudioPort.h>
44 #include <com_android_media_audio.h>
45 #include <android_media_audiopolicy.h>
46 #include <com_android_media_audioserver.h>
47 #include <cutils/bitops.h>
48 #include <error/expected_utils.h>
49 #include <media/AudioParameter.h>
50 #include <policy.h>
51 #include <private/android_filesystem_config.h>
52 #include <system/audio.h>
53 #include <system/audio_config.h>
54 #include <system/audio_effects/effect_hapticgenerator.h>
55 #include <utils/Log.h>
56 
57 #include "AudioPolicyManager.h"
58 #include "SpatializerHelper.h"
59 #include "TypeConverter.h"
60 
61 namespace android {
62 
63 
64 namespace audio_flags = android::media::audiopolicy;
65 
66 using android::media::audio::common::AudioDevice;
67 using android::media::audio::common::AudioDeviceAddress;
68 using android::media::audio::common::AudioDeviceDescription;
69 using android::media::audio::common::AudioMMapPolicy;
70 using android::media::audio::common::AudioMMapPolicyInfo;
71 using android::media::audio::common::AudioMMapPolicyType;
72 using android::media::audio::common::AudioPortDeviceExt;
73 using android::media::audio::common::AudioPortExt;
74 using android::media::audio::common::AudioConfigBase;
75 using binder::Status;
76 using com::android::media::audioserver::fix_call_audio_patch;
77 using content::AttributionSourceState;
78 
79 //FIXME: workaround for truncated touch sounds
80 // to be removed when the problem is handled by system UI
81 #define TOUCH_SOUND_FIXED_DELAY_MS 100
82 
83 // Largest difference in dB on earpiece in call between the voice volume and another
84 // media / notification / system volume.
85 constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
86 
87 template <typename T>
operator ==(const SortedVector<T> & left,const SortedVector<T> & right)88 bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
89 {
90     if (left.size() != right.size()) {
91         return false;
92     }
93     for (size_t index = 0; index < right.size(); index++) {
94         if (left[index] != right[index]) {
95             return false;
96         }
97     }
98     return true;
99 }
100 
101 template <typename T>
operator !=(const SortedVector<T> & left,const SortedVector<T> & right)102 bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
103 {
104     return !(left == right);
105 }
106 
107 // ----------------------------------------------------------------------------
108 // AudioPolicyInterface implementation
109 // ----------------------------------------------------------------------------
110 
setDeviceConnectionState(audio_policy_dev_state_t state,const android::media::audio::common::AudioPort & port,audio_format_t encodedFormat,bool deviceSwitch)111 status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
112         const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat,
113         bool deviceSwitch) {
114     status_t status = setDeviceConnectionStateInt(state, port, encodedFormat, deviceSwitch);
115     nextAudioPortGeneration();
116     return status;
117 }
118 
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name,audio_format_t encodedFormat)119 status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
120                                                       audio_policy_dev_state_t state,
121                                                       const char* device_address,
122                                                       const char* device_name,
123                                                       audio_format_t encodedFormat) {
124     media::AudioPortFw aidlPort;
125     if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
126         status == OK) {
127         return setDeviceConnectionState(state, aidlPort.hal, encodedFormat, false /*deviceSwitch*/);
128     } else {
129         ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
130         return status;
131     }
132 }
133 
broadcastDeviceConnectionState(const sp<DeviceDescriptor> & device,media::DeviceConnectedState state)134 status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
135                                                         media::DeviceConnectedState state)
136 {
137     audio_port_v7 devicePort;
138     device->toAudioPort(&devicePort);
139     status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
140     ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
141              static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
142 
143     return status;
144 }
145 
setDeviceConnectionStateInt(audio_policy_dev_state_t state,const android::media::audio::common::AudioPort & port,audio_format_t encodedFormat,bool deviceSwitch)146 status_t AudioPolicyManager::setDeviceConnectionStateInt(
147         audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
148         audio_format_t encodedFormat, bool deviceSwitch) {
149     if (port.ext.getTag() != AudioPortExt::device) {
150         return BAD_VALUE;
151     }
152     audio_devices_t device_type;
153     std::string device_address;
154     if (status_t status = aidl2legacy_AudioDevice_audio_device(
155                 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
156         status != OK) {
157         return status;
158     };
159     const char* device_name = port.name.c_str();
160     // connect/disconnect only 1 device at a time
161     if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
162         return BAD_VALUE;
163 
164     sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
165             device_type, device_address.c_str(), device_name, encodedFormat,
166             state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
167     if (device == nullptr) {
168         return INVALID_OPERATION;
169     }
170     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
171         device->setExtraAudioDescriptors(port.extraAudioDescriptors);
172     }
173     return setDeviceConnectionStateInt(device, state, deviceSwitch);
174 }
175 
setDeviceConnectionStateInt(audio_devices_t deviceType,audio_policy_dev_state_t state,const char * device_address,const char * device_name,audio_format_t encodedFormat,bool deviceSwitch)176 status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
177                                                          audio_policy_dev_state_t state,
178                                                          const char* device_address,
179                                                          const char* device_name,
180                                                          audio_format_t encodedFormat,
181                                                          bool deviceSwitch) {
182     media::AudioPortFw aidlPort;
183     if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
184         status == OK) {
185         return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat, deviceSwitch);
186     } else {
187         ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
188         return status;
189     }
190 }
191 
setDeviceConnectionStateInt(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state,bool deviceSwitch)192 status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
193                                                          audio_policy_dev_state_t state,
194                                                          bool deviceSwitch)
195 {
196     // handle output devices
197     if (audio_is_output_device(device->type())) {
198         SortedVector <audio_io_handle_t> outputs;
199 
200         ssize_t index = mAvailableOutputDevices.indexOf(device);
201 
202         // save a copy of the opened output descriptors before any output is opened or closed
203         // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
204         mPreviousOutputs = mOutputs;
205 
206         bool wasLeUnicastActive = isLeUnicastActive();
207 
208         switch (state)
209         {
210         // handle output device connection
211         case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
212             if (index >= 0) {
213                 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
214                 return INVALID_OPERATION;
215             }
216             ALOGV("%s() connecting device %s format %x",
217                     __func__, device->toString().c_str(), device->getEncodedFormat());
218 
219             // register new device as available
220             if (mAvailableOutputDevices.add(device) < 0) {
221                 return NO_MEMORY;
222             }
223 
224             // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
225             // parameters on newly connected devices (instead of opening the outputs...)
226             if (broadcastDeviceConnectionState(
227                         device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
228                 mAvailableOutputDevices.remove(device);
229                 mHwModules.cleanUpForDevice(device);
230                 ALOGE("%s() device %s format %x connection failed", __func__,
231                       device->toString().c_str(), device->getEncodedFormat());
232                 return INVALID_OPERATION;
233             }
234 
235             if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
236                 mAvailableOutputDevices.remove(device);
237 
238                 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
239 
240                 mHwModules.cleanUpForDevice(device);
241                 return INVALID_OPERATION;
242             }
243 
244             // Populate encapsulation information when a output device is connected.
245             device->setEncapsulationInfoFromHal(mpClientInterface);
246 
247             // outputs should never be empty here
248             ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
249                     "checkOutputsForDevice() returned no outputs but status OK");
250             ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
251 
252             } break;
253         // handle output device disconnection
254         case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
255             if (index < 0) {
256                 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
257                 return INVALID_OPERATION;
258             }
259 
260             ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
261 
262             // Notify the HAL to prepare to disconnect device
263             broadcastDeviceConnectionState(
264                     device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
265 
266             // remove device from available output devices
267             mAvailableOutputDevices.remove(device);
268 
269             mOutputs.clearSessionRoutesForDevice(device);
270 
271             checkOutputsForDevice(device, state, outputs);
272 
273             // Send Disconnect to HALs
274             broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
275 
276             // Reset active device codec
277             device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
278 
279             // remove device from mReportedFormatsMap cache
280             mReportedFormatsMap.erase(device);
281 
282             // remove preferred mixer configurations
283             mPreferredMixerAttrInfos.erase(device->getId());
284 
285             } break;
286 
287         default:
288             ALOGE("%s() invalid state: %x", __func__, state);
289             return BAD_VALUE;
290         }
291 
292         // Propagate device availability to Engine
293         setEngineDeviceConnectionState(device, state);
294 
295         // No need to evaluate playback routing when connecting a remote submix
296         // output device used by a dynamic policy of type recorder as no
297         // playback use case is affected.
298         bool doCheckForDeviceAndOutputChanges = true;
299         if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
300             for (audio_io_handle_t output : outputs) {
301                 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
302                 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
303                 if (policyMix != nullptr
304                         && policyMix->mMixType == MIX_TYPE_RECORDERS
305                         && device->address() == policyMix->mDeviceAddress.c_str()) {
306                     doCheckForDeviceAndOutputChanges = false;
307                     break;
308                 }
309             }
310         }
311 
312         auto checkCloseOutputs = [&]() {
313             // outputs must be closed after checkOutputForAllStrategies() is executed
314             if (!outputs.isEmpty()) {
315                 for (audio_io_handle_t output : outputs) {
316                     sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
317                     // close unused outputs after device disconnection or direct outputs that have
318                     // been opened by checkOutputsForDevice() to query dynamic parameters
319                     // "outputs" vector never contains duplicated outputs
320                     if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
321                             || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
322                                 (desc->mDirectOpenCount == 0))
323                             || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
324                                 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
325                         clearAudioSourcesForOutput(output);
326                         closeOutput(output);
327                     }
328                 }
329                 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
330                 return true;
331             }
332             return false;
333         };
334 
335         if (doCheckForDeviceAndOutputChanges && !deviceSwitch) {
336             checkForDeviceAndOutputChanges(checkCloseOutputs);
337         } else {
338             checkCloseOutputs();
339         }
340         if (!deviceSwitch) {
341             (void)updateCallRouting(false /*fromCache*/);
342             const DeviceVector msdOutDevices = getMsdAudioOutDevices();
343             const DeviceVector activeMediaDevices =
344                     mEngine->getActiveMediaDevices(mAvailableOutputDevices);
345             std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
346             for (size_t i = 0; i < mOutputs.size(); i++) {
347                 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
348                 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
349                     (desc != mPrimaryOutput))) {
350                     DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
351                     // do not force device change on duplicated output because if device is 0,
352                     // it will also force a device 0 for the two outputs it is duplicated to
353                     // a valid device selection on those outputs.
354                     bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
355                             && !desc->isDuplicated()
356                             && (!device_distinguishes_on_address(device->type())
357                                     // always force when disconnecting (a non-duplicated device)
358                                     || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
359                     if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
360                         // If the device is using preferred mixer attributes, the output need to
361                         // reopen with default configuration when the new selected devices are
362                         // different from current routing devices
363                         outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
364                         continue;
365                     }
366                     setOutputDevices(__func__, desc, newDevices, force, 0);
367                 }
368                 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
369                         !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
370                         desc->supportsDevicesForPlayback(activeMediaDevices)) {
371                     // Reopen the output to query the dynamic profiles when there is not active
372                     // clients or all active clients will be rerouted. Otherwise, set the flag
373                     // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
374                     // can be reopened to query dynamic profiles when all clients are inactive.
375                     if (areAllActiveTracksRerouted(desc)) {
376                         outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
377                     } else {
378                         desc->mPendingReopenToQueryProfiles = true;
379                     }
380                 }
381                 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
382                     // Clear the flag that previously set for re-querying profiles.
383                     desc->mPendingReopenToQueryProfiles = false;
384                 }
385             }
386             reopenOutputsWithDevices(outputsToReopenWithDevices);
387         }
388 
389         if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
390             cleanUpForDevice(device);
391         }
392 
393         checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
394 
395         mpClientInterface->onAudioPortListUpdate();
396         ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
397         return NO_ERROR;
398     }  // end if is output device
399 
400     // handle input devices
401     if (audio_is_input_device(device->type())) {
402         ssize_t index = mAvailableInputDevices.indexOf(device);
403         switch (state)
404         {
405         // handle input device connection
406         case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
407             if (index >= 0) {
408                 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
409                 return INVALID_OPERATION;
410             }
411 
412             ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
413 
414             if (mAvailableInputDevices.add(device) < 0) {
415                 return NO_MEMORY;
416             }
417 
418             // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
419             // parameters on newly connected devices (instead of opening the inputs...)
420             if (broadcastDeviceConnectionState(
421                         device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
422                 mAvailableInputDevices.remove(device);
423                 mHwModules.cleanUpForDevice(device);
424                 ALOGE("%s() device %s format %x connection failed", __func__,
425                       device->toString().c_str(), device->getEncodedFormat());
426                 return INVALID_OPERATION;
427             }
428             // Propagate device availability to Engine
429             setEngineDeviceConnectionState(device, state);
430 
431             if (checkInputsForDevice(device, state) != NO_ERROR) {
432                 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
433 
434                 mAvailableInputDevices.remove(device);
435 
436                 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
437 
438                 mHwModules.cleanUpForDevice(device);
439 
440                 return INVALID_OPERATION;
441             }
442 
443         } break;
444 
445         // handle input device disconnection
446         case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
447             if (index < 0) {
448                 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
449                 return INVALID_OPERATION;
450             }
451 
452             ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
453 
454             // Notify the HAL to prepare to disconnect device
455             broadcastDeviceConnectionState(
456                     device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
457 
458             mAvailableInputDevices.remove(device);
459 
460             checkInputsForDevice(device, state);
461 
462             // Set Disconnect to HALs
463             broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
464 
465             // remove device from mReportedFormatsMap cache
466             mReportedFormatsMap.erase(device);
467 
468             // Propagate device availability to Engine
469             setEngineDeviceConnectionState(device, state);
470         } break;
471 
472         default:
473             ALOGE("%s() invalid state: %x", __func__, state);
474             return BAD_VALUE;
475         }
476 
477         if (!deviceSwitch) {
478             checkCloseInputs();
479             // As the input device list can impact the output device selection, update
480             // getDeviceForStrategy() cache
481             updateDevicesAndOutputs();
482 
483             (void)updateCallRouting(false /*fromCache*/);
484             // Reconnect Audio Source
485             for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
486                 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
487                 checkAudioSourceForAttributes(attributes);
488             }
489 
490             if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
491                 cleanUpForDevice(device);
492             }
493         }
494 
495         mpClientInterface->onAudioPortListUpdate();
496         ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
497         return NO_ERROR;
498     } // end if is input device
499 
500     ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
501     return BAD_VALUE;
502 }
503 
deviceToAudioPort(audio_devices_t device,const char * device_address,const char * device_name,media::AudioPortFw * aidlPort)504 status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
505                                                const char* device_name,
506                                                media::AudioPortFw* aidlPort) {
507     const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
508     devDescr->setName(device_name);
509     return devDescr->writeToParcelable(aidlPort);
510 }
511 
setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,audio_policy_dev_state_t state)512 void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
513                                       audio_policy_dev_state_t state) {
514 
515     // the Engine does not have to know about remote submix devices used by dynamic audio policies
516     if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
517         return;
518     }
519     mEngine->setDeviceConnectionState(device, state);
520 }
521 
522 
getDeviceConnectionState(audio_devices_t device,const char * device_address)523 audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
524                                                                       const char *device_address)
525 {
526     sp<DeviceDescriptor> devDesc =
527             mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
528                                            false /* allowToCreate */,
529                                            (strlen(device_address) != 0)/*matchAddress*/);
530 
531     if (devDesc == 0) {
532         ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
533               device, device_address);
534         return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
535     }
536 
537     DeviceVector *deviceVector;
538 
539     if (audio_is_output_device(device)) {
540         deviceVector = &mAvailableOutputDevices;
541     } else if (audio_is_input_device(device)) {
542         deviceVector = &mAvailableInputDevices;
543     } else {
544         ALOGW("%s() invalid device type %08x", __func__, device);
545         return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
546     }
547 
548     return (deviceVector->getDevice(
549                 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
550             AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
551 }
552 
handleDeviceConfigChange(audio_devices_t device,const char * device_address,const char * device_name,audio_format_t encodedFormat)553 status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
554                                                       const char *device_address,
555                                                       const char *device_name,
556                                                       audio_format_t encodedFormat)
557 {
558     ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
559           device, device_address, device_name, encodedFormat);
560 
561     // connect/disconnect only 1 device at a time
562     if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
563 
564     // Check if the device is currently connected
565     DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
566     if (deviceList.empty()) {
567         // Nothing to do: device is not connected
568         return NO_ERROR;
569     }
570     sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
571 
572     // For offloaded A2DP, Hw modules may have the capability to
573     // configure codecs.
574     // Handle two specific cases by sending a set parameter to
575     // configure A2DP codecs. No need to toggle device state.
576     // Case 1: A2DP active device switches from primary to primary
577     // module
578     // Case 2: A2DP device config changes on primary module.
579     if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
580         sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
581         audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
582         if (availablePrimaryOutputDevices().contains(devDesc) &&
583            (module != 0 && module->getHandle() == primaryHandle)) {
584             bool isA2dp = audio_is_a2dp_out_device(device);
585             const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
586                     : String8(AudioParameter::keyReconfigLeSupported);
587             String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
588             AudioParameter repliedParameters(reply);
589             int isReconfigSupported;
590             repliedParameters.getInt(supportKey, isReconfigSupported);
591             if (isReconfigSupported) {
592                 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
593                         : String8(AudioParameter::keyReconfigLe);
594                 AudioParameter param;
595                 param.add(key, String8("true"));
596                 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
597                 devDesc->setEncodedFormat(encodedFormat);
598                 return NO_ERROR;
599             }
600         }
601     }
602     auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
603     uint32_t muteWaitMs = 0;
604     for (size_t i = 0; i < mOutputs.size(); i++) {
605        sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
606        // mute media strategies to avoid sending the music tail into
607        // the earpiece or headset.
608        if (desc->isStrategyActive(musicStrategy)) {
609            uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
610            uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
611                         tempRecommendedMuteDuration : desc->latency() * 4;
612            if (muteWaitMs < tempMuteDurationMs) {
613                muteWaitMs = tempMuteDurationMs;
614            }
615        }
616        setStrategyMute(musicStrategy, true, desc);
617        setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
618           mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
619                                               nullptr, true /*fromCache*/).types());
620     }
621     // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
622     // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
623     // happens after the actual device switch.
624     if (muteWaitMs > 0) {
625         ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
626         usleep(muteWaitMs * 1000);
627     }
628     // Toggle the device state: UNAVAILABLE -> AVAILABLE
629     // This will force reading again the device configuration
630     status_t status = setDeviceConnectionState(device,
631                                       AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
632                                       device_address, device_name,
633                                       devDesc->getEncodedFormat());
634     if (status != NO_ERROR) {
635         ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
636               status);
637         return status;
638     }
639 
640     status = setDeviceConnectionState(device,
641                                       AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
642                                       device_address, device_name, encodedFormat);
643     if (status != NO_ERROR) {
644         ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
645               status);
646         return status;
647     }
648 
649     return NO_ERROR;
650 }
651 
getHwOffloadFormatsSupportedForBluetoothMedia(audio_devices_t device,std::vector<audio_format_t> * formats)652 status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
653                                     audio_devices_t device, std::vector<audio_format_t> *formats)
654 {
655     ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
656     status_t status = NO_ERROR;
657     std::unordered_set<audio_format_t> formatSet;
658     sp<HwModule> primaryModule =
659             mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
660     if (primaryModule == nullptr) {
661         ALOGE("%s() unable to get primary module", __func__);
662         return NO_INIT;
663     }
664 
665     DeviceTypeSet audioDeviceSet;
666 
667     switch(device) {
668     case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
669         audioDeviceSet = getAudioDeviceOutAllA2dpSet();
670         break;
671     case AUDIO_DEVICE_OUT_BLE_HEADSET:
672         audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
673         break;
674     case AUDIO_DEVICE_OUT_BLE_BROADCAST:
675         audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
676         break;
677     default:
678         ALOGE("%s() device type 0x%08x not supported", __func__, device);
679         return BAD_VALUE;
680     }
681 
682     DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
683             audioDeviceSet);
684     for (const auto& device : declaredDevices) {
685         formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
686     }
687     formats->assign(formatSet.begin(), formatSet.end());
688     return status;
689 }
690 
selectBestRxSinkDevicesForCall(bool fromCache)691 DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
692 {
693     DeviceVector rxSinkdevices{};
694     rxSinkdevices = mEngine->getOutputDevicesForAttributes(
695                 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
696     if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
697         auto rxSinkDevice = rxSinkdevices.itemAt(0);
698         auto telephonyRxModule = mHwModules.getModuleForDeviceType(
699                     AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
700         // retrieve Rx Source device descriptor
701         sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
702                     AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
703 
704         // RX Telephony and Rx sink devices are declared by Primary Audio HAL
705         if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
706                 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
707             ALOGI("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
708             return DeviceVector(rxSinkDevice);
709         }
710     }
711     // Note that despite the fact that getNewOutputDevices() is called on the primary output,
712     // the device returned is not necessarily reachable via this output
713     // (filter later by setOutputDevices())
714     return getNewOutputDevices(mPrimaryOutput, fromCache);
715 }
716 
updateCallRouting(bool fromCache,uint32_t delayMs,uint32_t * waitMs)717 status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
718 {
719     if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
720         DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
721         return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
722     }
723     return INVALID_OPERATION;
724 }
725 
updateCallRoutingInternal(const DeviceVector & rxDevices,uint32_t delayMs,uint32_t * waitMs)726 status_t AudioPolicyManager::updateCallRoutingInternal(
727         const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
728 {
729     bool createTxPatch = false;
730     bool createRxPatch = false;
731     uint32_t muteWaitMs = 0;
732     if (hasPrimaryOutput() &&
733             mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
734         return INVALID_OPERATION;
735     }
736 
737     audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
738     auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
739 
740     if (!fix_call_audio_patch()) {
741         disconnectTelephonyAudioSource(mCallRxSourceClient);
742         disconnectTelephonyAudioSource(mCallTxSourceClient);
743     }
744 
745     if (rxDevices.isEmpty()) {
746         ALOGW("%s() no selected output device", __func__);
747         return INVALID_OPERATION;
748     }
749     if (txSourceDevice == nullptr) {
750         ALOGE("%s() selected input device not available", __func__);
751         return INVALID_OPERATION;
752     }
753 
754     ALOGV("%s device rxDevice %s txDevice %s", __func__,
755           rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
756 
757     auto telephonyRxModule =
758         mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
759     auto telephonyTxModule =
760         mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
761     // retrieve Rx Source and Tx Sink device descriptors
762     sp<DeviceDescriptor> rxSourceDevice =
763         mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
764                                          String8(),
765                                          AUDIO_FORMAT_DEFAULT);
766     sp<DeviceDescriptor> txSinkDevice =
767         mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
768                                           String8(),
769                                           AUDIO_FORMAT_DEFAULT);
770 
771     // RX and TX Telephony device are declared by Primary Audio HAL
772     if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
773             (telephonyRxModule->getHalVersionMajor() >= 3)) {
774         if (rxSourceDevice == 0 || txSinkDevice == 0) {
775             // RX / TX Telephony device(s) is(are) not currently available
776             ALOGE("%s() no telephony Tx and/or RX device", __func__);
777             return INVALID_OPERATION;
778         }
779         // createAudioPatchInternal now supports both HW / SW bridging
780         createRxPatch = true;
781         createTxPatch = true;
782     } else {
783         // If the RX device is on the primary HW module, then use legacy routing method for
784         // voice calls via setOutputDevice() on primary output.
785         // Otherwise, create two audio patches for TX and RX path.
786         createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
787                 (rxSourceDevice != 0);
788         // If the TX device is also on the primary HW module, setOutputDevice() will take care
789         // of it due to legacy implementation. If not, create a patch.
790         createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
791                 (txSinkDevice != 0);
792     }
793     // Use legacy routing method for voice calls via setOutputDevice() on primary output.
794     // Otherwise, create two audio patches for TX and RX path.
795     if (!createRxPatch) {
796         if (fix_call_audio_patch()) {
797             disconnectTelephonyAudioSource(mCallRxSourceClient);
798         }
799         if (!hasPrimaryOutput()) {
800             ALOGW("%s() no primary output available", __func__);
801             return INVALID_OPERATION;
802         }
803         muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
804     } else { // create RX path audio patch
805         connectTelephonyRxAudioSource(delayMs);
806         // If the TX device is on the primary HW module but RX device is
807         // on other HW module, SinkMetaData of telephony input should handle it
808         // assuming the device uses audio HAL V5.0 and above
809     }
810     if (createTxPatch) { // create TX path audio patch
811         // terminate active capture if on the same HW module as the call TX source device
812         // FIXME: would be better to refine to only inputs whose profile connects to the
813         // call TX device but this information is not in the audio patch and logic here must be
814         // symmetric to the one in startInput()
815         for (const auto& activeDesc : mInputs.getActiveInputs()) {
816             if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
817                 closeActiveClients(activeDesc);
818             }
819         }
820         connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
821     } else if (fix_call_audio_patch()) {
822         disconnectTelephonyAudioSource(mCallTxSourceClient);
823     }
824     if (waitMs != nullptr) {
825         *waitMs = muteWaitMs;
826     }
827     return NO_ERROR;
828 }
829 
isDeviceOfModule(const sp<DeviceDescriptor> & devDesc,const char * moduleId) const830 bool AudioPolicyManager::isDeviceOfModule(
831         const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
832     sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
833     if (module != 0) {
834         return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
835                 .indexOf(devDesc) != NAME_NOT_FOUND
836                 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
837                 .indexOf(devDesc) != NAME_NOT_FOUND;
838     }
839     return false;
840 }
841 
connectTelephonyRxAudioSource(uint32_t delayMs)842 void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
843 {
844     const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
845 
846     if (fix_call_audio_patch()) {
847         if (mCallRxSourceClient != nullptr) {
848             DeviceVector rxDevices =
849                   mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
850             ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
851                         "connectTelephonyRxAudioSource(): no device found for call RX source");
852             sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
853             if (mCallRxSourceClient->isConnected()
854                     && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
855                 return;
856             }
857             disconnectTelephonyAudioSource(mCallRxSourceClient);
858         }
859     } else {
860         disconnectTelephonyAudioSource(mCallRxSourceClient);
861     }
862 
863     const struct audio_port_config source = {
864         .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
865         .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
866     };
867     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
868 
869     status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
870                                        true /*internal*/, true /*isCallRx*/, delayMs);
871     ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
872     mCallRxSourceClient = mAudioSources.valueFor(portId);
873     ALOGV_IF(mCallRxSourceClient != nullptr, "%s portdID %d between source %s and sink %s",
874         __func__, portId, mCallRxSourceClient->srcDevice()->toString().c_str(),
875         mCallRxSourceClient->sinkDevice()->toString().c_str());
876     ALOGE_IF(mCallRxSourceClient == nullptr,
877              "%s failed to start Telephony Rx AudioSource", __func__);
878 }
879 
disconnectTelephonyAudioSource(sp<SourceClientDescriptor> & clientDesc)880 void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
881 {
882     if (clientDesc == nullptr) {
883         return;
884     }
885     ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
886             "%s error stopping audio source", __func__);
887     clientDesc.clear();
888 }
889 
connectTelephonyTxAudioSource(const sp<DeviceDescriptor> & srcDevice,const sp<DeviceDescriptor> & sinkDevice,uint32_t delayMs)890 void AudioPolicyManager::connectTelephonyTxAudioSource(
891         const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
892         uint32_t delayMs)
893 {
894     if (srcDevice == nullptr || sinkDevice == nullptr) {
895         ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
896         return;
897     }
898 
899     if (fix_call_audio_patch()) {
900         if (mCallTxSourceClient != nullptr) {
901             if (mCallTxSourceClient->isConnected()
902                     && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
903                 return;
904             }
905             disconnectTelephonyAudioSource(mCallTxSourceClient);
906         }
907     } else {
908         disconnectTelephonyAudioSource(mCallTxSourceClient);
909     }
910 
911     PatchBuilder patchBuilder;
912     patchBuilder.addSource(srcDevice).addSink(sinkDevice);
913 
914     auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
915     const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
916 
917     struct audio_port_config source = {};
918     srcDevice->toAudioPortConfig(&source);
919     mCallTxSourceClient = new SourceClientDescriptor(
920                 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
921                 mCommunnicationStrategy, toVolumeSource(aa), true,
922                 false /*isCallRx*/, true /*isCallTx*/);
923     mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
924 
925     audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
926     status_t status = connectAudioSourceToSink(
927                 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
928                 delayMs);
929     ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
930     ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
931         srcDevice->toString().c_str(), sinkDevice->toString().c_str());
932     if (status == NO_ERROR) {
933         mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
934     }
935 }
936 
setPhoneState(audio_mode_t state)937 void AudioPolicyManager::setPhoneState(audio_mode_t state)
938 {
939     ALOGV("setPhoneState() state %d", state);
940     // store previous phone state for management of sonification strategy below
941     int oldState = mEngine->getPhoneState();
942     bool wasLeUnicastActive = isLeUnicastActive();
943 
944     if (mEngine->setPhoneState(state) != NO_ERROR) {
945         ALOGW("setPhoneState() invalid or same state %d", state);
946         return;
947     }
948     /// Opens: can these line be executed after the switch of volume curves???
949     if (isStateInCall(oldState)) {
950         ALOGV("setPhoneState() in call state management: new state is %d", state);
951         // force reevaluating accessibility routing when call stops
952         invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
953     }
954 
955     /**
956      * Switching to or from incall state or switching between telephony and VoIP lead to force
957      * routing command.
958      */
959     bool force = ((isStateInCall(oldState) != isStateInCall(state))
960                   || (isStateInCall(state) && (state != oldState)));
961 
962     // check for device and output changes triggered by new phone state
963     checkForDeviceAndOutputChanges();
964 
965     int delayMs = 0;
966     if (isStateInCall(state)) {
967         nsecs_t sysTime = systemTime();
968         auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
969         auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
970         for (size_t i = 0; i < mOutputs.size(); i++) {
971             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
972             // mute media and sonification strategies and delay device switch by the largest
973             // latency of any output where either strategy is active.
974             // This avoid sending the ring tone or music tail into the earpiece or headset.
975             if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
976                  desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
977                                         sysTime)) &&
978                     (delayMs < (int)desc->latency()*2)) {
979                 delayMs = desc->latency()*2;
980             }
981             setStrategyMute(musicStrategy, true, desc);
982             setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
983                 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
984                                                        nullptr, true /*fromCache*/).types());
985             setStrategyMute(sonificationStrategy, true, desc);
986             setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
987                 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
988                                                        nullptr, true /*fromCache*/).types());
989         }
990     }
991 
992     if (state == AUDIO_MODE_IN_CALL) {
993         (void)updateCallRouting(false /*fromCache*/, delayMs);
994     } else {
995         if (oldState == AUDIO_MODE_IN_CALL) {
996             disconnectTelephonyAudioSource(mCallRxSourceClient);
997             disconnectTelephonyAudioSource(mCallTxSourceClient);
998         }
999         if (hasPrimaryOutput()) {
1000             DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
1001             // force routing command to audio hardware when ending call
1002             // even if no device change is needed
1003             if (isStateInCall(oldState) && rxDevices.isEmpty()) {
1004                 rxDevices = mPrimaryOutput->devices();
1005             }
1006             setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
1007         }
1008     }
1009 
1010     std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
1011     // reevaluate routing on all outputs in case tracks have been started during the call
1012     for (size_t i = 0; i < mOutputs.size(); i++) {
1013         sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1014         DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
1015         if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
1016                 && desc->mPreferredAttrInfo != nullptr) {
1017             // If the output is using preferred mixer attributes and the audio mode is not normal,
1018             // the output need to reopen with default configuration.
1019             outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
1020             continue;
1021         }
1022         if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
1023             bool forceRouting = !newDevices.isEmpty();
1024             setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
1025                              true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
1026         }
1027     }
1028     reopenOutputsWithDevices(outputsToReopen);
1029 
1030     checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1031 
1032     if (isStateInCall(state)) {
1033         ALOGV("setPhoneState() in call state management: new state is %d", state);
1034         // force reevaluating accessibility routing when call starts
1035         invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
1036     }
1037 
1038     // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
1039     mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1040                             isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
1041 }
1042 
getPhoneState()1043 audio_mode_t AudioPolicyManager::getPhoneState() {
1044     return mEngine->getPhoneState();
1045 }
1046 
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)1047 void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
1048                                      audio_policy_forced_cfg_t config)
1049 {
1050     ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
1051     if (config == mEngine->getForceUse(usage)) {
1052         return;
1053     }
1054 
1055     if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1056         ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1057         return;
1058     }
1059     bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1060             (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1061             (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
1062 
1063     // check for device and output changes triggered by new force usage
1064     checkForDeviceAndOutputChanges();
1065 
1066     // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1067     if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
1068         invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
1069     }
1070 
1071     //FIXME: workaround for truncated touch sounds
1072     // to be removed when the problem is handled by system UI
1073     uint32_t delayMs = 0;
1074     if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1075         delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1076     }
1077 
1078     updateCallAndOutputRouting(forceVolumeReeval, delayMs);
1079     updateInputRouting();
1080 }
1081 
setSystemProperty(const char * property,const char * value)1082 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
1083 {
1084     ALOGV("setSystemProperty() property %s, value %s", property, value);
1085 }
1086 
1087 // Find an MSD output profile compatible with the parameters passed.
1088 // When "directOnly" is set, restrict search to profiles for direct outputs.
getMsdProfileForOutput(const DeviceVector & devices,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,bool directOnly)1089 sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1090                                                    const DeviceVector& devices,
1091                                                    uint32_t samplingRate,
1092                                                    audio_format_t format,
1093                                                    audio_channel_mask_t channelMask,
1094                                                    audio_output_flags_t flags,
1095                                                    bool directOnly)
1096 {
1097     flags = getRelevantFlags(flags, directOnly);
1098 
1099     sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1100     if (msdModule != nullptr) {
1101         // for the msd module check if there are patches to the output devices
1102         if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1103             HwModuleCollection modules;
1104             modules.add(msdModule);
1105             return searchCompatibleProfileHwModules(
1106                     modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1107                     flags, directOnly);
1108         }
1109     }
1110     return nullptr;
1111 }
1112 
1113 // Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1114 // 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)1115 sp<IOProfile> AudioPolicyManager::getProfileForOutput(
1116                                                    const DeviceVector& devices,
1117                                                    uint32_t samplingRate,
1118                                                    audio_format_t format,
1119                                                    audio_channel_mask_t channelMask,
1120                                                    audio_output_flags_t flags,
1121                                                    bool directOnly)
1122 {
1123     flags = getRelevantFlags(flags, directOnly);
1124 
1125     return searchCompatibleProfileHwModules(
1126             mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1127 }
1128 
getRelevantFlags(audio_output_flags_t flags,bool directOnly)1129 audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1130                                             audio_output_flags_t flags, bool directOnly) {
1131     if (directOnly) {
1132          // only retain flags that will drive the direct output profile selection
1133          // if explicitly requested
1134          static const uint32_t kRelevantFlags =
1135                 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1136                 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1137          flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
1138     }
1139     return flags;
1140 }
1141 
searchCompatibleProfileHwModules(const HwModuleCollection & hwModules,const DeviceVector & devices,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,bool directOnly)1142 sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1143                                         const HwModuleCollection& hwModules,
1144                                         const DeviceVector& devices,
1145                                         uint32_t samplingRate,
1146                                         audio_format_t format,
1147                                         audio_channel_mask_t channelMask,
1148                                         audio_output_flags_t flags,
1149                                         bool directOnly) {
1150     sp<IOProfile> directOnlyProfile = nullptr;
1151     sp<IOProfile> compressOffloadProfile = nullptr;
1152     sp<IOProfile> profile = nullptr;
1153     for (const auto& hwModule : hwModules) {
1154         for (const auto& curProfile : hwModule->getOutputProfiles()) {
1155              if (curProfile->getCompatibilityScore(devices,
1156                      samplingRate, NULL /*updatedSamplingRate*/,
1157                      format, NULL /*updatedFormat*/,
1158                      channelMask, NULL /*updatedChannelMask*/,
1159                      flags) == IOProfile::NO_MATCH) {
1160                  continue;
1161              }
1162              // reject profiles not corresponding to a device currently available
1163              if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1164                  continue;
1165              }
1166              // reject profiles if connected device does not support codec
1167              if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1168                  continue;
1169              }
1170              if (!directOnly) {
1171                 return curProfile;
1172              }
1173 
1174              profile = curProfile;
1175              if ((flags == AUDIO_OUTPUT_FLAG_DIRECT) &&
1176                  curProfile->getFlags() == AUDIO_OUTPUT_FLAG_DIRECT) {
1177                  directOnlyProfile = curProfile;
1178              }
1179 
1180              if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1181                  compressOffloadProfile = curProfile;
1182              }
1183         }
1184     }
1185 
1186     return directOnlyProfile ? directOnlyProfile
1187                             : (compressOffloadProfile ? compressOffloadProfile : profile);
1188 
1189 }
1190 
getSpatializerOutputProfile(const audio_config_t * config __unused,const AudioDeviceTypeAddrVector & devices) const1191 sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
1192         const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
1193 {
1194     for (const auto& hwModule : mHwModules) {
1195         for (const auto& curProfile : hwModule->getOutputProfiles()) {
1196             if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
1197                 continue;
1198             }
1199             if (!devices.empty()) {
1200                 // reject profiles not corresponding to a device currently available
1201                 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1202                 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1203                     continue;
1204                 }
1205                 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1206                         != devices.size()) {
1207                     continue;
1208                 }
1209             }
1210             ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1211             return curProfile;
1212         }
1213     }
1214     return nullptr;
1215 }
1216 
getOutput(audio_stream_type_t stream)1217 audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
1218 {
1219     DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
1220 
1221     // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1222     // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1223     // format, flags, etc. This may result in some discrepancy for functions that utilize
1224     // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1225     // and AudioSystem::getOutputSamplingRate().
1226 
1227     SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
1228     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1229     if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
1230         flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1231     }
1232     const audio_io_handle_t output = selectOutput(outputs, flags);
1233 
1234     ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1235           devices.toString().c_str(), output);
1236     return output;
1237 }
1238 
getAudioAttributes(audio_attributes_t * dstAttr,const audio_attributes_t * srcAttr,audio_stream_type_t srcStream)1239 status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1240                                                 const audio_attributes_t *srcAttr,
1241                                                 audio_stream_type_t srcStream)
1242 {
1243     if (srcAttr != NULL) {
1244         if (!isValidAttributes(srcAttr)) {
1245             ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1246                     __func__,
1247                     srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1248                     srcAttr->tags);
1249             return BAD_VALUE;
1250         }
1251         *dstAttr = *srcAttr;
1252     } else {
1253         if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1254             ALOGE("%s:  invalid stream type", __func__);
1255             return BAD_VALUE;
1256         }
1257         *dstAttr = mEngine->getAttributesForStreamType(srcStream);
1258     }
1259 
1260     // Only honor audibility enforced when required. The client will be
1261     // forced to reconnect if the forced usage changes.
1262     if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1263         dstAttr->flags = static_cast<audio_flags_mask_t>(
1264                 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
1265     }
1266 
1267     return NO_ERROR;
1268 }
1269 
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,audio_config_t * config,audio_output_flags_t * flags,DeviceIdVector * selectedDeviceIds,bool * isRequestedDeviceForExclusiveUse,std::vector<sp<AudioPolicyMix>> * secondaryMixes,output_type_t * outputType,bool * isSpatialized,bool * isBitPerfect)1270 status_t AudioPolicyManager::getOutputForAttrInt(
1271         audio_attributes_t *resultAttr,
1272         audio_io_handle_t *output,
1273         audio_session_t session,
1274         const audio_attributes_t *attr,
1275         audio_stream_type_t *stream,
1276         uid_t uid,
1277         audio_config_t *config,
1278         audio_output_flags_t *flags,
1279         DeviceIdVector *selectedDeviceIds,
1280         bool *isRequestedDeviceForExclusiveUse,
1281         std::vector<sp<AudioPolicyMix>> *secondaryMixes,
1282         output_type_t *outputType,
1283         bool *isSpatialized,
1284         bool *isBitPerfect)
1285 {
1286     DeviceVector outputDevices;
1287     audio_port_handle_t requestedPortId = getFirstDeviceId(*selectedDeviceIds);
1288     selectedDeviceIds->clear();
1289     DeviceVector msdDevices = getMsdAudioOutDevices();
1290     const sp<DeviceDescriptor> requestedDevice =
1291         mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1292 
1293     *outputType = API_OUTPUT_INVALID;
1294     *isSpatialized = false;
1295 
1296     status_t status = getAudioAttributes(resultAttr, attr, *stream);
1297     if (status != NO_ERROR) {
1298         return status;
1299     }
1300     if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
1301         resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
1302     }
1303     *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
1304 
1305     ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1306           toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
1307 
1308     bool usePrimaryOutputFromPolicyMixes = false;
1309 
1310     // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1311     //       otherwise, fallback to the dynamic policies, if none match, query the engine.
1312     // Secondary outputs are always found by dynamic policies as the engine do not support them
1313     sp<AudioPolicyMix> primaryMix;
1314     const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1315         .channel_mask = config->channel_mask,
1316         .format = config->format,
1317     };
1318     status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1319                                            mAvailableOutputDevices, requestedDevice, primaryMix,
1320                                            secondaryMixes, usePrimaryOutputFromPolicyMixes);
1321     if (status != OK) {
1322         return status;
1323     }
1324 
1325     // FIXME: in case of RENDER policy, the output capabilities should be checked
1326     if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1327             && (!audio_is_linear_pcm(config->format) ||
1328                     *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
1329         ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
1330         return BAD_VALUE;
1331     }
1332     if (usePrimaryOutputFromPolicyMixes) {
1333         sp<DeviceDescriptor> policyMixDevice =
1334                 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1335                                                   primaryMix->mDeviceAddress,
1336                                                   AUDIO_FORMAT_DEFAULT);
1337         sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
1338         bool tryDirectForFlags = policyDesc == nullptr ||
1339                 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1340                 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
1341         // if a direct output can be opened to deliver the track's multi-channel content to the
1342         // output rather than being downmixed by the primary output, then use this direct
1343         // output by by-passing the primary mix if possible, otherwise fall-through to primary
1344         // mix.
1345         bool tryDirectForChannelMask = policyDesc != nullptr
1346                     && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1347                         audio_channel_count_from_out_mask(config->channel_mask));
1348         if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
1349             audio_io_handle_t newOutput;
1350             status = openDirectOutput(
1351                     *stream, session, config,
1352                     (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1353                     DeviceVector(policyMixDevice), &newOutput, *resultAttr);
1354             if (status == NO_ERROR) {
1355                 policyDesc = mOutputs.valueFor(newOutput);
1356                 primaryMix->setOutput(policyDesc);
1357             } else if (tryDirectForFlags) {
1358                 ALOGW("%s, failed open direct, status: %d", __func__, status);
1359                 policyDesc = nullptr;
1360             } // otherwise use primary if available.
1361         }
1362         if (policyDesc != nullptr) {
1363             policyDesc->mPolicyMix = primaryMix;
1364             *output = policyDesc->mIoHandle;
1365             if (policyMixDevice != nullptr) {
1366                 selectedDeviceIds->push_back(policyMixDevice->getId());
1367             }
1368             if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1369                 // Remove direct flag as it is not on a direct output.
1370                 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1371             }
1372 
1373             ALOGV("getOutputForAttr() returns output %d", *output);
1374             if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1375                 *outputType = API_OUT_MIX_PLAYBACK;
1376             } else {
1377                 *outputType = API_OUTPUT_LEGACY;
1378             }
1379             return NO_ERROR;
1380         } else {
1381             if (policyMixDevice != nullptr) {
1382                 ALOGE("%s, try to use primary mix but no output found", __func__);
1383                 return INVALID_OPERATION;
1384             }
1385             // Fallback to default engine selection as the selected primary mix device is not
1386             // available.
1387         }
1388     }
1389     // Virtual sources must always be dynamicaly or explicitly routed
1390     if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1391         ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1392         return BAD_VALUE;
1393     }
1394     // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1395     // in order to let the choice of the order to future vendor engine
1396     outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
1397 
1398     if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
1399         *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1400     }
1401 
1402     // Set incall music only if device was explicitly set, and fallback to the device which is
1403     // chosen by the engine if not.
1404     // FIXME: provide a more generic approach which is not device specific and move this back
1405     // to getOutputForDevice.
1406     // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
1407     if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
1408         (*stream == AUDIO_STREAM_MUSIC  || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
1409         audio_is_linear_pcm(config->format) &&
1410         isCallAudioAccessible()) {
1411         if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
1412             *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
1413             *isRequestedDeviceForExclusiveUse = true;
1414         }
1415     }
1416 
1417     ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1418           __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1419           config->channel_mask, *flags, toString(*stream).c_str());
1420 
1421     *output = AUDIO_IO_HANDLE_NONE;
1422     if (!msdDevices.isEmpty()) {
1423         *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
1424         if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
1425             ALOGV("%s() Using MSD devices %s instead of devices %s",
1426                   __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1427         } else {
1428             *output = AUDIO_IO_HANDLE_NONE;
1429         }
1430     }
1431     if (*output == AUDIO_IO_HANDLE_NONE) {
1432         sp<PreferredMixerAttributesInfo> info = nullptr;
1433         if (outputDevices.size() == 1) {
1434             info = getPreferredMixerAttributesInfo(
1435                     outputDevices.itemAt(0)->getId(),
1436                     mEngine->getProductStrategyForAttributes(*resultAttr),
1437                     true /*activeBitPerfectPreferred*/);
1438             // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1439             // and it is currently active.
1440             if (info != nullptr && info->getUid() != uid &&
1441                 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
1442                 info = nullptr;
1443             }
1444 
1445             if (info != nullptr && info->isBitPerfect() &&
1446                 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1447                         AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1448                 // Reject direct request if a preferred mixer config in use is bit-perfect.
1449                 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1450                       __func__);
1451                 return BAD_VALUE;
1452             }
1453 
1454             if (com::android::media::audioserver::
1455                     fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1456                 if (info != nullptr && info->getUid() == uid &&
1457                     info->configMatches(*config) &&
1458                     (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1459                             std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1460                                         [this, &outputDevices](audio_usage_t usage) {
1461                                             return mOutputs.isUsageActiveOnDevice(
1462                                                     usage, outputDevices[0]); }))) {
1463                     // Bit-perfect request is not allowed when the phone mode is not normal or
1464                     // there is any higher priority user case active.
1465                     return INVALID_OPERATION;
1466                 }
1467             }
1468         }
1469         *output = getOutputForDevices(outputDevices, session, resultAttr, config,
1470                 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
1471         // The client will be active if the client is currently preferred mixer owner and the
1472         // requested configuration matches the preferred mixer configuration.
1473         *isBitPerfect = (info != nullptr
1474                 && info->isBitPerfect()
1475                 && info->getUid() == uid
1476                 && *output != AUDIO_IO_HANDLE_NONE
1477                 // When bit-perfect output is selected for the preferred mixer attributes owner,
1478                 // only need to consider the config matches.
1479                 && mOutputs.valueFor(*output)->isConfigurationMatched(
1480                         clientConfig, AUDIO_OUTPUT_FLAG_NONE));
1481 
1482         if (*isBitPerfect) {
1483             *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1484         }
1485     }
1486     if (*output == AUDIO_IO_HANDLE_NONE) {
1487         AudioProfileVector profiles;
1488         status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1489         if (ret == NO_ERROR && !profiles.empty()) {
1490             const auto channels = profiles[0]->getChannels();
1491             if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1492                 config->channel_mask = *channels.begin();
1493             }
1494             const auto sampleRates = profiles[0]->getSampleRates();
1495             if (!sampleRates.empty() &&
1496                     (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1497                 config->sample_rate = *sampleRates.begin();
1498             }
1499             config->format = profiles[0]->getFormat();
1500         }
1501         return INVALID_OPERATION;
1502     }
1503 
1504     for (auto &outputDevice : outputDevices) {
1505         if (std::find(selectedDeviceIds->begin(), selectedDeviceIds->end(),
1506                       outputDevice->getId()) == selectedDeviceIds->end()) {
1507             selectedDeviceIds->push_back(outputDevice->getId());
1508             if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
1509                 std::swap(selectedDeviceIds->front(), selectedDeviceIds->back());
1510             }
1511         }
1512     }
1513 
1514     if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1515         *outputType = API_OUTPUT_TELEPHONY_TX;
1516     } else {
1517         *outputType = API_OUTPUT_LEGACY;
1518     }
1519 
1520     ALOGV("%s returns output %d selectedDeviceIds %s", __func__, *output,
1521             toString(*selectedDeviceIds).c_str());
1522 
1523     return NO_ERROR;
1524 }
1525 
getOutputForAttr(const audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,const AttributionSourceState & attributionSource,audio_config_t * config,audio_output_flags_t * flags,DeviceIdVector * selectedDeviceIds,audio_port_handle_t * portId,std::vector<audio_io_handle_t> * secondaryOutputs,output_type_t * outputType,bool * isSpatialized,bool * isBitPerfect,float * volume,bool * muted)1526 status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1527                                               audio_io_handle_t *output,
1528                                               audio_session_t session,
1529                                               audio_stream_type_t *stream,
1530                                               const AttributionSourceState& attributionSource,
1531                                               audio_config_t *config,
1532                                               audio_output_flags_t *flags,
1533                                               DeviceIdVector *selectedDeviceIds,
1534                                               audio_port_handle_t *portId,
1535                                               std::vector<audio_io_handle_t> *secondaryOutputs,
1536                                               output_type_t *outputType,
1537                                               bool *isSpatialized,
1538                                               bool *isBitPerfect,
1539                                               float *volume,
1540                                               bool *muted)
1541 {
1542     // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1543     if (*portId != AUDIO_PORT_HANDLE_NONE) {
1544         return INVALID_OPERATION;
1545     }
1546     const uid_t uid = VALUE_OR_RETURN_STATUS(
1547         aidl2legacy_int32_t_uid_t(attributionSource.uid));
1548     audio_attributes_t resultAttr;
1549     bool isRequestedDeviceForExclusiveUse = false;
1550     std::vector<sp<AudioPolicyMix>> secondaryMixes;
1551     DeviceIdVector requestedDeviceIds = *selectedDeviceIds;
1552 
1553     // Prevent from storing invalid requested device id in clients
1554     DeviceIdVector sanitizedRequestedPortIds;
1555     for (auto deviceId : *selectedDeviceIds) {
1556         if (mAvailableOutputDevices.getDeviceFromId(deviceId) != nullptr) {
1557             sanitizedRequestedPortIds.push_back(deviceId);
1558         }
1559     }
1560     *selectedDeviceIds = sanitizedRequestedPortIds;
1561 
1562     status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
1563             config, flags, selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
1564             secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1565             isBitPerfect);
1566     if (status != NO_ERROR) {
1567         return status;
1568     }
1569     std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
1570     if (secondaryOutputs != nullptr) {
1571         for (auto &secondaryMix : secondaryMixes) {
1572             sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1573             if (outputDesc != nullptr &&
1574                 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE &&
1575                 outputDesc->mIoHandle != *output) {
1576                 secondaryOutputs->push_back(outputDesc->mIoHandle);
1577                 weakSecondaryOutputDescs.push_back(outputDesc);
1578             }
1579         }
1580     }
1581 
1582     audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1583         .channel_mask = config->channel_mask,
1584         .format = config->format,
1585     };
1586     *portId = PolicyAudioPort::getNextUniqueId();
1587 
1588     sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
1589     // TODO(b/367816690): Add device id sets to TrackClientDescriptor
1590     sp<TrackClientDescriptor> clientDesc =
1591         new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
1592                                   getFirstDeviceId(sanitizedRequestedPortIds), *stream,
1593                                   mEngine->getProductStrategyForAttributes(resultAttr),
1594                                   toVolumeSource(resultAttr),
1595                                   *flags, isRequestedDeviceForExclusiveUse,
1596                                   std::move(weakSecondaryOutputDescs),
1597                                   outputDesc->mPolicyMix);
1598     outputDesc->addClient(clientDesc);
1599 
1600     *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
1601     *muted = outputDesc->isMutedByGroup(toVolumeSource(resultAttr));
1602 
1603     ALOGV("%s() returns output %d requestedPortIds %s selectedDeviceIds %s for port ID %d",
1604           __func__, *output, toString(requestedDeviceIds).c_str(),
1605           toString(*selectedDeviceIds).c_str(), *portId);
1606 
1607     return NO_ERROR;
1608 }
1609 
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,audio_attributes_t attributes)1610 status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1611                                               audio_session_t session,
1612                                               const audio_config_t *config,
1613                                               audio_output_flags_t flags,
1614                                               const DeviceVector &devices,
1615                                               audio_io_handle_t *output,
1616                                               audio_attributes_t attributes) {
1617 
1618     *output = AUDIO_IO_HANDLE_NONE;
1619 
1620     // skip direct output selection if the request can obviously be attached to a mixed output
1621     // and not explicitly requested
1622     if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1623             audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1624             audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1625         return NAME_NOT_FOUND;
1626     }
1627 
1628     // Reject flag combinations that do not make sense. Note that the requested flags might not
1629     // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1630     // combine the requested flags with its own flags, yielding an unsupported combination.
1631     if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1632         return NAME_NOT_FOUND;
1633     }
1634 
1635     // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1636     // This prevents creating an offloaded track and tearing it down immediately after start
1637     // when audioflinger detects there is an active non offloadable effect.
1638     // FIXME: We should check the audio session here but we do not have it in this context.
1639     // This may prevent offloading in rare situations where effects are left active by apps
1640     // in the background.
1641     sp<IOProfile> profile;
1642     if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1643             !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1644         profile = getProfileForOutput(
1645                 devices, config->sample_rate, config->format, config->channel_mask,
1646                 flags, true /* directOnly */);
1647     }
1648 
1649     if (profile == nullptr) {
1650         return NAME_NOT_FOUND;
1651     }
1652 
1653     // exclusive outputs for MMAP and Offload are enforced by different session ids.
1654     for (size_t i = 0; i < mOutputs.size(); i++) {
1655         sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1656         if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1657             // reuse direct output if currently open by the same client
1658             // and configured with same parameters
1659             if ((config->sample_rate == desc->getSamplingRate()) &&
1660                 (config->format == desc->getFormat()) &&
1661                 (config->channel_mask == desc->getChannelMask()) &&
1662                 (session == desc->mDirectClientSession)) {
1663                 desc->mDirectOpenCount++;
1664                 ALOGI("%s reusing direct output %d for session %d", __func__,
1665                     mOutputs.keyAt(i), session);
1666                 *output = mOutputs.keyAt(i);
1667                 return NO_ERROR;
1668             }
1669         }
1670     }
1671 
1672     if (!profile->canOpenNewIo()) {
1673         if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1674             // MMAP gracefully handles lack of an exclusive track resource by mixing
1675             // above the audio framework. For AAudio to know that the limit is reached,
1676             // return an error.
1677             ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1678                   profile->getName().c_str());
1679             return NAME_NOT_FOUND;
1680         } else {
1681             // Close outputs on this profile, if available, to free resources for this request
1682             for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1683                 const auto desc = mOutputs.valueAt(i);
1684                 if (desc->mProfile == profile) {
1685                     ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1686                           desc->mIoHandle, session, profile->getName().c_str());
1687                     closeOutput(desc->mIoHandle);
1688                 }
1689             }
1690         }
1691     }
1692 
1693     // Unable to close streams to find free resources for this request
1694     if (!profile->canOpenNewIo()) {
1695         ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1696               profile->getName().c_str());
1697         return NAME_NOT_FOUND;
1698     }
1699 
1700     auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
1701 
1702     // An MSD patch may be using the only output stream that can service this request. Release
1703     // all MSD patches to prioritize this request over any active output on MSD.
1704     releaseMsdOutputPatches(devices);
1705 
1706     status_t status =
1707             outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
1708                              attributes);
1709 
1710     // only accept an output with the requested parameters, unless the format can be IEC61937
1711     // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1712     const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1713             && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1714             && audio_has_proportional_frames(outputDesc->getFormat());
1715     if (status != NO_ERROR ||
1716         (!ignoreRequestedParametersCheck &&
1717         ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1718          (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1719          (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
1720         ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1721                 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1722                 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1723                 config->channel_mask, outputDesc->getChannelMask());
1724         if (*output != AUDIO_IO_HANDLE_NONE) {
1725             outputDesc->close();
1726         }
1727         // fall back to mixer output if possible when the direct output could not be open
1728         if (audio_is_linear_pcm(config->format) &&
1729                 config->sample_rate  <= SAMPLE_RATE_HZ_MAX) {
1730             return NAME_NOT_FOUND;
1731         }
1732         *output = AUDIO_IO_HANDLE_NONE;
1733         return BAD_VALUE;
1734     }
1735     outputDesc->mDirectOpenCount = 1;
1736     outputDesc->mDirectClientSession = session;
1737 
1738     addOutput(*output, outputDesc);
1739     // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1740     if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1741             hwModule->getHalVersionMajor() >= 3) {
1742         setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1743     }
1744     mPreviousOutputs = mOutputs;
1745     ALOGV("%s returns new direct output %d", __func__, *output);
1746     mpClientInterface->onAudioPortListUpdate();
1747     return NO_ERROR;
1748 }
1749 
getOutputForDevices(const DeviceVector & devices,audio_session_t session,const audio_attributes_t * attr,const audio_config_t * config,audio_output_flags_t * flags,bool * isSpatialized,sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,bool forceMutingHaptic)1750 audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1751         const DeviceVector &devices,
1752         audio_session_t session,
1753         const audio_attributes_t *attr,
1754         const audio_config_t *config,
1755         audio_output_flags_t *flags,
1756         bool *isSpatialized,
1757         sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
1758         bool forceMutingHaptic)
1759 {
1760     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
1761 
1762     // Discard haptic channel mask when forcing muting haptic channels.
1763     audio_channel_mask_t channelMask = forceMutingHaptic
1764             ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1765             : config->channel_mask;
1766 
1767     // open a direct output if required by specified parameters
1768     //force direct flag if offload flag is set: offloading implies a direct output stream
1769     // and all common behaviors are driven by checking only the direct flag
1770     // this should normally be set appropriately in the policy configuration file
1771     if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1772         *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
1773     }
1774     if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1775         *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
1776     }
1777 
1778     audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1779 
1780     // only allow deep buffering for music stream type
1781     if (stream != AUDIO_STREAM_MUSIC) {
1782         *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1783     } else if (/* stream == AUDIO_STREAM_MUSIC && */
1784             *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
1785         // use DEEP_BUFFER as default output for music stream type
1786         *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1787     }
1788     if (stream == AUDIO_STREAM_TTS) {
1789         *flags = AUDIO_OUTPUT_FLAG_TTS;
1790     } else if (stream == AUDIO_STREAM_VOICE_CALL &&
1791                audio_is_linear_pcm(config->format) &&
1792                (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
1793         *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
1794                                        AUDIO_OUTPUT_FLAG_DIRECT);
1795         ALOGV("Set VoIP and Direct output flags for PCM format");
1796     }
1797 
1798     // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1799     if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1800         *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1801     }
1802 
1803     // Use the spatializer output if the content can be spatialized, no preferred mixer
1804     // was specified and offload or direct playback is not explicitly requested, and there is no
1805     // haptic channel included in playback
1806     *isSpatialized = false;
1807     if (mSpatializerOutput != nullptr &&
1808         canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1809         prefMixerConfigInfo == nullptr &&
1810         ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1811         checkHapticCompatibilityOnSpatializerOutput(config, session)) {
1812         *isSpatialized = true;
1813         return mSpatializerOutput->mIoHandle;
1814     }
1815 
1816     audio_config_t directConfig = *config;
1817     directConfig.channel_mask = channelMask;
1818 
1819     status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1820                                        *attr);
1821     if (status != NAME_NOT_FOUND) {
1822         return output;
1823     }
1824 
1825     // A request for HW A/V sync cannot fallback to a mixed output because time
1826     // stamps are embedded in audio data
1827     if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1828         return AUDIO_IO_HANDLE_NONE;
1829     }
1830     // A request for Tuner cannot fallback to a mixed output
1831     if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1832         return AUDIO_IO_HANDLE_NONE;
1833     }
1834 
1835     // ignoring channel mask due to downmix capability in mixer
1836 
1837     // open a non direct output
1838 
1839     // for non direct outputs, only PCM is supported
1840     if (audio_is_linear_pcm(config->format)) {
1841         // get which output is suitable for the specified stream. The actual
1842         // routing change will happen when startOutput() will be called
1843         SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
1844         if (prefMixerConfigInfo != nullptr) {
1845             for (audio_io_handle_t outputHandle : outputs) {
1846                 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1847                 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1848                     output = outputHandle;
1849                     break;
1850                 }
1851             }
1852             if (output == AUDIO_IO_HANDLE_NONE) {
1853                 // No output open with the preferred profile. Open a new one.
1854                 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1855                 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1856                 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1857                 config.format = prefMixerConfigInfo->getConfigBase().format;
1858                 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1859                         prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1860                         &config, prefMixerConfigInfo->getFlags());
1861                 if (preferredOutput == nullptr) {
1862                     ALOGE("%s failed to open output with preferred mixer config", __func__);
1863                 } else {
1864                     output = preferredOutput->mIoHandle;
1865                 }
1866             }
1867         } else {
1868             // at this stage we should ignore the DIRECT flag as no direct output could be
1869             // found earlier
1870             *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1871             if (com::android::media::audioserver::
1872                     fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1873                 // If the preferred mixer attributes is null, do not select the bit-perfect output
1874                 // unless the bit-perfect output is the only output.
1875                 // The bit-perfect output can exist while the passed in preferred mixer attributes
1876                 // info is null when it is a high priority client. The high priority clients are
1877                 // ringtone or alarm, which is not a bit-perfect use case.
1878                 size_t i = 0;
1879                 while (i < outputs.size() && outputs.size() > 1) {
1880                     auto desc = mOutputs.valueFor(outputs[i]);
1881                     // The output descriptor must not be null here.
1882                     if (desc->isBitPerfect()) {
1883                         outputs.removeItemsAt(i);
1884                     } else {
1885                         i += 1;
1886                     }
1887                 }
1888             }
1889             output = selectOutput(
1890                     outputs, *flags, config->format, channelMask, config->sample_rate, session);
1891         }
1892     }
1893     ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
1894             "sampling rate %d, format %#x, channels %#x, flags %#x",
1895             stream, config->sample_rate, config->format, channelMask, *flags);
1896 
1897     return output;
1898 }
1899 
getMsdAudioInDevice() const1900 sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1901     auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1902                                                                      mAvailableInputDevices);
1903     return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1904 }
1905 
getMsdAudioOutDevices() const1906 DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1907     return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1908                                                         mAvailableOutputDevices);
1909 }
1910 
getMsdOutputPatches() const1911 const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
1912     AudioPatchCollection msdPatches;
1913     sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1914     if (msdModule != 0) {
1915         for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1916             sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1917             for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1918                 const struct audio_port_config *source = &patch->mPatch.sources[j];
1919                 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1920                         source->ext.device.hw_module == msdModule->getHandle()) {
1921                     msdPatches.addAudioPatch(patch->getHandle(), patch);
1922                 }
1923             }
1924         }
1925     }
1926     return msdPatches;
1927 }
1928 
isMsdPatch(const audio_patch_handle_t & handle) const1929 bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1930     ssize_t index = mAudioPatches.indexOfKey(handle);
1931     if (index < 0) {
1932         return false;
1933     }
1934     const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1935     sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1936     if (msdModule == nullptr) {
1937         return false;
1938     }
1939     const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1940     if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1941         return true;
1942     }
1943     index = getMsdOutputPatches().indexOfKey(handle);
1944     if (index < 0) {
1945         return false;
1946     }
1947     return true;
1948 }
1949 
getMsdProfiles(bool hwAvSync,const InputProfileCollection & inputProfiles,const OutputProfileCollection & outputProfiles,const sp<DeviceDescriptor> & sourceDevice,const sp<DeviceDescriptor> & sinkDevice,AudioProfileVector & sourceProfiles,AudioProfileVector & sinkProfiles) const1950 status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1951                                             const InputProfileCollection &inputProfiles,
1952                                             const OutputProfileCollection &outputProfiles,
1953                                             const sp<DeviceDescriptor> &sourceDevice,
1954                                             const sp<DeviceDescriptor> &sinkDevice,
1955                                             AudioProfileVector& sourceProfiles,
1956                                             AudioProfileVector& sinkProfiles) const {
1957     if (inputProfiles.isEmpty()) {
1958         ALOGE("%s() no input profiles for source module", __func__);
1959         return NO_INIT;
1960     }
1961     if (outputProfiles.isEmpty()) {
1962         ALOGE("%s() no output profiles for sink module", __func__);
1963         return NO_INIT;
1964     }
1965     for (const auto &inProfile : inputProfiles) {
1966         if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1967                 inProfile->supportsDevice(sourceDevice)) {
1968             appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
1969         }
1970     }
1971     for (const auto &outProfile : outputProfiles) {
1972         if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
1973                 outProfile->supportsDevice(sinkDevice)) {
1974             appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
1975         }
1976     }
1977     return NO_ERROR;
1978 }
1979 
getBestMsdConfig(bool hwAvSync,const AudioProfileVector & sourceProfiles,const AudioProfileVector & sinkProfiles,audio_port_config * sourceConfig,audio_port_config * sinkConfig) const1980 status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1981         const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1982         audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1983 {
1984     // Compressed formats for MSD module, ordered from most preferred to least preferred.
1985     static const std::vector<audio_format_t> formatsOrder = {{
1986             AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1987             AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1988             AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
1989     static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1990         // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1991         // preferred).
1992         std::vector<audio_channel_mask_t> masks = {{
1993             AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1994             AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1995             AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1996         // insert index masks (higher counts most preferred) as preferred over position masks
1997         for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1998             masks.insert(
1999                     masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
2000         }
2001         return masks;
2002     }();
2003 
2004     struct audio_config_base bestSinkConfig;
2005     status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
2006             channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
2007     if (result != NO_ERROR) {
2008         ALOGD("%s() no matching config found for sink, hwAvSync: %d",
2009                 __func__, hwAvSync);
2010         return result;
2011     }
2012     sinkConfig->sample_rate = bestSinkConfig.sample_rate;
2013     sinkConfig->channel_mask = bestSinkConfig.channel_mask;
2014     sinkConfig->format = bestSinkConfig.format;
2015     // For encoded streams force direct flag to prevent downstream mixing.
2016     sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2017             sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
2018     if (audio_is_iec61937_compatible(sinkConfig->format)) {
2019         // For formats compatible with IEC61937 encapsulation, assume that
2020         // the input is IEC61937 framed (for proportional buffer sizing).
2021         // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
2022         // raw and IEC61937 framed streams.
2023         sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2024                 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2025     }
2026     sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2027     // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
2028     sourceConfig->channel_mask =
2029             audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2030             == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2031             bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
2032     sourceConfig->format = bestSinkConfig.format;
2033     // Copy input stream directly without any processing (e.g. resampling).
2034     sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2035             sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2036     if (hwAvSync) {
2037         sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2038                 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2039         sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2040                 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2041     }
2042     const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2043             AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2044     sinkConfig->config_mask |= config_mask;
2045     sourceConfig->config_mask |= config_mask;
2046     return NO_ERROR;
2047 }
2048 
buildMsdPatch(bool msdIsSource,const sp<DeviceDescriptor> & device) const2049 PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2050                                                const sp<DeviceDescriptor> &device) const
2051 {
2052     PatchBuilder patchBuilder;
2053     sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2054     ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2055     sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2056     if (deviceModule == nullptr) {
2057         ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2058         return patchBuilder;
2059     }
2060     const InputProfileCollection inputProfiles = msdIsSource ?
2061             msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2062     const OutputProfileCollection outputProfiles = msdIsSource ?
2063             deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2064 
2065     const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2066     const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2067             device : getMsdAudioOutDevices().itemAt(0);
2068     patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2069 
2070     audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2071     audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
2072     AudioProfileVector sourceProfiles;
2073     AudioProfileVector sinkProfiles;
2074     // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2075     // For now, we just forcefully try with HwAvSync first.
2076     for (auto hwAvSync : { true, false }) {
2077         if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2078                 sourceProfiles, sinkProfiles) != NO_ERROR) {
2079             continue;
2080         }
2081         if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2082                 &sinkConfig) == NO_ERROR) {
2083             // Found a matching config. Re-create PatchBuilder with this config.
2084             return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2085         }
2086     }
2087     ALOGV("%s() no matching config found. Fall through to default PCM patch"
2088             " supporting PCM format conversion.", __func__);
2089     return patchBuilder;
2090 }
2091 
setMsdOutputPatches(const DeviceVector * outputDevices)2092 status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
2093     DeviceVector devices;
2094     if (outputDevices != nullptr && outputDevices->size() > 0) {
2095         devices.add(*outputDevices);
2096     } else {
2097         // Use media strategy for unspecified output device. This should only
2098         // occur on checkForDeviceAndOutputChanges(). Device connection events may
2099         // therefore invalidate explicit routing requests.
2100         devices = mEngine->getOutputDevicesForAttributes(
2101                     attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
2102         LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
2103     }
2104     std::vector<PatchBuilder> patchesToCreate;
2105     for (auto i = 0u; i < devices.size(); ++i) {
2106         ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
2107         patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
2108     }
2109     // Retain only the MSD patches associated with outputDevices request.
2110     // Tear down the others, and create new ones as needed.
2111     AudioPatchCollection patchesToRemove = getMsdOutputPatches();
2112     for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2113         auto retainedPatch = false;
2114         for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2115             if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2116                 patchesToRemove.removeItemsAt(i);
2117                 retainedPatch = true;
2118                 break;
2119             }
2120         }
2121         if (retainedPatch) {
2122             it = patchesToCreate.erase(it);
2123             continue;
2124         }
2125         ++it;
2126     }
2127     if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2128         return NO_ERROR;
2129     }
2130     for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2131         auto &currentPatch = patchesToRemove.valueAt(i);
2132         releaseAudioPatch(currentPatch->getHandle(), mUidCached);
2133     }
2134     status_t status = NO_ERROR;
2135     for (const auto &p : patchesToCreate) {
2136         auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2137                 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2138         char message[256];
2139         snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2140             "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2141                 currStatus == NO_ERROR ? "Success" : "Error",
2142                 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2143                 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2144         if (currStatus == NO_ERROR) {
2145             ALOGD("%s", message);
2146         } else {
2147             ALOGE("%s", message);
2148             if (status == NO_ERROR) {
2149                 status = currStatus;
2150             }
2151         }
2152     }
2153     return status;
2154 }
2155 
releaseMsdOutputPatches(const DeviceVector & devices)2156 void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2157     AudioPatchCollection msdPatches = getMsdOutputPatches();
2158     for (size_t i = 0; i < msdPatches.size(); i++) {
2159         const auto& patch = msdPatches[i];
2160         for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2161             const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2162             if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2163                     String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2164                 releaseAudioPatch(patch->getHandle(), mUidCached);
2165                 break;
2166             }
2167         }
2168     }
2169 }
2170 
msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector & devices)2171 bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
2172     DeviceVector devicesToCheck =
2173             mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
2174     AudioPatchCollection msdPatches = getMsdOutputPatches();
2175     for (size_t i = 0; i < msdPatches.size(); i++) {
2176         const auto& patch = msdPatches[i];
2177         for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2178             const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2179             if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2180                 const auto& foundDevice = devicesToCheck.getDevice(
2181                     sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2182                 if (foundDevice != nullptr) {
2183                     devicesToCheck.remove(foundDevice);
2184                     if (devicesToCheck.isEmpty()) {
2185                         return true;
2186                     }
2187                 }
2188             }
2189         }
2190     }
2191     return false;
2192 }
2193 
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)2194 audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
2195                                                    audio_output_flags_t flags,
2196                                                    audio_format_t format,
2197                                                    audio_channel_mask_t channelMask,
2198                                                    uint32_t samplingRate,
2199                                                    audio_session_t sessionId)
2200 {
2201     LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2202         "%s called with format %#x", __func__, format);
2203 
2204     // Return the output that haptic-generating attached to when 1) session id is specified,
2205     // 2) haptic-generating effect exists for given session id and 3) the output that
2206     // haptic-generating effect attached to is in given outputs.
2207     if (sessionId != AUDIO_SESSION_NONE) {
2208         audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2209                 sessionId, FX_IID_HAPTICGENERATOR);
2210         if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2211             return hapticGeneratingOutput;
2212         }
2213     }
2214 
2215     // Flags disqualifying an output: the match must happen before calling selectOutput()
2216     static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2217         (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2218 
2219     // Flags expressing a functional request: must be honored in priority over
2220     // other criteria
2221     static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2222         (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
2223             AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2224             AUDIO_OUTPUT_FLAG_SPATIALIZER);
2225     // Flags expressing a performance request: have lower priority than serving
2226     // requested sampling rate or channel mask
2227     static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2228         (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2229             AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2230 
2231     const audio_output_flags_t functionalFlags =
2232         (audio_output_flags_t)(flags & kFunctionalFlags);
2233     const audio_output_flags_t performanceFlags =
2234         (audio_output_flags_t)(flags & kPerformanceFlags);
2235 
2236     audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2237 
2238     // select one output among several that provide a path to a particular device or set of
2239     // devices (the list was previously build by getOutputsForDevices()).
2240     // The priority is as follows:
2241     // 1: the output supporting haptic playback when requesting haptic playback
2242     // 2: the output with the highest number of requested functional flags
2243     //    with tiebreak preferring the minimum number of extra functional flags
2244     //    (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
2245     // 3: the output supporting the exact channel mask
2246     // 4: the output with a higher channel count than requested
2247     // 5: the output with the highest sampling rate if the requested sample rate is
2248     //    greater than default sampling rate
2249     // 6: the output with the highest number of requested performance flags
2250     // 7: the output with the bit depth the closest to the requested one
2251     // 8: the primary output
2252     // 9: the first output in the list
2253 
2254     // matching criteria values in priority order for best matching output so far
2255     std::vector<uint32_t> bestMatchCriteria(8, 0);
2256 
2257     const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
2258     const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2259     const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2260         channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2261 
2262     for (audio_io_handle_t output : outputs) {
2263         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2264         // matching criteria values in priority order for current output
2265         std::vector<uint32_t> currentMatchCriteria(8, 0);
2266 
2267         if (outputDesc->isDuplicated()) {
2268             continue;
2269         }
2270         if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2271             continue;
2272         }
2273 
2274         // If haptic channel is specified, use the haptic output if present.
2275         // When using haptic output, same audio format and sample rate are required.
2276         const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
2277             outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
2278         // skip if haptic channel specified but output does not support it, or output support haptic
2279         // but there is no haptic channel requested AND no orphan haptic effect exist
2280         if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2281             (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
2282             continue;
2283         }
2284         // In the case of audio-coupled-haptic playback, there is no format conversion and
2285         // resampling in the framework, same format/channel/sampleRate for client and the output
2286         // thread is required. In the case of HapticGenerator effect, do not require format
2287         // matching.
2288         if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2289              samplingRate == outputDesc->getSamplingRate()) ||
2290             (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
2291             currentMatchCriteria[0] = outputHapticChannelCount;
2292         }
2293 
2294         // functional flags match
2295         const int matchingFunctionalFlags =
2296                 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2297         const int totalFunctionalFlags =
2298                 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2299         // Prefer matching functional flags, but subtract unnecessary functional flags.
2300         currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
2301 
2302         // channel mask and channel count match
2303         uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2304                 outputDesc->getChannelMask());
2305         if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2306             channelCount <= outputChannelCount) {
2307             if ((audio_channel_mask_get_representation(channelMask) ==
2308                     audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2309                     ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
2310                 currentMatchCriteria[2] = outputChannelCount;
2311             }
2312             currentMatchCriteria[3] = outputChannelCount;
2313         }
2314 
2315         // sampling rate match
2316         if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
2317             int diff;  // avoid unsigned integer overflow.
2318             __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2319 
2320             // prefer the closest output sampling rate greater than or equal to target
2321             // if none exists, prefer the closest output sampling rate less than target.
2322             //
2323             // criteria is offset to make non-negative.
2324             currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
2325         }
2326 
2327         // performance flags match
2328         currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2329 
2330         // format match
2331         if (format != AUDIO_FORMAT_INVALID) {
2332             currentMatchCriteria[6] =
2333                 PolicyAudioPort::kFormatDistanceMax -
2334                 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
2335         }
2336 
2337         // primary output match
2338         currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2339 
2340         // compare match criteria by priority then value
2341         if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2342                 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2343             bestMatchCriteria = currentMatchCriteria;
2344             bestOutput = output;
2345 
2346             std::stringstream result;
2347             std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2348                 std::ostream_iterator<int>(result, " "));
2349             ALOGV("%s new bestOutput %d criteria %s",
2350                 __func__, bestOutput, result.str().c_str());
2351         }
2352     }
2353 
2354     return bestOutput;
2355 }
2356 
startOutput(audio_port_handle_t portId)2357 status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
2358 {
2359     ALOGV("%s portId %d", __FUNCTION__, portId);
2360 
2361     sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2362     if (outputDesc == 0) {
2363         ALOGW("startOutput() no output for client %d", portId);
2364         return DEAD_OBJECT;
2365     }
2366     sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2367 
2368     ALOGV("startOutput() output %d, stream %d, session %d",
2369           outputDesc->mIoHandle, client->stream(), client->session());
2370 
2371     if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2372             && gHighPriorityUseCases.count(client->attributes().usage) != 0
2373             && outputDesc->isBitPerfect()) {
2374         // Usually, APM selects bit-perfect output for high priority use cases only when
2375         // bit-perfect output is the only output that can be routed to the selected device.
2376         // However, here is no need to play high priority use cases such as ringtone and alarm
2377         // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2378         // can attach to new output.
2379         ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2380               __func__, client->stream());
2381         reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2382         return DEAD_OBJECT;
2383     }
2384 
2385     status_t status = outputDesc->start();
2386     if (status != NO_ERROR) {
2387         return status;
2388     }
2389 
2390     uint32_t delayMs;
2391     status = startSource(outputDesc, client, &delayMs);
2392 
2393     if (status != NO_ERROR) {
2394         outputDesc->stop();
2395         if (status == DEAD_OBJECT) {
2396             sp<SwAudioOutputDescriptor> desc =
2397                     reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2398             if (desc == nullptr) {
2399                 // This is not common, it may indicate something wrong with the HAL.
2400                 ALOGE("%s unable to open output with default config", __func__);
2401                 return status;
2402             }
2403         }
2404         return status;
2405     }
2406 
2407     // If the client is the first one active on preferred mixer parameters, reopen the output
2408     // if the current mixer parameters doesn't match the preferred one.
2409     if (outputDesc->devices().size() == 1) {
2410         sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2411                 outputDesc->devices()[0]->getId(), client->strategy());
2412         if (info != nullptr && info->getUid() == client->uid()) {
2413             if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2414                     info->getConfigBase(), info->getFlags())) {
2415                 stopSource(outputDesc, client);
2416                 outputDesc->stop();
2417                 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2418                 config.channel_mask = info->getConfigBase().channel_mask;
2419                 config.sample_rate = info->getConfigBase().sample_rate;
2420                 config.format = info->getConfigBase().format;
2421                 sp<SwAudioOutputDescriptor> desc =
2422                         reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2423                 if (desc == nullptr) {
2424                     return BAD_VALUE;
2425                 }
2426                 desc->mPreferredAttrInfo = info;
2427                 // Intentionally return error to let the client side resending request for
2428                 // creating and starting.
2429                 return DEAD_OBJECT;
2430             }
2431             info->increaseActiveClient();
2432             if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
2433                 // If it is first bit-perfect client, reroute all clients that will be routed to
2434                 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2435                 PortHandleVector clientsToInvalidate;
2436                 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
2437                 for (size_t i = 0; i < mOutputs.size(); i++) {
2438                     if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2439                         mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
2440                         continue;
2441                     }
2442                     if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2443                         outputsToResetDevice.push_back(mOutputs[i]);
2444                     }
2445                     for (const auto& c : mOutputs[i]->getClientIterable()) {
2446                         clientsToInvalidate.push_back(c->portId());
2447                     }
2448                 }
2449                 if (!clientsToInvalidate.empty()) {
2450                     ALOGD("%s Invalidate clients due to first bit-perfect client started",
2451                           __func__);
2452                     mpClientInterface->invalidateTracks(clientsToInvalidate);
2453                 }
2454                 for (const auto& output : outputsToResetDevice) {
2455                     resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2456                 }
2457             }
2458         }
2459     }
2460 
2461     if (client->hasPreferredDevice()) {
2462         // playback activity with preferred device impacts routing occurred, inform upper layers
2463         mpClientInterface->onRoutingUpdated();
2464     }
2465     if (delayMs != 0) {
2466         usleep(delayMs * 1000);
2467     }
2468 
2469     if (status == NO_ERROR &&
2470         outputDesc->mPreferredAttrInfo != nullptr &&
2471         outputDesc->isBitPerfect() &&
2472         com::android::media::audioserver::
2473                 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2474         // A new client is started on bit-perfect output, update all clients internal mute.
2475         updateClientsInternalMute(outputDesc);
2476     }
2477 
2478     return status;
2479 }
2480 
isLeUnicastActive() const2481 bool AudioPolicyManager::isLeUnicastActive() const {
2482     if (isInCall()) {
2483         return true;
2484     }
2485     return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2486 }
2487 
isAnyDeviceTypeActive(const DeviceTypeSet & deviceTypes) const2488 bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2489     if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2490         return false;
2491     }
2492     bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2493     ALOGV("%s active %d", __func__, active);
2494     return active;
2495 }
2496 
startSource(const sp<SwAudioOutputDescriptor> & outputDesc,const sp<TrackClientDescriptor> & client,uint32_t * delayMs)2497 status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2498                                          const sp<TrackClientDescriptor>& client,
2499                                          uint32_t *delayMs)
2500 {
2501     // cannot start beacon playback if any other output is being used
2502     uint32_t beaconMuteLatency = 0;
2503 
2504     *delayMs = 0;
2505     audio_stream_type_t stream = client->stream();
2506     auto clientVolSrc = client->volumeSource();
2507     auto clientStrategy = client->strategy();
2508     auto clientAttr = client->attributes();
2509     // SPEAKER_CLEANUP doesn't the share the high-frequency requirements of beacons
2510     if (clientAttr.usage != AUDIO_USAGE_SPEAKER_CLEANUP) {
2511         if (stream == AUDIO_STREAM_TTS) {
2512             ALOGV("\t found BEACON stream");
2513             if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
2514                     toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
2515                 return INVALID_OPERATION;
2516             } else {
2517                 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2518             }
2519         } else {
2520             // some playback other than beacon starts
2521             beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2522         }
2523     } else {
2524         // TODO handle muting of other streams outside of a11y
2525     }
2526 
2527     // force device change if the output is inactive and no audio patch is already present.
2528     // check active before incrementing usage count
2529     bool force = !outputDesc->isActive() && !outputDesc->isRouted();
2530 
2531     DeviceVector devices;
2532     sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
2533     const char *address = NULL;
2534     if (policyMix != nullptr) {
2535         audio_devices_t newDeviceType;
2536         address = policyMix->mDeviceAddress.c_str();
2537         if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2538             newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2539         } else {
2540             newDeviceType = policyMix->mDeviceType;
2541         }
2542         sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2543                                                         AUDIO_FORMAT_DEFAULT);
2544         ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2545         devices.add(device);
2546     }
2547 
2548     // requiresMuteCheck is false when we can bypass mute strategy.
2549     // It covers a common case when there is no materially active audio
2550     // and muting would result in unnecessary delay and dropped audio.
2551     const uint32_t outputLatencyMs = outputDesc->latency();
2552     bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2);  // account for drain
2553     bool wasLeUnicastActive = isLeUnicastActive();
2554 
2555     // increment usage count for this stream on the requested output:
2556     // NOTE that the usage count is the same for duplicated output and hardware output which is
2557     // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
2558     outputDesc->setClientActive(client, true);
2559 
2560     if (client->hasPreferredDevice(true)) {
2561         if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
2562             // Preferred device may be exclusive, use only if no other active clients on this output
2563             devices = DeviceVector(
2564                         mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2565         } else {
2566             devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2567         }
2568         if (devices != outputDesc->devices()) {
2569             checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
2570         }
2571     }
2572 
2573     if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
2574         selectOutputForMusicEffects();
2575     }
2576 
2577     if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
2578         // starting an output being rerouted?
2579         if (devices.isEmpty()) {
2580             devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2581         }
2582         bool shouldWait =
2583             (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2584              followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2585              (beaconMuteLatency > 0));
2586         uint32_t waitMs = beaconMuteLatency;
2587         const bool needToCloseBitPerfectOutput =
2588                 (com::android::media::audioserver::
2589                         fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2590                 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2591         std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
2592         for (size_t i = 0; i < mOutputs.size(); i++) {
2593             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2594             if (desc != outputDesc) {
2595                 // An output has a shared device if
2596                 // - managed by the same hw module
2597                 // - supports the currently selected device
2598                 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
2599                         && (!desc->filterSupportedDevices(devices).isEmpty());
2600 
2601                 // force a device change if any other output is:
2602                 // - managed by the same hw module
2603                 // - supports currently selected device
2604                 // - has a current device selection that differs from selected device.
2605                 // - has an active audio patch
2606                 // In this case, the audio HAL must receive the new device selection so that it can
2607                 // change the device currently selected by the other output.
2608                 if (sharedDevice &&
2609                         desc->devices() != devices &&
2610                         desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2611                     force = true;
2612                 }
2613                 // wait for audio on other active outputs to be presented when starting
2614                 // a notification so that audio focus effect can propagate, or that a mute/unmute
2615                 // event occurred for beacon
2616                 const uint32_t latencyMs = desc->latency();
2617                 const bool isActive = desc->isActive(latencyMs * 2);  // account for drain
2618 
2619                 if (shouldWait && isActive && (waitMs < latencyMs)) {
2620                     waitMs = latencyMs;
2621                 }
2622 
2623                 // Require mute check if another output is on a shared device
2624                 // and currently active to have proper drain and avoid pops.
2625                 // Note restoring AudioTracks onto this output needs to invoke
2626                 // a volume ramp if there is no mute.
2627                 requiresMuteCheck |= sharedDevice && isActive;
2628 
2629                 if (desc->isBitPerfect()) {
2630                     if (needToCloseBitPerfectOutput) {
2631                         outputsToReopen.push_back(desc);
2632                     } else if (!desc->devices().filter(devices).isEmpty()) {
2633                         // There is an active bit-perfect playback on one of the targeted device,
2634                         // the client should be reattached to the bit-perfect thread.
2635                         ALOGD("%s, fails as there is bit-perfect playback active", __func__);
2636                         return DEAD_OBJECT;
2637                     }
2638                 }
2639             }
2640         }
2641 
2642         if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
2643             // If the output is open with preferred mixer attributes, but the routed device is
2644             // changed when calling this function, returning DEAD_OBJECT to indicate routing
2645             // changed.
2646             return DEAD_OBJECT;
2647         }
2648         for (auto& outputToReopen : outputsToReopen) {
2649             reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2650         }
2651         const uint32_t muteWaitMs =
2652                 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2653                                  requiresMuteCheck);
2654 
2655         // apply volume rules for current stream and device if necessary
2656         auto &curves = getVolumeCurves(client->attributes());
2657         if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
2658                           curves.getVolumeIndex(outputDesc->devices().types()),
2659                           outputDesc, outputDesc->devices().types(), 0 /*delay*/,
2660                           outputDesc->useHwGain() /*force*/)) {
2661             // request AudioService to reinitialize the volume curves asynchronously
2662             ALOGE("checkAndSetVolume failed, requesting volume range init");
2663             mpClientInterface->onVolumeRangeInitRequest();
2664         };
2665 
2666         // update the outputs if starting an output with a stream that can affect notification
2667         // routing
2668         handleNotificationRoutingForStream(stream);
2669 
2670         // force reevaluating accessibility routing when ringtone or alarm starts
2671         if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
2672             invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
2673         }
2674 
2675         if (waitMs > muteWaitMs) {
2676             *delayMs = waitMs - muteWaitMs;
2677         }
2678 
2679         // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2680         // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2681         // via AudioCommandThread to AudioFlinger.  Hence it is possible that the volume
2682         // change occurs after the MixerThread starts and causes a stream volume
2683         // glitch.
2684         //
2685         // We do not introduce additional delay here.
2686     }
2687 
2688     if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2689             mEngine->getForceUse(
2690                     AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
2691         setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
2692     }
2693 
2694     // Automatically enable the remote submix input when output is started on a re routing mix
2695     // of type MIX_TYPE_RECORDERS
2696     if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2697         policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
2698         setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2699                                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2700                                     address,
2701                                     "remote-submix",
2702                                     AUDIO_FORMAT_DEFAULT);
2703     }
2704 
2705     checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2706 
2707     return NO_ERROR;
2708 }
2709 
checkLeBroadcastRoutes(bool wasUnicastActive,sp<SwAudioOutputDescriptor> ignoredOutput,uint32_t delayMs)2710 void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2711         sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2712     bool isUnicastActive = isLeUnicastActive();
2713 
2714     if (wasUnicastActive != isUnicastActive) {
2715         std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
2716         //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2717         for (size_t i = 0; i < mOutputs.size(); i++) {
2718             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2719             if (desc != ignoredOutput && desc->isActive()
2720                     && ((isUnicastActive &&
2721                             !desc->devices().
2722                                     getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2723                         || (wasUnicastActive &&
2724                             !desc->devices().getDevicesFromTypes(
2725                                     getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2726                 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2727                 bool force = desc->devices() != newDevices;
2728                 if (desc->mPreferredAttrInfo != nullptr && force) {
2729                     // If the device is using preferred mixer attributes, the output need to reopen
2730                     // with default configuration when the new selected devices are different from
2731                     // current routing devices.
2732                     outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2733                     continue;
2734                 }
2735                 setOutputDevices(__func__, desc, newDevices, force, delayMs);
2736                 // re-apply device specific volume if not done by setOutputDevice()
2737                 if (!force) {
2738                     applyStreamVolumes(desc, newDevices.types(), delayMs);
2739                 }
2740             }
2741         }
2742         reopenOutputsWithDevices(outputsToReopen);
2743     }
2744 }
2745 
stopOutput(audio_port_handle_t portId)2746 status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
2747 {
2748     ALOGV("%s portId %d", __FUNCTION__, portId);
2749 
2750     sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2751     if (outputDesc == 0) {
2752         ALOGW("stopOutput() no output for client %d", portId);
2753         return DEAD_OBJECT;
2754     }
2755     sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2756 
2757     if (client->hasPreferredDevice(true)) {
2758         // playback activity with preferred device impacts routing occurred, inform upper layers
2759         mpClientInterface->onRoutingUpdated();
2760     }
2761 
2762     ALOGV("stopOutput() output %d, stream %d, session %d",
2763           outputDesc->mIoHandle, client->stream(), client->session());
2764 
2765     status_t status = stopSource(outputDesc, client);
2766 
2767     if (status == NO_ERROR ) {
2768         outputDesc->stop();
2769     } else {
2770         return status;
2771     }
2772 
2773     if (outputDesc->devices().size() == 1) {
2774         sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2775                 outputDesc->devices()[0]->getId(), client->strategy());
2776         bool outputReopened = false;
2777         if (info != nullptr && info->getUid() == client->uid()) {
2778             info->decreaseActiveClient();
2779             if (info->getActiveClientCount() == 0) {
2780                 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2781                 outputReopened = true;
2782             }
2783         }
2784         if (com::android::media::audioserver::
2785                     fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2786             !outputReopened && outputDesc->isBitPerfect()) {
2787             // Only need to update the clients' internal mute when the output is bit-perfect and it
2788             // is not reopened.
2789             updateClientsInternalMute(outputDesc);
2790         }
2791     }
2792     return status;
2793 }
2794 
stopSource(const sp<SwAudioOutputDescriptor> & outputDesc,const sp<TrackClientDescriptor> & client)2795 status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2796                                         const sp<TrackClientDescriptor>& client)
2797 {
2798     // always handle stream stop, check which stream type is stopping
2799     audio_stream_type_t stream = client->stream();
2800     auto clientVolSrc = client->volumeSource();
2801     bool wasLeUnicastActive = isLeUnicastActive();
2802 
2803     // speaker cleanup is not a beacon event
2804     // TODO handle speaker cleanup activity
2805     if (client->attributes().usage != AUDIO_USAGE_SPEAKER_CLEANUP) {
2806         handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2807     }
2808 
2809     if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2810         if (outputDesc->getActivityCount(clientVolSrc) == 1) {
2811             // Automatically disable the remote submix input when output is stopped on a
2812             // re routing mix of type MIX_TYPE_RECORDERS
2813             sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
2814             if (isSingleDeviceType(
2815                     outputDesc->devices().types(), &audio_is_remote_submix_device) &&
2816                 policyMix != nullptr &&
2817                 policyMix->mMixType == MIX_TYPE_RECORDERS) {
2818                 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2819                                             AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2820                                             policyMix->mDeviceAddress,
2821                                             "remote-submix", AUDIO_FORMAT_DEFAULT);
2822             }
2823         }
2824         bool forceDeviceUpdate = false;
2825         if (client->hasPreferredDevice(true) &&
2826                 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
2827             checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
2828             forceDeviceUpdate = true;
2829         }
2830 
2831         // decrement usage count of this stream on the output
2832         outputDesc->setClientActive(client, false);
2833 
2834         // store time at which the stream was stopped - see isStreamActive()
2835         if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
2836             outputDesc->setStopTime(client, systemTime());
2837             DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2838 
2839             // If the routing does not change, if an output is routed on a device using HwGain
2840             // (aka setAudioPortConfig) and there are still active clients following different
2841             // volume group(s), force reapply volume
2842             bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2843                     outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2844 
2845             // delay the device switch by twice the latency because stopOutput() is executed when
2846             // the track stop() command is received and at that time the audio track buffer can
2847             // still contain data that needs to be drained. The latency only covers the audio HAL
2848             // and kernel buffers. Also the latency does not always include additional delay in the
2849             // audio path (audio DSP, CODEC ...)
2850             setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
2851                              nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
2852 
2853             // force restoring the device selection on other active outputs if it differs from the
2854             // one being selected for this output
2855             std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
2856             uint32_t delayMs = outputDesc->latency()*2;
2857             for (size_t i = 0; i < mOutputs.size(); i++) {
2858                 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2859                 if (desc != outputDesc &&
2860                         desc->isActive() &&
2861                         outputDesc->sharesHwModuleWith(desc) &&
2862                         (newDevices != desc->devices())) {
2863                     DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2864                     bool force = desc->devices() != newDevices2;
2865 
2866                     if (desc->mPreferredAttrInfo != nullptr && force) {
2867                         // If the device is using preferred mixer attributes, the output need to
2868                         // reopen with default configuration when the new selected devices are
2869                         // different from current routing devices.
2870                         outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2871                         continue;
2872                     }
2873                     setOutputDevices(__func__, desc, newDevices2, force, delayMs);
2874 
2875                     // re-apply device specific volume if not done by setOutputDevice()
2876                     if (!force) {
2877                         applyStreamVolumes(desc, newDevices2.types(), delayMs);
2878                     }
2879                 }
2880             }
2881             reopenOutputsWithDevices(outputsToReopen);
2882             // update the outputs if stopping one with a stream that can affect notification routing
2883             handleNotificationRoutingForStream(stream);
2884         }
2885 
2886         if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2887                 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
2888             setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
2889         }
2890 
2891         if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
2892             selectOutputForMusicEffects();
2893         }
2894 
2895         checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2896 
2897         return NO_ERROR;
2898     } else {
2899         ALOGW("stopOutput() refcount is already 0");
2900         return INVALID_OPERATION;
2901     }
2902 }
2903 
releaseOutput(audio_port_handle_t portId)2904 bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
2905 {
2906     ALOGV("%s portId %d", __FUNCTION__, portId);
2907 
2908     sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2909     if (outputDesc == 0) {
2910         // If an output descriptor is closed due to a device routing change,
2911         // then there are race conditions with releaseOutput from tracks
2912         // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2913         // destroyed shortly thereafter.
2914         //
2915         // Here we just log a warning, instead of a fatal error.
2916         ALOGW("releaseOutput() no output for client %d", portId);
2917         return false;
2918     }
2919 
2920     ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
2921 
2922     sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2923     if (outputDesc->isClientActive(client)) {
2924         ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2925         stopOutput(portId);
2926     }
2927 
2928     if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2929         if (outputDesc->mDirectOpenCount <= 0) {
2930             ALOGW("releaseOutput() invalid open count %d for output %d",
2931                   outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
2932             return false;
2933         }
2934         if (--outputDesc->mDirectOpenCount == 0) {
2935             closeOutput(outputDesc->mIoHandle);
2936             mpClientInterface->onAudioPortListUpdate();
2937         }
2938     }
2939 
2940     outputDesc->removeClient(portId);
2941     if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2942         // The output is pending reopened to query dynamic profiles and
2943         // there is no active clients
2944         closeOutput(outputDesc->mIoHandle);
2945         sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2946                 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2947         if (newOutputDesc == nullptr) {
2948             ALOGE("%s failed to open output", __func__);
2949         }
2950         return true;
2951     }
2952     return false;
2953 }
2954 
2955 
getMixType(audio_devices_t deviceType,bool externallyRouted,const sp<AudioPolicyMix> & mix)2956 static AudioPolicyClientInterface::MixType getMixType(audio_devices_t deviceType,
2957                                                       bool externallyRouted,
2958                                                       const sp<AudioPolicyMix>& mix) {
2959     using MixType = AudioPolicyClientInterface::MixType;
2960     // If the client chose the route, special perms
2961     if (externallyRouted) {
2962         if (is_mix_loopback_render(mix->mRouteFlags)) {
2963             return MixType::PUBLIC_CAPTURE_PLAYBACK;
2964         }
2965         return MixType::EXT_POLICY_REROUTE;
2966     }
2967     switch (deviceType) {
2968         case AUDIO_DEVICE_IN_ECHO_REFERENCE:
2969             return MixType::CAPTURE;
2970         case AUDIO_DEVICE_IN_TELEPHONY_RX:
2971             return MixType::TELEPHONY_RX_CAPTURE;
2972         case AUDIO_DEVICE_IN_REMOTE_SUBMIX:
2973             if (!mix) {
2974                 return MixType::CAPTURE;
2975             } else {
2976                 ALOG_ASSERT(mix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2977                 // when routed due to a policy, no perms (client not in control)
2978                 // there is an external policy, but this input is attached to a mix of recorders,
2979                 // meaning it receives audio injected into the framework, so the recorder doesn't
2980                 // know about it and is therefore considered "legacy"
2981                 return MixType::NONE;
2982             }
2983         default:
2984             return MixType::NONE;
2985     }
2986 }
2987 
2988 base::expected<media::GetInputForAttrResponse, std::variant<binder::Status, AudioConfigBase>>
getInputForAttr(audio_attributes_t attributes_,audio_io_handle_t requestedInput,audio_port_handle_t requestedDeviceId,audio_config_base_t config,const audio_input_flags_t flags,audio_unique_id_t riid,audio_session_t session,const AttributionSourceState & attributionSource)2989 AudioPolicyManager::getInputForAttr(audio_attributes_t attributes_,
2990                                      audio_io_handle_t requestedInput,
2991                                      audio_port_handle_t requestedDeviceId,
2992                                      audio_config_base_t config,
2993                                      const audio_input_flags_t flags,
2994                                      audio_unique_id_t riid,
2995                                      audio_session_t session,
2996                                      const AttributionSourceState& attributionSource)
2997 {
2998     ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2999           "flags %#x attributes=%s requested device ID %d",
3000           __func__, attributes_.source, config.sample_rate, config.format, config.channel_mask,
3001           session, flags, toString(attributes_).c_str(), requestedDeviceId);
3002 
3003     sp<AudioPolicyMix> policyMix;
3004     sp<DeviceDescriptor> device;
3005     sp<AudioInputDescriptor> inputDesc;
3006     sp<AudioInputDescriptor> previousInputDesc;
3007     sp<RecordClientDescriptor> clientDesc;
3008     uid_t uid = static_cast<uid_t>(attributionSource.uid);
3009     bool isSoundTrigger;
3010     int vdi = 0 /* default device id */;
3011     audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3012 
3013     if (attributes_.source == AUDIO_SOURCE_DEFAULT) {
3014         attributes_.source = AUDIO_SOURCE_MIC;
3015     }
3016 
3017     const auto& attributes = attributes_;
3018 
3019     bool externallyRouted = false;
3020     // Explicit routing?
3021     sp<DeviceDescriptor> explicitRoutingDevice =
3022             mAvailableInputDevices.getDeviceFromId(requestedDeviceId);
3023 
3024     // special case for mmap capture: if an input IO handle is specified, we reuse this input if
3025     // possible
3026     if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
3027             requestedInput != AUDIO_IO_HANDLE_NONE) {
3028         ssize_t index = mInputs.indexOfKey(requestedInput);
3029         if (index < 0) {
3030             return base::unexpected{Status::fromExceptionCode(
3031                     EX_ILLEGAL_ARGUMENT,
3032                     String8::format("%s unknown MMAP input %d", __func__, requestedInput))};
3033         }
3034         sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
3035         RecordClientVector clients = inputDesc->getClientsForSession(session);
3036         if (clients.size() == 0) {
3037             return base::unexpected{Status::fromExceptionCode(
3038                     EX_ILLEGAL_ARGUMENT, String8::format("%s unknown session %d on input %d",
3039                                                          __func__, session, requestedInput))};
3040         }
3041         // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
3042         // The second call is for the first active client and sets the UID. Any further call
3043         // corresponds to a new client and is only permitted from the same UID.
3044         // If the first UID is silenced, allow a new UID connection and replace with new UID
3045         if (clients.size() > 1) {
3046             for (const auto& client : clients) {
3047                 // The client map is ordered by key values (portId) and portIds are allocated
3048                 // incrementaly. So the first client in this list is the one opened by audio flinger
3049                 // when the mmap stream is created and should be ignored as it does not correspond
3050                 // to an actual client
3051                 if (client == *clients.cbegin()) {
3052                     continue;
3053                 }
3054                 if (uid != client->uid() && !client->isSilenced()) {
3055                     return base::unexpected{Status::fromExceptionCode(
3056                             EX_ILLEGAL_STATE,
3057                             String8::format("%s bad uid %d for client %d uid %d", __func__, uid,
3058                                             client->portId(), client->uid()))};
3059                 }
3060             }
3061         }
3062         input = requestedInput;
3063         device = inputDesc->getDevice();
3064     } else if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
3065                 extractAddressFromAudioAttributes(attributes).has_value()) {
3066         status_t status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
3067         if (status != NO_ERROR) {
3068             ALOGW("%s could not find input mix for attr %s",
3069                     __func__, toString(attributes).c_str());
3070             return base::unexpected {aidl_utils::binderStatusFromStatusT(status)};
3071         }
3072         device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3073                                                   String8(attributes.tags + strlen("addr=")),
3074                                                   AUDIO_FORMAT_DEFAULT);
3075         externallyRouted = true;
3076     } else {
3077         if (explicitRoutingDevice != nullptr) {
3078             device = explicitRoutingDevice;
3079         } else {
3080             // Prevent from storing invalid requested device id in clients
3081             requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
3082             device = mEngine->getInputDeviceForAttributes(
3083                     attributes, true /*ignorePreferredDevice*/, uid, session, &policyMix);
3084             ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3085                 __FUNCTION__, device->type());
3086         }
3087     }
3088 
3089     if (device == nullptr) {
3090         const auto attr = legacy2aidl_audio_attributes_t_AudioAttributes(attributes);
3091         return base::unexpected{Status::fromExceptionCode(
3092                 EX_ILLEGAL_ARGUMENT,
3093                 String8::format("%s could not find device for attr %s", __func__,
3094                                 attr.has_value() ? attr->toString().c_str() : ""))};
3095     }
3096 
3097     const auto mixType = getMixType(device->type(), externallyRouted, policyMix);
3098     const AudioPolicyClientInterface::PermissionReqs permReq {
3099         .source =  legacy2aidl_audio_source_t_AudioSource(attributes.source).value(),
3100         .mixType = mixType,
3101         .virtualDeviceId = (mixType == AudioPolicyClientInterface::MixType::NONE &&
3102                             policyMix != nullptr) ? policyMix->mVirtualDeviceId : 0,
3103 
3104         .isHotword = (flags & (AUDIO_INPUT_FLAG_HW_HOTWORD | AUDIO_INPUT_FLAG_HOTWORD_TAP |
3105                                AUDIO_INPUT_FLAG_HW_LOOKBACK)) != 0,
3106         .isCallRedir = (attributes.flags & AUDIO_FLAG_CALL_REDIRECTION) != 0,
3107     };
3108 
3109     auto permRes = mpClientInterface->checkPermissionForInput(attributionSource, permReq);
3110     if (!permRes.has_value()) return base::unexpected {permRes.error()};
3111     if (!permRes.value()) {
3112         return base::unexpected{Status::fromExceptionCode(
3113                 EX_SECURITY, String8::format("%s: %s missing perms for source %d mix %d vdi %d"
3114                     "hotword? %d callredir? %d", __func__, attributionSource.toString().c_str(),
3115                                              static_cast<int>(permReq.source),
3116                                              static_cast<int>(permReq.mixType),
3117                                              permReq.virtualDeviceId,
3118                                              permReq.isHotword,
3119                                              permReq.isCallRedir))};
3120     }
3121 
3122     if (input == AUDIO_IO_HANDLE_NONE) {
3123         input = getInputForDevice(device, session, attributes, config, flags, policyMix);
3124         if (input == AUDIO_IO_HANDLE_NONE) {
3125             AudioProfileVector profiles;
3126             status_t ret = getProfilesForDevices(
3127                     DeviceVector(device), profiles, flags, true /*isInput*/);
3128             if (ret == NO_ERROR && !profiles.empty()) {
3129                 const auto channels = profiles[0]->getChannels();
3130                 if (!channels.empty() && (channels.find(config.channel_mask) == channels.end())) {
3131                     config.channel_mask = *channels.begin();
3132                 }
3133                 const auto sampleRates = profiles[0]->getSampleRates();
3134                 if (!sampleRates.empty() &&
3135                         (sampleRates.find(config.sample_rate) == sampleRates.end())) {
3136                     config.sample_rate = *sampleRates.begin();
3137                 }
3138                 config.format = profiles[0]->getFormat();
3139             }
3140             const auto suggestedConfig = VALUE_OR_FATAL(
3141                 legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/));
3142             return base::unexpected {suggestedConfig};
3143         }
3144     }
3145 
3146     auto selectedDeviceId = mAvailableInputDevices.contains(device) ?
3147                 device->getId() : AUDIO_PORT_HANDLE_NONE;
3148 
3149     isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
3150         mSoundTriggerSessions.indexOfKey(session) >= 0;
3151 
3152     const auto allocatedPortId = PolicyAudioPort::getNextUniqueId();
3153 
3154     clientDesc = new RecordClientDescriptor(allocatedPortId, riid, uid, session, attributes, config,
3155                                             requestedDeviceId, attributes.source, flags,
3156                                             isSoundTrigger);
3157     inputDesc = mInputs.valueFor(input);
3158     // Move (if found) effect for the client session to its input
3159     mEffects.moveEffectsForIo(session, input, &mInputs, mpClientInterface);
3160     inputDesc->addClient(clientDesc);
3161 
3162     ALOGV("getInputForAttr() returns input %d selectedDeviceId %d vdi %d for port ID %d",
3163             input, selectedDeviceId, permReq.virtualDeviceId, allocatedPortId);
3164 
3165     auto ret = media::GetInputForAttrResponse {};
3166     ret.input = input;
3167     ret.selectedDeviceId = selectedDeviceId;
3168     ret.portId = allocatedPortId;
3169     ret.virtualDeviceId = permReq.virtualDeviceId;
3170     ret.config = legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/).value();
3171     ret.source = legacy2aidl_audio_source_t_AudioSource(attributes.source).value();
3172     return ret;
3173 }
3174 
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)3175 audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor>& device,
3176                                                         audio_session_t session,
3177                                                         const audio_attributes_t& attributes,
3178                                                         const audio_config_base_t& config,
3179                                                         audio_input_flags_t flags,
3180                                                         const sp<AudioPolicyMix>& policyMix) {
3181     audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3182     audio_source_t halInputSource = attributes.source;
3183     bool isSoundTrigger = false;
3184 
3185     if (attributes.source == AUDIO_SOURCE_HOTWORD) {
3186         ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3187         if (index >= 0) {
3188             input = mSoundTriggerSessions.valueFor(session);
3189             isSoundTrigger = true;
3190             flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3191             ALOGV("SoundTrigger capture on session %d input %d", session, input);
3192         } else {
3193             halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
3194         }
3195     } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
3196                audio_is_linear_pcm(config.format)) {
3197         flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
3198     }
3199 
3200     if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3201         flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3202     }
3203 
3204     // sampling rate and flags may be updated by getInputProfile
3205     uint32_t profileSamplingRate = (config.sample_rate == 0) ?
3206             SAMPLE_RATE_HZ_DEFAULT : config.sample_rate;
3207     audio_format_t profileFormat = config.format;
3208     audio_channel_mask_t profileChannelMask = config.channel_mask;
3209     audio_input_flags_t profileFlags = flags;
3210     // find a compatible input profile (not necessarily identical in parameters)
3211     sp<IOProfile> profile = getInputProfile(
3212             device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3213     if (profile == nullptr) {
3214         return input;
3215     }
3216 
3217     // Pick input sampling rate if not specified by client
3218     uint32_t samplingRate = config.sample_rate;
3219     if (samplingRate == 0) {
3220         samplingRate = profileSamplingRate;
3221     }
3222 
3223     if (profile->getModuleHandle() == 0) {
3224         ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
3225         return input;
3226     }
3227 
3228     // Reuse an already opened input if:
3229     //  - a client with the same session ID already exists on that input
3230     //  - OR the requested device is a remote submix device with the same adrress
3231     //    as the one connected to that input
3232     for (size_t i = 0; i < mInputs.size(); i++) {
3233         sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3234         if (desc->mProfile != profile) {
3235             continue;
3236         }
3237         RecordClientVector clients = desc->clientsList();
3238         for (const auto &client : clients) {
3239             if (session == client->session()) {
3240                 return desc->mIoHandle;
3241             }
3242         }
3243         if (audio_is_remote_submix_device(device->type())
3244                 && (device->address() != "0")
3245                 && device->equals(desc->getDevice())) {
3246             return desc->mIoHandle;
3247         }
3248     }
3249 
3250     bool isPreemptor = false;
3251     if (!profile->canOpenNewIo()) {
3252         if (com::android::media::audioserver::fix_input_sharing_logic()) {
3253             //  First pick best candidate for preemption (there may not be any):
3254             //  - Preempt and input if:
3255             //     - It has only strictly lower priority use cases than the new client
3256             //     - It has equal priority use cases than the new client, was not
3257             //     opened thanks to preemption, is not routed to the same device than the device to
3258             //     consider or has been active since opened.
3259             //  - Order the preemption candidates by inactive first and priority second
3260             sp<AudioInputDescriptor> closeCandidate;
3261             int leastCloseRank = INT_MAX;
3262             static const int sCloseActive = 0x100;
3263 
3264             for (size_t i = 0; i < mInputs.size(); i++) {
3265                 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3266                 if (desc->mProfile != profile) {
3267                     continue;
3268                 }
3269                 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3270                 if (topPrioClient == nullptr) {
3271                     continue;
3272                 }
3273                 int topPrio = source_priority(topPrioClient->source());
3274                 if (topPrio < source_priority(attributes.source)
3275                       || (topPrio == source_priority(attributes.source)
3276                           && !(desc->isPreemptor() || desc->getDevice() == device))) {
3277                     int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3278                     if (closeRank < leastCloseRank) {
3279                         leastCloseRank = closeRank;
3280                         closeCandidate = desc;
3281                     }
3282                 }
3283             }
3284 
3285             if (closeCandidate != nullptr) {
3286                 closeInput(closeCandidate->mIoHandle);
3287                 // Mark the new input as being issued from a preemption
3288                 // so that is will not be preempted later
3289                 isPreemptor = true;
3290             } else {
3291                 // Then pick the best reusable input (There is always one)
3292                 // The order of preference is:
3293                 // 1) active inputs with same use case as the new client
3294                 // 2) inactive inputs with same use case
3295                 // 3) active inputs with different use cases
3296                 // 4) inactive inputs with different use cases
3297                 sp<AudioInputDescriptor> reuseCandidate;
3298                 int leastReuseRank = INT_MAX;
3299                 static const int sReuseDifferentUseCase = 0x100;
3300 
3301                 for (size_t i = 0; i < mInputs.size(); i++) {
3302                     sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3303                     if (desc->mProfile != profile) {
3304                         continue;
3305                     }
3306                     int reuseRank = sReuseDifferentUseCase;
3307                     for (const auto& client: desc->getClientIterable()) {
3308                         if (client->source() == attributes.source) {
3309                             reuseRank = 0;
3310                             break;
3311                         }
3312                     }
3313                     reuseRank += desc->isActive() ? 0 : 1;
3314                     if (reuseRank < leastReuseRank) {
3315                         leastReuseRank = reuseRank;
3316                         reuseCandidate = desc;
3317                     }
3318                 }
3319                 return reuseCandidate->mIoHandle;
3320             }
3321         } else { // fix_input_sharing_logic()
3322             for (size_t i = 0; i < mInputs.size(); ) {
3323                  sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3324                  if (desc->mProfile != profile) {
3325                      i++;
3326                      continue;
3327                  }
3328                 // if sound trigger, reuse input if used by other sound trigger on same session
3329                 // else
3330                 //    reuse input if active client app is not in IDLE state
3331                 //
3332                 RecordClientVector clients = desc->clientsList();
3333                 bool doClose = false;
3334                 for (const auto& client : clients) {
3335                     if (isSoundTrigger != client->isSoundTrigger()) {
3336                         continue;
3337                     }
3338                     if (client->isSoundTrigger()) {
3339                         if (session == client->session()) {
3340                             return desc->mIoHandle;
3341                         }
3342                         continue;
3343                     }
3344                     if (client->active() && client->appState() != APP_STATE_IDLE) {
3345                         return desc->mIoHandle;
3346                     }
3347                     doClose = true;
3348                 }
3349                 if (doClose) {
3350                     closeInput(desc->mIoHandle);
3351                 } else {
3352                     i++;
3353                 }
3354             }
3355         }
3356     }
3357 
3358     sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3359             profile, mpClientInterface, isPreemptor);
3360 
3361     audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3362     lConfig.sample_rate = profileSamplingRate;
3363     lConfig.channel_mask = profileChannelMask;
3364     lConfig.format = profileFormat;
3365 
3366     status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
3367 
3368     // only accept input with the exact requested set of parameters
3369     if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
3370         (profileSamplingRate != lConfig.sample_rate) ||
3371         !audio_formats_match(profileFormat, lConfig.format) ||
3372         (profileChannelMask != lConfig.channel_mask)) {
3373         ALOGW("getInputForAttr() failed opening input: sampling rate %d"
3374               ", format %#x, channel mask %#x",
3375               profileSamplingRate, profileFormat, profileChannelMask);
3376         if (input != AUDIO_IO_HANDLE_NONE) {
3377             inputDesc->close();
3378         }
3379         return AUDIO_IO_HANDLE_NONE;
3380     }
3381 
3382     inputDesc->mPolicyMix = policyMix;
3383 
3384     addInput(input, inputDesc);
3385     mpClientInterface->onAudioPortListUpdate();
3386 
3387     return input;
3388 }
3389 
startInput(audio_port_handle_t portId)3390 status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
3391 {
3392     ALOGV("%s portId %d", __FUNCTION__, portId);
3393 
3394     sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3395     if (inputDesc == 0) {
3396         ALOGW("%s no input for client %d", __FUNCTION__, portId);
3397         return DEAD_OBJECT;
3398     }
3399     audio_io_handle_t input = inputDesc->mIoHandle;
3400     sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
3401     if (client->active()) {
3402         ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3403         return INVALID_OPERATION;
3404     }
3405 
3406     audio_session_t session = client->session();
3407 
3408     ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
3409 
3410     Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
3411 
3412     status_t status = inputDesc->start();
3413     if (status != NO_ERROR) {
3414         return status;
3415     }
3416 
3417     // increment activity count before calling getNewInputDevice() below as only active sessions
3418     // are considered for device selection
3419     inputDesc->setClientActive(client, true);
3420 
3421     // indicate active capture to sound trigger service if starting capture from a mic on
3422     // primary HW module
3423     sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
3424     if (device != nullptr) {
3425         status = setInputDevice(input, device, true /* force */);
3426     } else {
3427         ALOGW("%s no new input device can be found for descriptor %d",
3428                 __FUNCTION__, inputDesc->getId());
3429         status = BAD_VALUE;
3430     }
3431 
3432     if (status == NO_ERROR && inputDesc->activeCount() == 1) {
3433         sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
3434         // if input maps to a dynamic policy with an activity listener, notify of state change
3435         if ((policyMix != nullptr)
3436                 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3437             mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
3438                     MIX_STATE_MIXING);
3439         }
3440 
3441         DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3442         if (primaryInputDevices.contains(device) &&
3443                 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
3444             mpClientInterface->setSoundTriggerCaptureState(true);
3445         }
3446 
3447         // automatically enable the remote submix output when input is started if not
3448         // used by a policy mix of type MIX_TYPE_RECORDERS
3449         // For remote submix (a virtual device), we open only one input per capture request.
3450         if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
3451             String8 address = String8("");
3452             if (policyMix == nullptr) {
3453                 address = String8("0");
3454             } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3455                 address = policyMix->mDeviceAddress;
3456             }
3457             if (address != "") {
3458                 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3459                         AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3460                         address, "remote-submix", AUDIO_FORMAT_DEFAULT);
3461             }
3462         }
3463     } else if (status != NO_ERROR) {
3464         // Restore client activity state.
3465         inputDesc->setClientActive(client, false);
3466         inputDesc->stop();
3467     }
3468 
3469     ALOGV("%s input %d source = %d status = %d exit",
3470             __FUNCTION__, input, client->source(), status);
3471 
3472     return status;
3473 }
3474 
stopInput(audio_port_handle_t portId)3475 status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
3476 {
3477     ALOGV("%s portId %d", __FUNCTION__, portId);
3478 
3479     sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3480     if (inputDesc == 0) {
3481         ALOGW("%s no input for client %d", __FUNCTION__, portId);
3482         return DEAD_OBJECT;
3483     }
3484     audio_io_handle_t input = inputDesc->mIoHandle;
3485     sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
3486     if (!client->active()) {
3487         ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
3488         return INVALID_OPERATION;
3489     }
3490     auto old_source = inputDesc->source();
3491     inputDesc->setClientActive(client, false);
3492 
3493     inputDesc->stop();
3494     if (inputDesc->isActive()) {
3495         auto current_source = inputDesc->source();
3496         setInputDevice(input, getNewInputDevice(inputDesc),
3497                 old_source != current_source /* force */);
3498     } else {
3499         sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
3500         // if input maps to a dynamic policy with an activity listener, notify of state change
3501         if ((policyMix != nullptr)
3502                 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3503             mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
3504                     MIX_STATE_IDLE);
3505         }
3506 
3507         // automatically disable the remote submix output when input is stopped if not
3508         // used by a policy mix of type MIX_TYPE_RECORDERS
3509         if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
3510             String8 address = String8("");
3511             if (policyMix == nullptr) {
3512                 address = String8("0");
3513             } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3514                 address = policyMix->mDeviceAddress;
3515             }
3516             if (address != "") {
3517                 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3518                                          AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3519                                          address, "remote-submix", AUDIO_FORMAT_DEFAULT);
3520             }
3521         }
3522         resetInputDevice(input);
3523 
3524         // indicate inactive capture to sound trigger service if stopping capture from a mic on
3525         // primary HW module
3526         DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3527         if (primaryInputDevices.contains(inputDesc->getDevice()) &&
3528                 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
3529             mpClientInterface->setSoundTriggerCaptureState(false);
3530         }
3531         inputDesc->clearPreemptedSessions();
3532     }
3533     return NO_ERROR;
3534 }
3535 
releaseInput(audio_port_handle_t portId)3536 void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
3537 {
3538     ALOGV("%s portId %d", __FUNCTION__, portId);
3539 
3540     sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3541     if (inputDesc == 0) {
3542         ALOGW("%s no input for client %d", __FUNCTION__, portId);
3543         return;
3544     }
3545     sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
3546     audio_io_handle_t input = inputDesc->mIoHandle;
3547 
3548     ALOGV("%s %d", __FUNCTION__, input);
3549 
3550     inputDesc->removeClient(portId);
3551 
3552     // If no more clients are present in this session, park effects to an orphan chain
3553     RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3554     if (clientsOnSession.size() == 0) {
3555         mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3556     }
3557     if (inputDesc->getClientCount() > 0) {
3558         ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
3559         return;
3560     }
3561 
3562     closeInput(input);
3563     mpClientInterface->onAudioPortListUpdate();
3564     ALOGV("%s exit", __FUNCTION__);
3565 }
3566 
closeActiveClients(const sp<AudioInputDescriptor> & input)3567 void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
3568 {
3569     RecordClientVector clients = input->clientsList(true);
3570 
3571     for (const auto& client : clients) {
3572         closeClient(client->portId());
3573     }
3574 }
3575 
closeClient(audio_port_handle_t portId)3576 void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3577 {
3578     stopInput(portId);
3579     releaseInput(portId);
3580 }
3581 
checkCloseInput(const sp<AudioInputDescriptor> & input)3582 bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3583     if (input->clientsList().size() == 0
3584             || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3585         return true;
3586     }
3587     for (const auto& client : input->clientsList()) {
3588         sp<DeviceDescriptor> device =
3589             mEngine->getInputDeviceForAttributes(
3590                     client->attributes(), false /*ignorePreferredDevice*/, client->uid(),
3591                     client->session());
3592         if (!input->supportedDevices().contains(device)) {
3593             return true;
3594         }
3595     }
3596     setInputDevice(input->mIoHandle, getNewInputDevice(input));
3597     return false;
3598 }
3599 
checkCloseInputs()3600 void AudioPolicyManager::checkCloseInputs() {
3601     // After connecting or disconnecting an input device, close input if:
3602     // - it has no client (was just opened to check profile)  OR
3603     // - none of its supported devices are connected anymore OR
3604     // - one of its clients cannot be routed to one of its supported
3605     // devices anymore. Otherwise update device selection
3606     std::vector<audio_io_handle_t> inputsToClose;
3607     for (size_t i = 0; i < mInputs.size(); i++) {
3608         if (checkCloseInput(mInputs.valueAt(i))) {
3609             inputsToClose.push_back(mInputs.keyAt(i));
3610         }
3611     }
3612     for (const audio_io_handle_t handle : inputsToClose) {
3613         ALOGV("%s closing input %d", __func__, handle);
3614         closeInput(handle);
3615     }
3616 }
3617 
setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,const char * address __unused,bool enabled,audio_stream_type_t streamToDriveAbs)3618 status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3619                                                             const char *address __unused,
3620                                                             bool enabled,
3621                                                             audio_stream_type_t streamToDriveAbs)
3622 {
3623     ALOGI("%s: deviceType 0x%X, enabled %d, streamToDriveAbs %d", __func__, deviceType, enabled,
3624           streamToDriveAbs);
3625 
3626     bool changed = false;
3627     audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3628     if (enabled) {
3629         if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3630             ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3631                   toString(streamToDriveAbs).c_str());
3632             return BAD_VALUE;
3633         }
3634 
3635         const auto attrIt = mAbsoluteVolumeDrivingStreams.find(deviceType);
3636         if (attrIt == mAbsoluteVolumeDrivingStreams.end() ||
3637             (attrIt->second.usage != attributesToDriveAbs.usage ||
3638              attrIt->second.content_type != attributesToDriveAbs.content_type ||
3639              attrIt->second.flags != attributesToDriveAbs.flags)) {
3640             mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3641             changed = true;
3642         }
3643     } else {
3644         if (mAbsoluteVolumeDrivingStreams.erase(deviceType) != 0) {
3645             changed = true;
3646         }
3647     }
3648 
3649     const DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3650             attributesToDriveAbs, nullptr /* preferredDevice */, true /* fromCache */);
3651     audio_devices_t volumeDevice = Volume::getDeviceForVolume(devices.types());
3652     changed &= (volumeDevice == deviceType);
3653     // if something changed on the output device for the changed attributes, apply the stream
3654     // volumes regarding the new absolute mode to all the outputs without any delay
3655     if (changed) {
3656         for (size_t i = 0; i < mOutputs.size(); i++) {
3657             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3658             DeviceTypeSet curDevices = desc->devices().types();
3659             if (volumeDevice != Volume::getDeviceForVolume(curDevices)) {
3660                 continue;  // skip if not using the target volume device
3661             }
3662 
3663             ALOGI("%s: apply stream volumes for %s(curDevices %s) and device type 0x%X", __func__,
3664                   desc->info().c_str(), dumpDeviceTypes(curDevices).c_str(), deviceType);
3665             applyStreamVolumes(desc, {deviceType});
3666         }
3667     }
3668 
3669     return NO_ERROR;
3670 }
3671 
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)3672 void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
3673 {
3674     ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
3675     if (indexMin < 0 || indexMax < 0) {
3676         ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3677         return;
3678     }
3679     getVolumeCurves(stream).initVolume(indexMin, indexMax);
3680 
3681     // initialize other private stream volumes which follow this one
3682     for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3683         if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
3684             continue;
3685         }
3686         getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
3687     }
3688 }
3689 
setStreamVolumeIndex(audio_stream_type_t stream,int index,bool muted,audio_devices_t device)3690 status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
3691                                                   int index,
3692                                                   bool muted,
3693                                                   audio_devices_t device)
3694 {
3695     auto attributes = mEngine->getAttributesForStreamType(stream);
3696     if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3697         ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3698         return NO_ERROR;
3699     }
3700     ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3701           toString(stream).c_str(), toString(attributes).c_str(), index, device);
3702     return setVolumeIndexForAttributes(attributes, index, muted, device);
3703 }
3704 
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)3705 status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
3706                                                   int *index,
3707                                                   audio_devices_t device)
3708 {
3709     // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3710     // stream by the engine.
3711     DeviceTypeSet deviceTypes = {device};
3712     if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3713         deviceTypes = mEngine->getOutputDevicesForStream(
3714                 stream, true /*fromCache*/).types();
3715     }
3716     return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
3717 }
3718 
setVolumeIndexForAttributes(const audio_attributes_t & attributes,int index,bool muted,audio_devices_t device)3719 status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
3720                                                          int index,
3721                                                          bool muted,
3722                                                          audio_devices_t device)
3723 {
3724     // Get Volume group matching the Audio Attributes
3725     auto group = mEngine->getVolumeGroupForAttributes(attributes);
3726     if (group == VOLUME_GROUP_NONE) {
3727         ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
3728         return BAD_VALUE;
3729     }
3730     ALOGV("%s: group %d matching with %s index %d",
3731             __FUNCTION__, group, toString(attributes).c_str(), index);
3732     if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3733         ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3734                 __FUNCTION__, toString(attributes).c_str());
3735         return NO_ERROR;
3736     }
3737     status_t status = NO_ERROR;
3738     IVolumeCurves &curves = getVolumeCurves(attributes);
3739     VolumeSource vs = toVolumeSource(group);
3740     // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3741     // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3742     VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3743             toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
3744     product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3745 
3746 
3747     status = setVolumeCurveIndex(index, muted, device, curves);
3748     if (status != NO_ERROR) {
3749         ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3750         return status;
3751     }
3752 
3753     DeviceTypeSet curSrcDevices;
3754     auto curCurvAttrs = curves.getAttributes();
3755     if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3756         auto attr = curCurvAttrs.front();
3757         curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
3758     } else if (!curves.getStreamTypes().empty()) {
3759         auto stream = curves.getStreamTypes().front();
3760         curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
3761     } else {
3762         ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3763         return BAD_VALUE;
3764     }
3765     audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3766     resetDeviceTypes(curSrcDevices, curSrcDevice);
3767 
3768     // update volume on all outputs and streams matching the following:
3769     // - The requested stream (or a stream matching for volume control) is active on the output
3770     // - The device (or devices) selected by the engine for this stream includes
3771     // the requested device
3772     // - For non default requested device, currently selected device on the output is either the
3773     // requested device or one of the devices selected by the engine for this stream
3774     // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3775     // no specific device volume value exists for currently selected device.
3776     // - Only apply the volume if the requested device is the desired device for volume control.
3777     for (size_t i = 0; i < mOutputs.size(); i++) {
3778         sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3779         DeviceTypeSet curDevices = desc->devices().types();
3780 
3781         if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3782             curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
3783         }
3784 
3785         if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
3786             continue;
3787         }
3788         if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3789                 curDevices.find(device) == curDevices.end()) {
3790             continue;
3791         }
3792         bool applyVolume = false;
3793         if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3794             curSrcDevices.insert(device);
3795             applyVolume = (curSrcDevices.find(
3796                     Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3797                     && Volume::getDeviceForVolume(curSrcDevices) == device;
3798         } else {
3799             applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3800         }
3801         if (!applyVolume) {
3802             continue; // next output
3803         }
3804         // Inter / intra volume group priority management: Loop on strategies arranged by priority
3805         // If a higher priority strategy is active, and the output is routed to a device with a
3806         // HW Gain management, do not change the volume
3807         if (desc->useHwGain()) {
3808             applyVolume = false;
3809             bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
3810             // If the volume source is active with higher priority source, ensure at least Sw Muted
3811             desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
3812             for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3813                 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3814                                                        false /*preferredDevice*/);
3815                 if (activeClients.empty()) {
3816                     continue;
3817                 }
3818                 bool isPreempted = false;
3819                 bool isHigherPriority = productStrategy < strategy;
3820                 for (const auto &client : activeClients) {
3821                     if (isHigherPriority && (client->volumeSource() != activityVs)) {
3822                         ALOGV("%s: Strategy=%d (\nrequester:\n"
3823                               " group %d, volumeGroup=%d attributes=%s)\n"
3824                               " higher priority source active:\n"
3825                               " volumeGroup=%d attributes=%s) \n"
3826                               " on output %zu, bailing out", __func__, productStrategy,
3827                               group, group, toString(attributes).c_str(),
3828                               client->volumeSource(), toString(client->attributes()).c_str(), i);
3829                         applyVolume = false;
3830                         isPreempted = true;
3831                         break;
3832                     }
3833                     // However, continue for loop to ensure no higher prio clients running on output
3834                     if (client->volumeSource() == activityVs) {
3835                         applyVolume = true;
3836                     }
3837                 }
3838                 if (isPreempted || applyVolume) {
3839                     break;
3840                 }
3841             }
3842             if (!applyVolume) {
3843                 continue; // next output
3844             }
3845         }
3846         //FIXME: workaround for truncated touch sounds
3847         // delayed volume change for system stream to be removed when the problem is
3848         // handled by system UI
3849         status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
3850                     ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
3851                          TOUCH_SOUND_FIXED_DELAY_MS : 0));
3852         if (volStatus != NO_ERROR) {
3853             status = volStatus;
3854         }
3855     }
3856 
3857     // update voice volume if the an active call route exists and target device is same as current
3858     if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()) {
3859         audio_devices_t rxSinkDevice = mCallRxSourceClient->sinkDevice()->type();
3860         audio_devices_t curVoiceDevice = Volume::getDeviceForVolume({rxSinkDevice});
3861         if (curVoiceDevice == device
3862                 && curSrcDevices.find(curVoiceDevice) != curSrcDevices.end()) {
3863             bool isVoiceVolSrc;
3864             bool isBtScoVolSrc;
3865             if (isVolumeConsistentForCalls(vs, {rxSinkDevice},
3866                     isVoiceVolSrc, isBtScoVolSrc, __func__)
3867                     && (isVoiceVolSrc || isBtScoVolSrc)) {
3868                 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
3869                         !audio_is_ble_out_device(rxSinkDevice);
3870                 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
3871             }
3872         }
3873     }
3874 
3875     mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3876     return status;
3877 }
3878 
setVolumeCurveIndex(int index,bool muted,audio_devices_t device,IVolumeCurves & volumeCurves)3879 status_t AudioPolicyManager::setVolumeCurveIndex(int index,
3880                                                  bool muted,
3881                                                  audio_devices_t device,
3882                                                  IVolumeCurves &volumeCurves)
3883 {
3884     // VOICE_CALL stream has minVolumeIndex > 0  but can be muted directly by an
3885     // app that has MODIFY_PHONE_STATE permission.
3886     bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3887     if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
3888             (index > volumeCurves.getVolumeIndexMax())) {
3889         ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3890               volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
3891         return BAD_VALUE;
3892     }
3893     if (!audio_is_output_device(device)) {
3894         return BAD_VALUE;
3895     }
3896 
3897     // Force max volume if stream cannot be muted
3898     if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3899 
3900     ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
3901     volumeCurves.addCurrentVolumeIndex(device, index);
3902     volumeCurves.setIsMuted(muted);
3903     return NO_ERROR;
3904 }
3905 
getVolumeIndexForAttributes(const audio_attributes_t & attr,int & index,audio_devices_t device)3906 status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3907                                                          int &index,
3908                                                          audio_devices_t device)
3909 {
3910     // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3911     // stream by the engine.
3912     DeviceTypeSet deviceTypes = {device};
3913     if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3914         deviceTypes = mEngine->getOutputDevicesForAttributes(
3915                 attr, nullptr, true /*fromCache*/).types();
3916     }
3917     return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
3918 }
3919 
getVolumeIndex(const IVolumeCurves & curves,int & index,const DeviceTypeSet & deviceTypes) const3920 status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3921                                             int &index,
3922                                             const DeviceTypeSet& deviceTypes) const
3923 {
3924     if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
3925         return BAD_VALUE;
3926     }
3927     index = curves.getVolumeIndex(deviceTypes);
3928     ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
3929     return NO_ERROR;
3930 }
3931 
getMinVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)3932 status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3933                                                             int &index)
3934 {
3935     index = getVolumeCurves(attr).getVolumeIndexMin();
3936     return NO_ERROR;
3937 }
3938 
getMaxVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)3939 status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3940                                                             int &index)
3941 {
3942     index = getVolumeCurves(attr).getVolumeIndexMax();
3943     return NO_ERROR;
3944 }
3945 
selectOutputForMusicEffects()3946 audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
3947 {
3948     // select one output among several suitable for global effects.
3949     // The priority is as follows:
3950     // 1: An offloaded output. If the effect ends up not being offloadable,
3951     //    AudioFlinger will invalidate the track and the offloaded output
3952     //    will be closed causing the effect to be moved to a PCM output.
3953     // 2: Spatializer output if the stereo spatializer feature enabled
3954     // 3: A deep buffer output
3955     // 4: The primary output
3956     // 5: the first output in the list
3957 
3958     DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3959                 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
3960     SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
3961 
3962     if (outputs.size() == 0) {
3963         return AUDIO_IO_HANDLE_NONE;
3964     }
3965 
3966     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3967     bool activeOnly = true;
3968 
3969     while (output == AUDIO_IO_HANDLE_NONE) {
3970         audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3971         audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
3972         audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3973         audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3974 
3975         for (audio_io_handle_t outputLoop : outputs) {
3976             sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
3977             if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
3978                 continue;
3979             }
3980             ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3981                   activeOnly, outputLoop, desc->mFlags);
3982             if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3983                 outputOffloaded = outputLoop;
3984             }
3985             if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3986                 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3987                     outputSpatializer = outputLoop;
3988                 }
3989             }
3990             if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
3991                 outputDeepBuffer = outputLoop;
3992             }
3993             if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
3994                 outputPrimary = outputLoop;
3995             }
3996         }
3997         if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3998             output = outputOffloaded;
3999         } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
4000             output = outputSpatializer;
4001         } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
4002             output = outputDeepBuffer;
4003         } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
4004             output = outputPrimary;
4005         } else {
4006             output = outputs[0];
4007         }
4008         activeOnly = false;
4009     }
4010 
4011     if (output != mMusicEffectOutput) {
4012         mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
4013                 mpClientInterface);
4014         mMusicEffectOutput = output;
4015     }
4016 
4017     ALOGV("selectOutputForMusicEffects selected output %d", output);
4018     return output;
4019 }
4020 
getOutputForEffect(const effect_descriptor_t * desc __unused)4021 audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
4022 {
4023     return selectOutputForMusicEffects();
4024 }
4025 
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,product_strategy_t strategy,int session,int id)4026 status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
4027                                 audio_io_handle_t io,
4028                                 product_strategy_t strategy,
4029                                 int session,
4030                                 int id)
4031 {
4032     if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
4033         ssize_t index = mOutputs.indexOfKey(io);
4034         if (index < 0) {
4035             index = mInputs.indexOfKey(io);
4036             if (index < 0) {
4037                 ALOGW("registerEffect() unknown io %d", io);
4038                 return INVALID_OPERATION;
4039             }
4040         }
4041     }
4042     bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
4043                             && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
4044                                     || strategy == PRODUCT_STRATEGY_NONE));
4045     return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
4046 }
4047 
unregisterEffect(int id)4048 status_t AudioPolicyManager::unregisterEffect(int id)
4049 {
4050     if (mEffects.getEffect(id) == nullptr) {
4051         return INVALID_OPERATION;
4052     }
4053     if (mEffects.isEffectEnabled(id)) {
4054         ALOGW("%s effect %d enabled", __FUNCTION__, id);
4055         setEffectEnabled(id, false);
4056     }
4057     return mEffects.unregisterEffect(id);
4058 }
4059 
setEffectEnabled(int id,bool enabled)4060 status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
4061 {
4062     sp<EffectDescriptor> effect = mEffects.getEffect(id);
4063     if (effect == nullptr) {
4064         return INVALID_OPERATION;
4065     }
4066 
4067     status_t status = mEffects.setEffectEnabled(id, enabled);
4068     if (status == NO_ERROR) {
4069         mInputs.trackEffectEnabled(effect, enabled);
4070     }
4071     return status;
4072 }
4073 
4074 
moveEffectsToIo(const std::vector<int> & ids,audio_io_handle_t io)4075 status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
4076 {
4077    mEffects.moveEffects(ids, io);
4078    return NO_ERROR;
4079 }
4080 
isStreamActive(audio_stream_type_t stream,uint32_t inPastMs) const4081 bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
4082 {
4083     auto vs = toVolumeSource(stream, false);
4084     return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
4085 }
4086 
isStreamActiveRemotely(audio_stream_type_t stream,uint32_t inPastMs) const4087 bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
4088 {
4089     auto vs = toVolumeSource(stream, false);
4090     return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
4091 }
4092 
isSourceActive(audio_source_t source) const4093 bool AudioPolicyManager::isSourceActive(audio_source_t source) const
4094 {
4095     for (size_t i = 0; i < mInputs.size(); i++) {
4096         const sp<AudioInputDescriptor>  inputDescriptor = mInputs.valueAt(i);
4097         if (inputDescriptor->isSourceActive(source)) {
4098             return true;
4099         }
4100     }
4101     return false;
4102 }
4103 
4104 // Register a list of custom mixes with their attributes and format.
4105 // When a mix is registered, corresponding input and output profiles are
4106 // added to the remote submix hw module. The profile contains only the
4107 // parameters (sampling rate, format...) specified by the mix.
4108 // The corresponding input remote submix device is also connected.
4109 //
4110 // When a remote submix device is connected, the address is checked to select the
4111 // appropriate profile and the corresponding input or output stream is opened.
4112 //
4113 // When capture starts, getInputForAttr() will:
4114 //  - 1 look for a mix matching the address passed in attribtutes tags if any
4115 //  - 2 if none found, getDeviceForInputSource() will:
4116 //     - 2.1 look for a mix matching the attributes source
4117 //     - 2.2 if none found, default to device selection by policy rules
4118 // At this time, the corresponding output remote submix device is also connected
4119 // and active playback use cases can be transferred to this mix if needed when reconnecting
4120 // after AudioTracks are invalidated
4121 //
4122 // When playback starts, getOutputForAttr() will:
4123 //  - 1 look for a mix matching the address passed in attribtutes tags if any
4124 //  - 2 if none found, look for a mix matching the attributes usage
4125 //  - 3 if none found, default to device and output selection by policy rules.
4126 
registerPolicyMixes(const Vector<AudioMix> & mixes)4127 status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
4128 {
4129     ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4130     status_t res = NO_ERROR;
4131     bool checkOutputs = false;
4132     sp<HwModule> rSubmixModule;
4133     Vector<AudioMix> registeredMixes;
4134     AudioDeviceTypeAddrVector devices;
4135     // examine each mix's route type
4136     for (size_t i = 0; i < mixes.size(); i++) {
4137         AudioMix mix = mixes[i];
4138         // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4139         if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4140             ALOGE("Unsupported Policy Mix %zu of %zu: "
4141                   "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4142                    i, mixes.size());
4143             res = INVALID_OPERATION;
4144             break;
4145         }
4146         // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4147         // in the same way.
4148         if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
4149             ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4150                   mix.mRouteFlags);
4151             if (rSubmixModule == 0) {
4152                 rSubmixModule = mHwModules.getModuleFromName(
4153                         AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4154                 if (rSubmixModule == 0) {
4155                     ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
4156                             i);
4157                     res = INVALID_OPERATION;
4158                     break;
4159                 }
4160             }
4161 
4162             String8 address = mix.mDeviceAddress;
4163             audio_devices_t deviceTypeToMakeAvailable;
4164             if (mix.mMixType == MIX_TYPE_PLAYERS) {
4165                 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4166                 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4167             } else {
4168                 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4169                 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4170             }
4171 
4172             if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
4173                 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
4174                 res = INVALID_OPERATION;
4175                 break;
4176             }
4177             audio_config_t outputConfig = mix.mFormat;
4178             audio_config_t inputConfig = mix.mFormat;
4179             // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4180             // in stereo and let audio flinger do the channel conversion if needed.
4181             outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4182             inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
4183             rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
4184                     AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4185                     audio_is_linear_pcm(outputConfig.format)
4186                         ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
4187             rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
4188                     AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4189                     audio_is_linear_pcm(inputConfig.format)
4190                         ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
4191 
4192             if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
4193                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4194                     address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
4195                 ALOGE("Failed to set remote submix device available, type %u, address %s",
4196                         mix.mDeviceType, address.c_str());
4197                 break;
4198             }
4199         } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4200             String8 address = mix.mDeviceAddress;
4201             audio_devices_t type = mix.mDeviceType;
4202             ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
4203                     i, mixes.size(), type, address.c_str());
4204 
4205             sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4206                     mix.mDeviceType, mix.mDeviceAddress,
4207                     String8(), AUDIO_FORMAT_DEFAULT);
4208             if (device == nullptr) {
4209                 res = INVALID_OPERATION;
4210                 break;
4211             }
4212 
4213             bool foundOutput = false;
4214             // First try to find an already opened output supporting the device
4215             for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
4216                 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
4217 
4218                 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
4219                     if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
4220                         ALOGE("Could not register mix RENDER,  dev=0x%X addr=%s", type,
4221                               address.c_str());
4222                         res = INVALID_OPERATION;
4223                     } else {
4224                         foundOutput = true;
4225                     }
4226                 }
4227             }
4228             // If no output found, try to find a direct output profile supporting the device
4229             for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4230                 sp<HwModule> module = mHwModules[i];
4231                 for (size_t j = 0;
4232                         j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4233                         j++) {
4234                     sp<IOProfile> profile = module->getOutputProfiles()[j];
4235                     if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4236                         if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4237                             ALOGE("Could not register mix RENDER,  dev=0x%X addr=%s", type,
4238                                   address.c_str());
4239                             res = INVALID_OPERATION;
4240                         } else {
4241                             foundOutput = true;
4242                         }
4243                     }
4244                 }
4245             }
4246             if (res != NO_ERROR) {
4247                 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
4248                         i, type, address.c_str());
4249                 res = INVALID_OPERATION;
4250                 break;
4251             } else if (!foundOutput) {
4252                 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
4253                         i, type, address.c_str());
4254                 res = INVALID_OPERATION;
4255                 break;
4256             } else {
4257                 checkOutputs = true;
4258                 devices.push_back(AudioDeviceTypeAddr(mix.mDeviceType, mix.mDeviceAddress.c_str()));
4259                 registeredMixes.add(mix);
4260             }
4261         }
4262     }
4263     if (res != NO_ERROR) {
4264         if (audio_flags::audio_mix_ownership()) {
4265             // Only unregister mixes that were actually registered to not accidentally unregister
4266             // mixes that already existed previously.
4267             unregisterPolicyMixes(registeredMixes);
4268             registeredMixes.clear();
4269         } else {
4270             unregisterPolicyMixes(mixes);
4271         }
4272     } else if (checkOutputs) {
4273         checkForDeviceAndOutputChanges();
4274         changeOutputDevicesMuteState(devices);
4275         updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4276             true /* skipDelays */);
4277         changeOutputDevicesMuteState(devices);
4278     }
4279     return res;
4280 }
4281 
unregisterPolicyMixes(Vector<AudioMix> mixes)4282 status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4283 {
4284     ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
4285     status_t res = NO_ERROR;
4286     bool checkOutputs = false;
4287     sp<HwModule> rSubmixModule;
4288     AudioDeviceTypeAddrVector devices;
4289     // examine each mix's route type
4290     for (const auto& mix : mixes) {
4291         if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
4292 
4293             if (rSubmixModule == 0) {
4294                 rSubmixModule = mHwModules.getModuleFromName(
4295                         AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4296                 if (rSubmixModule == 0) {
4297                     res = INVALID_OPERATION;
4298                     continue;
4299                 }
4300             }
4301 
4302             String8 address = mix.mDeviceAddress;
4303 
4304             if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
4305                 res = INVALID_OPERATION;
4306                 continue;
4307             }
4308 
4309             for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
4310                 if (getDeviceConnectionState(device, address.c_str()) ==
4311                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4312                     status_t currentRes =
4313                             setDeviceConnectionStateInt(device,
4314                                                         AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4315                                                         address.c_str(),
4316                                                         "remote-submix",
4317                                                         AUDIO_FORMAT_DEFAULT);
4318                     if (!audio_flags::audio_mix_ownership()) {
4319                         res = currentRes;
4320                     }
4321                     if (currentRes != OK) {
4322                         ALOGE("Error making RemoteSubmix device unavailable for mix "
4323                               "with type %d, address %s", device, address.c_str());
4324                         res = INVALID_OPERATION;
4325                     }
4326                 }
4327             }
4328             rSubmixModule->removeOutputProfile(address.c_str());
4329             rSubmixModule->removeInputProfile(address.c_str());
4330 
4331         } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4332             if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
4333                 res = INVALID_OPERATION;
4334                 continue;
4335             } else {
4336                 devices.push_back(AudioDeviceTypeAddr(mix.mDeviceType, mix.mDeviceAddress.c_str()));
4337                 checkOutputs = true;
4338             }
4339         }
4340     }
4341 
4342     if (res == NO_ERROR && checkOutputs) {
4343         checkForDeviceAndOutputChanges();
4344         changeOutputDevicesMuteState(devices);
4345         updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4346             true /* skipDelays */);
4347         changeOutputDevicesMuteState(devices);
4348     }
4349     return res;
4350 }
4351 
getRegisteredPolicyMixes(std::vector<AudioMix> & _aidl_return)4352 status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4353     if (!audio_flags::audio_mix_test_api()) {
4354         return INVALID_OPERATION;
4355     }
4356 
4357     _aidl_return.clear();
4358     _aidl_return.reserve(mPolicyMixes.size());
4359     for (const auto &policyMix: mPolicyMixes) {
4360         _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4361                              policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4362                              policyMix->mCbFlags);
4363         _aidl_return.back().mDeviceType = policyMix->mDeviceType;
4364         _aidl_return.back().mToken = policyMix->mToken;
4365         _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
4366     }
4367 
4368     ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
4369     return OK;
4370 }
4371 
updatePolicyMix(const AudioMix & mix,const std::vector<AudioMixMatchCriterion> & updatedCriteria)4372 status_t AudioPolicyManager::updatePolicyMix(
4373             const AudioMix& mix,
4374             const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4375     status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4376     if (res == NO_ERROR) {
4377         checkForDeviceAndOutputChanges();
4378         updateCallAndOutputRouting();
4379     }
4380     return res;
4381 }
4382 
dumpManualSurroundFormats(String8 * dst) const4383 void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4384 {
4385     size_t i = 0;
4386     constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4387     for (const auto& fmt : mManualSurroundFormats) {
4388         if (i++ != 0) dst->append(", ");
4389         std::string sfmt;
4390         FormatConverter::toString(fmt, sfmt);
4391         dst->append(sfmt.size() >= audioFormatPrefixLen ?
4392                 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4393     }
4394 }
4395 
4396 // 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,bool matchAddress)4397 bool  AudioPolicyManager::areAllDevicesSupported(
4398         const AudioDeviceTypeAddrVector& devices,
4399         std::function<bool(audio_devices_t)> predicate,
4400         const char *context,
4401         bool matchAddress) {
4402     for (size_t i = 0; i < devices.size(); i++) {
4403         sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
4404                 devices[i].mType, devices[i].getAddress(), String8(),
4405                 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
4406         if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
4407             ALOGE("%s: device type %#x address %s not supported or not match predicate",
4408                     context, devices[i].mType, devices[i].getAddress());
4409             return false;
4410         }
4411     }
4412     return true;
4413 }
4414 
changeOutputDevicesMuteState(const AudioDeviceTypeAddrVector & devices)4415 void AudioPolicyManager::changeOutputDevicesMuteState(
4416         const AudioDeviceTypeAddrVector& devices) {
4417     ALOGVV("%s() num devices %zu", __func__, devices.size());
4418 
4419     std::vector<sp<SwAudioOutputDescriptor>> outputs =
4420             getSoftwareOutputsForDevices(devices);
4421 
4422     for (size_t i = 0; i < outputs.size(); i++) {
4423         sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4424         DeviceVector prevDevices = outputDesc->devices();
4425         checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4426     }
4427 }
4428 
getSoftwareOutputsForDevices(const AudioDeviceTypeAddrVector & devices) const4429 std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4430         const AudioDeviceTypeAddrVector& devices) const
4431 {
4432     std::vector<sp<SwAudioOutputDescriptor>> outputs;
4433     DeviceVector deviceDescriptors;
4434     for (size_t j = 0; j < devices.size(); j++) {
4435         sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4436                 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4437         if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4438             ALOGE("%s: device type %#x address %s not supported or not an output device",
4439                 __func__, devices[j].mType, devices[j].getAddress());
4440                     continue;
4441         }
4442         deviceDescriptors.add(desc);
4443     }
4444     for (size_t i = 0; i < mOutputs.size(); i++) {
4445         if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4446             continue;
4447         }
4448         outputs.push_back(mOutputs.valueAt(i));
4449     }
4450     return outputs;
4451 }
4452 
setUidDeviceAffinities(uid_t uid,const AudioDeviceTypeAddrVector & devices)4453 status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
4454         const AudioDeviceTypeAddrVector& devices) {
4455     ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
4456     if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4457         return BAD_VALUE;
4458     }
4459     status_t res =  mPolicyMixes.setUidDeviceAffinities(uid, devices);
4460     if (res != NO_ERROR) {
4461         ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4462         return res;
4463     }
4464 
4465     checkForDeviceAndOutputChanges();
4466     updateCallAndOutputRouting();
4467 
4468     return NO_ERROR;
4469 }
4470 
removeUidDeviceAffinities(uid_t uid)4471 status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4472     ALOGV("%s() uid=%d", __FUNCTION__, uid);
4473     status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4474     if (res != NO_ERROR) {
4475         ALOGE("%s() Could not remove all device affinities for uid = %d",
4476             __FUNCTION__, uid);
4477         return INVALID_OPERATION;
4478     }
4479 
4480     checkForDeviceAndOutputChanges();
4481     updateCallAndOutputRouting();
4482 
4483     return res;
4484 }
4485 
4486 
setDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role,const AudioDeviceTypeAddrVector & devices)4487 status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4488                                                        device_role_t role,
4489                                                        const AudioDeviceTypeAddrVector &devices) {
4490     ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4491             dumpAudioDeviceTypeAddrVector(devices).c_str());
4492 
4493     if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4494         return BAD_VALUE;
4495     }
4496     status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
4497     if (status != NO_ERROR) {
4498         ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4499                 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4500         return status;
4501     }
4502 
4503     checkForDeviceAndOutputChanges();
4504 
4505     bool forceVolumeReeval = false;
4506     // FIXME: workaround for truncated touch sounds
4507     // to be removed when the problem is handled by system UI
4508     uint32_t delayMs = 0;
4509     if (strategy == mCommunnicationStrategy) {
4510         forceVolumeReeval = true;
4511         delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4512         updateInputRouting();
4513     }
4514     updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4515 
4516     return NO_ERROR;
4517 }
4518 
updateCallAndOutputRouting(bool forceVolumeReeval,uint32_t delayMs,bool skipDelays)4519 void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4520     bool skipDelays)
4521 {
4522     uint32_t waitMs = 0;
4523     bool wasLeUnicastActive = isLeUnicastActive();
4524     if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
4525         // Only apply special touch sound delay once
4526         delayMs = 0;
4527     }
4528     std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
4529     for (size_t i = 0; i < mOutputs.size(); i++) {
4530         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4531         DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
4532         if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4533                 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
4534             // As done in setDeviceConnectionState, we could also fix default device issue by
4535             // preventing the force re-routing in case of default dev that distinguishes on address.
4536             // Let's give back to engine full device choice decision however.
4537             bool newDevicesNotEmpty = !newDevices.isEmpty();
4538             if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4539                 && newDevicesNotEmpty) {
4540                 // If the device is using preferred mixer attributes, the output need to reopen
4541                 // with default configuration when the new selected devices are different from
4542                 // current routing devices.
4543                 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4544                 continue;
4545             }
4546 
4547             waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4548                                       newDevicesNotEmpty /*force*/, delayMs,
4549                                       nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4550                                       !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
4551             // Only apply special touch sound delay once
4552             delayMs = 0;
4553         }
4554         if (forceVolumeReeval && !newDevices.isEmpty()) {
4555             applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4556         }
4557     }
4558     reopenOutputsWithDevices(outputsToReopen);
4559     checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
4560 }
4561 
updateInputRouting()4562 void AudioPolicyManager::updateInputRouting() {
4563     for (const auto& activeDesc : mInputs.getActiveInputs()) {
4564         // Skip for hotword recording as the input device switch
4565         // is handled within sound trigger HAL
4566         if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4567             continue;
4568         }
4569         auto newDevice = getNewInputDevice(activeDesc);
4570         // Force new input selection if the new device can not be reached via current input
4571         if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4572             setInputDevice(activeDesc->mIoHandle, newDevice);
4573         } else {
4574             closeInput(activeDesc->mIoHandle);
4575         }
4576     }
4577 }
4578 
4579 status_t
removeDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role,const AudioDeviceTypeAddrVector & devices)4580 AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4581                                                  device_role_t role,
4582                                                  const AudioDeviceTypeAddrVector &devices) {
4583     ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4584             dumpAudioDeviceTypeAddrVector(devices).c_str());
4585 
4586     if (!areAllDevicesSupported(
4587             devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
4588         return BAD_VALUE;
4589     }
4590     status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4591     if (status != NO_ERROR) {
4592         ALOGW("Engine could not remove devices %s for strategy %d role %d",
4593                 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4594         return status;
4595     }
4596 
4597     checkForDeviceAndOutputChanges();
4598 
4599     bool forceVolumeReeval = false;
4600     // TODO(b/263479999): workaround for truncated touch sounds
4601     // to be removed when the problem is handled by system UI
4602     uint32_t delayMs = 0;
4603     if (strategy == mCommunnicationStrategy) {
4604         forceVolumeReeval = true;
4605         delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4606         updateInputRouting();
4607     }
4608     updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4609 
4610     return NO_ERROR;
4611 }
4612 
clearDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role)4613 status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4614                                                          device_role_t role)
4615 {
4616     ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
4617 
4618     status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
4619     if (status != NO_ERROR) {
4620         ALOGW_IF(status != NAME_NOT_FOUND,
4621                 "Engine could not remove device role for strategy %d status %d",
4622                 strategy, status);
4623         return status;
4624     }
4625 
4626     checkForDeviceAndOutputChanges();
4627 
4628     bool forceVolumeReeval = false;
4629     // FIXME: workaround for truncated touch sounds
4630     // to be removed when the problem is handled by system UI
4631     uint32_t delayMs = 0;
4632     if (strategy == mCommunnicationStrategy) {
4633         forceVolumeReeval = true;
4634         delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4635         updateInputRouting();
4636     }
4637     updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4638 
4639     return NO_ERROR;
4640 }
4641 
getDevicesForRoleAndStrategy(product_strategy_t strategy,device_role_t role,AudioDeviceTypeAddrVector & devices)4642 status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4643                                                           device_role_t role,
4644                                                           AudioDeviceTypeAddrVector &devices) {
4645     return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
4646 }
4647 
setDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)4648 status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4649         audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4650     ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4651             dumpAudioDeviceTypeAddrVector(devices).c_str());
4652 
4653     if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
4654         return BAD_VALUE;
4655     }
4656     status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4657     ALOGW_IF(status != NO_ERROR,
4658             "Engine could not set preferred devices %s for audio source %d role %d",
4659             dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4660 
4661     if (status == NO_ERROR) {
4662         updateInputRouting();
4663         updateCallRouting(false /*fromCache*/);
4664     }
4665     return status;
4666 }
4667 
addDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)4668 status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4669         audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4670     ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4671             dumpAudioDeviceTypeAddrVector(devices).c_str());
4672 
4673     if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
4674         return BAD_VALUE;
4675     }
4676     status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4677     ALOGW_IF(status != NO_ERROR,
4678             "Engine could not add preferred devices %s for audio source %d role %d",
4679             dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4680 
4681     if (status == NO_ERROR) {
4682         updateInputRouting();
4683         updateCallRouting(false /*fromCache*/);
4684     }
4685     return status;
4686 }
4687 
removeDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)4688 status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4689         audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4690 {
4691     ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4692             dumpAudioDeviceTypeAddrVector(devices).c_str());
4693 
4694     if (!areAllDevicesSupported(
4695             devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
4696         return BAD_VALUE;
4697     }
4698 
4699     status_t status = mEngine->removeDevicesRoleForCapturePreset(
4700             audioSource, role, devices);
4701     ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
4702             "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
4703     if (status == NO_ERROR) {
4704         updateInputRouting();
4705         updateCallRouting(false /*fromCache*/);
4706     }
4707     return status;
4708 }
4709 
clearDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role)4710 status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4711                                                               device_role_t role) {
4712     ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4713 
4714     status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
4715     ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
4716             "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
4717     if (status == NO_ERROR) {
4718         updateInputRouting();
4719         updateCallRouting(false /*fromCache*/);
4720     }
4721     return status;
4722 }
4723 
getDevicesForRoleAndCapturePreset(audio_source_t audioSource,device_role_t role,AudioDeviceTypeAddrVector & devices)4724 status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4725         audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4726     return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4727 }
4728 
setUserIdDeviceAffinities(int userId,const AudioDeviceTypeAddrVector & devices)4729 status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
4730         const AudioDeviceTypeAddrVector& devices) {
4731     ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
4732     if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4733         return BAD_VALUE;
4734     }
4735     status_t status =  mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4736     if (status != NO_ERROR) {
4737         ALOGE("%s() could not set device affinity for userId %d",
4738             __FUNCTION__, userId);
4739         return status;
4740     }
4741 
4742     // reevaluate outputs for all devices
4743     checkForDeviceAndOutputChanges();
4744     changeOutputDevicesMuteState(devices);
4745     updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4746         true /* skipDelays */);
4747     changeOutputDevicesMuteState(devices);
4748 
4749     return NO_ERROR;
4750 }
4751 
removeUserIdDeviceAffinities(int userId)4752 status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
4753     ALOGV("%s() userId=%d", __FUNCTION__, userId);
4754     AudioDeviceTypeAddrVector devices;
4755     mPolicyMixes.getDevicesForUserId(userId, devices);
4756     status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4757     if (status != NO_ERROR) {
4758         ALOGE("%s() Could not remove all device affinities fo userId = %d",
4759             __FUNCTION__, userId);
4760         return status;
4761     }
4762 
4763     // reevaluate outputs for all devices
4764     checkForDeviceAndOutputChanges();
4765     changeOutputDevicesMuteState(devices);
4766     updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4767         true /* skipDelays */);
4768     changeOutputDevicesMuteState(devices);
4769 
4770     return NO_ERROR;
4771 }
4772 
dump(String8 * dst) const4773 void AudioPolicyManager::dump(String8 *dst) const
4774 {
4775     dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
4776     dst->appendFormat(" Primary Output I/O handle: %d\n",
4777              hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
4778     std::string stateLiteral;
4779     AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
4780     dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
4781     const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4782         "communications", "media", "record", "dock", "system",
4783         "HDMI system audio", "encoded surround output", "vibrate ringing" };
4784     for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4785          i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
4786         audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4787         dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4788         if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4789                 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4790             dst->append(" (MANUAL: ");
4791             dumpManualSurroundFormats(dst);
4792             dst->append(")");
4793         }
4794         dst->append("\n");
4795     }
4796     dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4797     dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
4798     dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
4799     dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
4800 
4801     dst->append("\n");
4802     mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4803     dst->append("\n");
4804     mAvailableInputDevices.dump(dst, String8("Available input"), 1);
4805     mHwModules.dump(dst);
4806     mOutputs.dump(dst);
4807     mInputs.dump(dst);
4808     mEffects.dump(dst, 1);
4809     mAudioPatches.dump(dst);
4810     mPolicyMixes.dump(dst);
4811     mAudioSources.dump(dst);
4812 
4813     dst->appendFormat(" AllowedCapturePolicies:\n");
4814     for (auto& policy : mAllowedCapturePolicies) {
4815         dst->appendFormat("   - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4816     }
4817 
4818     dst->appendFormat(" Preferred mixer audio configuration:\n");
4819     for (const auto it : mPreferredMixerAttrInfos) {
4820         dst->appendFormat("   - device port id: %d\n", it.first);
4821         for (const auto preferredMixerInfoIt : it.second) {
4822             dst->appendFormat("     - strategy: %d; ", preferredMixerInfoIt.first);
4823             preferredMixerInfoIt.second->dump(dst);
4824         }
4825     }
4826 
4827     dst->appendFormat("\nPolicy Engine dump:\n");
4828     mEngine->dump(dst);
4829 
4830     dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4831     for (const auto it : mAbsoluteVolumeDrivingStreams) {
4832         dst->appendFormat("   - device type: %s, driving stream %d\n",
4833                           dumpDeviceTypes({it.first}).c_str(),
4834                           mEngine->getVolumeGroupForAttributes(it.second));
4835     }
4836 
4837     // dump mmap policy by device
4838     dst->appendFormat("\nMmap policy:\n");
4839     for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4840         std::stringstream ss;
4841         ss << '{';
4842         for (const auto& [deviceType, policy] : policyByDevice) {
4843             ss << deviceType.toString() << ":" << toString(policy) << " ";
4844         }
4845         ss << '}';
4846         dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4847     }
4848 }
4849 
dump(int fd)4850 status_t AudioPolicyManager::dump(int fd)
4851 {
4852     String8 result;
4853     dump(&result);
4854     write(fd, result.c_str(), result.size());
4855     return NO_ERROR;
4856 }
4857 
setAllowedCapturePolicy(uid_t uid,audio_flags_mask_t capturePolicy)4858 status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4859 {
4860     mAllowedCapturePolicies[uid] = capturePolicy;
4861     return NO_ERROR;
4862 }
4863 
4864 // This function checks for the parameters which can be offloaded.
4865 // This can be enhanced depending on the capability of the DSP and policy
4866 // of the system.
getOffloadSupport(const audio_offload_info_t & offloadInfo)4867 audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
4868 {
4869     ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
4870      " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
4871      __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
4872      offloadInfo.format,
4873      offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4874      offloadInfo.has_video);
4875 
4876     if (!isOffloadPossible(offloadInfo)) {
4877         return AUDIO_OFFLOAD_NOT_SUPPORTED;
4878     }
4879 
4880     // See if there is a profile to support this.
4881     // AUDIO_DEVICE_NONE
4882     sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
4883                                             offloadInfo.sample_rate,
4884                                             offloadInfo.format,
4885                                             offloadInfo.channel_mask,
4886                                             AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4887                                             true /* directOnly */);
4888     ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4889             (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4890             ? ", supports gapless" : "");
4891     if (profile == nullptr) {
4892         return AUDIO_OFFLOAD_NOT_SUPPORTED;
4893     }
4894     if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4895         return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4896     }
4897     return AUDIO_OFFLOAD_SUPPORTED;
4898 }
4899 
isDirectOutputSupported(const audio_config_base_t & config,const audio_attributes_t & attributes)4900 bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4901                                                  const audio_attributes_t& attributes) {
4902     audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
4903     audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
4904     DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4905     sp<IOProfile> profile = getProfileForOutput(outputDevices,
4906                                             config.sample_rate,
4907                                             config.format,
4908                                             config.channel_mask,
4909                                             output_flags,
4910                                             true /* directOnly */);
4911     ALOGV("%s() profile %sfound with name: %s, "
4912         "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4913         __FUNCTION__, profile != 0 ? "" : "NOT ",
4914         (profile != 0 ? profile->getTagName().c_str() : "null"),
4915         config.sample_rate, config.format, config.channel_mask, output_flags);
4916 
4917     // also try the MSD module if compatible profile not found
4918     if (profile == nullptr) {
4919         profile = getMsdProfileForOutput(outputDevices,
4920                                               config.sample_rate,
4921                                               config.format,
4922                                               config.channel_mask,
4923                                               output_flags,
4924                                               true /* directOnly */);
4925         ALOGV("%s() MSD profile %sfound with name: %s, "
4926             "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4927             __FUNCTION__, profile != 0 ? "" : "NOT ",
4928             (profile != 0 ? profile->getTagName().c_str() : "null"),
4929             config.sample_rate, config.format, config.channel_mask, output_flags);
4930     }
4931     return (profile != nullptr);
4932 }
4933 
isOffloadPossible(const audio_offload_info_t & offloadInfo,bool durationIgnored)4934 bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4935                                            bool durationIgnored) {
4936     if (mMasterMono) {
4937         return false; // no offloading if mono is set.
4938     }
4939 
4940     // Check if offload has been disabled
4941     if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4942         ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4943         return false;
4944     }
4945 
4946     // Check if stream type is music, then only allow offload as of now.
4947     if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4948     {
4949         ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4950         return false;
4951     }
4952 
4953     //TODO: enable audio offloading with video when ready
4954     const bool allowOffloadWithVideo =
4955             property_get_bool("audio.offload.video", false /* default_value */);
4956     if (offloadInfo.has_video && !allowOffloadWithVideo) {
4957         ALOGV("%s: has_video == true, returning false", __func__);
4958         return false;
4959     }
4960 
4961     //If duration is less than minimum value defined in property, return false
4962     const int min_duration_secs = property_get_int32(
4963             "audio.offload.min.duration.secs", -1 /* default_value */);
4964     if (!durationIgnored) {
4965         if (min_duration_secs >= 0) {
4966             if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4967                 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4968                       __func__, min_duration_secs);
4969                 return false;
4970             }
4971         } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4972             ALOGV("%s: Offload denied by duration < default min(=%u)",
4973                   __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4974             return false;
4975         }
4976     }
4977 
4978     // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4979     // creating an offloaded track and tearing it down immediately after start when audioflinger
4980     // detects there is an active non offloadable effect.
4981     // FIXME: We should check the audio session here but we do not have it in this context.
4982     // This may prevent offloading in rare situations where effects are left active by apps
4983     // in the background.
4984     if (mEffects.isNonOffloadableEffectEnabled()) {
4985         return false;
4986     }
4987 
4988     return true;
4989 }
4990 
getDirectPlaybackSupport(const audio_attributes_t * attr,const audio_config_t * config)4991 audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4992                                                                  const audio_config_t *config) {
4993     audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4994     offloadInfo.format = config->format;
4995     offloadInfo.sample_rate = config->sample_rate;
4996     offloadInfo.channel_mask = config->channel_mask;
4997     offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4998     offloadInfo.has_video = false;
4999     offloadInfo.is_streaming = false;
5000     const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
5001 
5002     audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
5003     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5004     audio_flags_to_audio_output_flags(attr->flags, &flags);
5005     // only retain flags that will drive compressed offload or passthrough
5006     uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
5007     if (offloadPossible) {
5008         relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
5009     }
5010     flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
5011 
5012     DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
5013     if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
5014             [this, attr](sp<DeviceDescriptor> device) {
5015                     return getPreferredMixerAttributesInfo(
5016                             device->getId(),
5017                             mEngine->getProductStrategyForAttributes(*attr),
5018                             true /*activeBitPerfectPreferred*/) != nullptr;
5019             })) {
5020         // Bit-perfect playback is active on one of the selected devices, direct output will
5021         // be rejected at this instant.
5022         return AUDIO_DIRECT_NOT_SUPPORTED;
5023     }
5024     for (const auto& hwModule : mHwModules) {
5025         DeviceVector outputDevices = engineOutputDevices;
5026         // the MSD module checks for different conditions and output devices
5027         if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
5028             if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
5029                 continue;
5030             }
5031             outputDevices = getMsdAudioOutDevices();
5032         }
5033         for (const auto& curProfile : hwModule->getOutputProfiles()) {
5034             if (curProfile->getCompatibilityScore(outputDevices,
5035                     config->sample_rate, nullptr /*updatedSamplingRate*/,
5036                     config->format, nullptr /*updatedFormat*/,
5037                     config->channel_mask, nullptr /*updatedChannelMask*/,
5038                     flags) == IOProfile::NO_MATCH) {
5039                 continue;
5040             }
5041             // reject profiles not corresponding to a device currently available
5042             if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
5043                 continue;
5044             }
5045             if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
5046                         != AUDIO_OUTPUT_FLAG_NONE)) {
5047                 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
5048                         != AUDIO_DIRECT_NOT_SUPPORTED) {
5049                     // Already reports offload gapless supported. No need to report offload support.
5050                     continue;
5051                 }
5052                 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
5053                         != AUDIO_OUTPUT_FLAG_NONE) {
5054                     // If offload gapless is reported, no need to report offload support.
5055                     directMode = (audio_direct_mode_t) ((directMode &
5056                             ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
5057                             AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
5058                 } else {
5059                     directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
5060                 }
5061             } else {
5062                 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
5063             }
5064         }
5065     }
5066     return directMode;
5067 }
5068 
getDirectProfilesForAttributes(const audio_attributes_t * attr,AudioProfileVector & audioProfilesVector)5069 status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
5070                                                 AudioProfileVector& audioProfilesVector) {
5071     if (mEffects.isNonOffloadableEffectEnabled()) {
5072         return OK;
5073     }
5074     DeviceVector devices;
5075     status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
5076     if (status != OK) {
5077         return status;
5078     }
5079     ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
5080     if (devices.empty()) {
5081         return OK; // no output devices for the attributes
5082     }
5083     return getProfilesForDevices(devices, audioProfilesVector,
5084                                  AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
5085 }
5086 
getSupportedMixerAttributes(audio_port_handle_t portId,std::vector<audio_mixer_attributes_t> & mixerAttrs)5087 status_t AudioPolicyManager::getSupportedMixerAttributes(
5088         audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
5089     ALOGV("%s, portId=%d", __func__, portId);
5090     sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5091     if (deviceDescriptor == nullptr) {
5092         ALOGE("%s the requested device is currently unavailable", __func__);
5093         return BAD_VALUE;
5094     }
5095     if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5096         ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
5097               deviceDescriptor->type());
5098         return BAD_VALUE;
5099     }
5100     for (const auto& hwModule : mHwModules) {
5101         for (const auto& curProfile : hwModule->getOutputProfiles()) {
5102             if (curProfile->supportsDevice(deviceDescriptor)) {
5103                 curProfile->toSupportedMixerAttributes(&mixerAttrs);
5104             }
5105         }
5106     }
5107     return NO_ERROR;
5108 }
5109 
setPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,uid_t uid,const audio_mixer_attributes_t * mixerAttributes)5110 status_t AudioPolicyManager::setPreferredMixerAttributes(
5111         const audio_attributes_t *attr,
5112         audio_port_handle_t portId,
5113         uid_t uid,
5114         const audio_mixer_attributes_t *mixerAttributes) {
5115     ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
5116           "mixerBehavior=%d}, uid=%d, portId=%u",
5117           __func__, toString(*attr).c_str(), mixerAttributes->config.format,
5118           mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
5119           mixerAttributes->mixer_behavior, uid, portId);
5120     if (attr->usage != AUDIO_USAGE_MEDIA) {
5121         ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5122         return BAD_VALUE;
5123     }
5124     sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5125     if (deviceDescriptor == nullptr) {
5126         ALOGE("%s the requested device is currently unavailable", __func__);
5127         return BAD_VALUE;
5128     }
5129     if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5130         ALOGE("%s(%d), type=%d, is not a usb output device",
5131               __func__, portId, deviceDescriptor->type());
5132         return BAD_VALUE;
5133     }
5134 
5135     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5136     audio_flags_to_audio_output_flags(attr->flags, &flags);
5137     flags = (audio_output_flags_t) (flags |
5138             audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5139     sp<IOProfile> profile = nullptr;
5140     DeviceVector devices(deviceDescriptor);
5141     for (const auto& hwModule : mHwModules) {
5142         for (const auto& curProfile : hwModule->getOutputProfiles()) {
5143             if (curProfile->hasDynamicAudioProfile()
5144                     && curProfile->getCompatibilityScore(
5145                             devices,
5146                             mixerAttributes->config.sample_rate,
5147                             nullptr /*updatedSamplingRate*/,
5148                             mixerAttributes->config.format,
5149                             nullptr /*updatedFormat*/,
5150                             mixerAttributes->config.channel_mask,
5151                             nullptr /*updatedChannelMask*/,
5152                             flags)
5153                             != IOProfile::NO_MATCH) {
5154                 profile = curProfile;
5155                 break;
5156             }
5157         }
5158     }
5159     if (profile == nullptr) {
5160         ALOGE("%s, there is no compatible profile found", __func__);
5161         return BAD_VALUE;
5162     }
5163 
5164     sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5165             sp<PreferredMixerAttributesInfo>::make(
5166                     uid, portId, profile, flags, *mixerAttributes);
5167     const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5168     mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5169 
5170     // If 1) there is any client from the preferred mixer configuration owner that is currently
5171     // active and matches the strategy and 2) current output is on the preferred device and the
5172     // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5173     // configuration.
5174     std::vector<audio_io_handle_t> outputsToReopen;
5175     for (size_t i = 0; i < mOutputs.size(); i++) {
5176         const auto output = mOutputs.valueAt(i);
5177         if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5178             if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
5179                 output->mPreferredAttrInfo = mixerAttrInfo;
5180             } else {
5181                 for (const auto &client: output->getActiveClients()) {
5182                     if (client->uid() == uid && client->strategy() == strategy) {
5183                         client->setIsInvalid();
5184                         outputsToReopen.push_back(output->mIoHandle);
5185                     }
5186                 }
5187             }
5188         }
5189     }
5190     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5191     config.sample_rate = mixerAttributes->config.sample_rate;
5192     config.channel_mask = mixerAttributes->config.channel_mask;
5193     config.format = mixerAttributes->config.format;
5194     for (const auto output : outputsToReopen) {
5195         sp<SwAudioOutputDescriptor> desc =
5196                 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5197         if (desc == nullptr) {
5198             ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5199             continue;
5200         }
5201         desc->mPreferredAttrInfo = mixerAttrInfo;
5202     }
5203 
5204     return NO_ERROR;
5205 }
5206 
getPreferredMixerAttributesInfo(audio_port_handle_t devicePortId,product_strategy_t strategy,bool activeBitPerfectPreferred)5207 sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
5208         audio_port_handle_t devicePortId,
5209         product_strategy_t strategy,
5210         bool activeBitPerfectPreferred) {
5211     auto it = mPreferredMixerAttrInfos.find(devicePortId);
5212     if (it == mPreferredMixerAttrInfos.end()) {
5213         return nullptr;
5214     }
5215     if (activeBitPerfectPreferred) {
5216         for (auto [strategy, info] : it->second) {
5217             if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
5218                 return info;
5219             }
5220         }
5221     }
5222     auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5223     return strategyMatchedMixerAttrInfoIt == it->second.end()
5224             ? nullptr : strategyMatchedMixerAttrInfoIt->second;
5225 }
5226 
getPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,audio_mixer_attributes_t * mixerAttributes)5227 status_t AudioPolicyManager::getPreferredMixerAttributes(
5228         const audio_attributes_t *attr,
5229         audio_port_handle_t portId,
5230         audio_mixer_attributes_t* mixerAttributes) {
5231     sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5232             portId, mEngine->getProductStrategyForAttributes(*attr));
5233     if (info == nullptr) {
5234         return NAME_NOT_FOUND;
5235     }
5236     *mixerAttributes = info->getMixerAttributes();
5237     return NO_ERROR;
5238 }
5239 
clearPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,uid_t uid)5240 status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5241                                                            audio_port_handle_t portId,
5242                                                            uid_t uid) {
5243     const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5244     const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5245     if (preferredMixerAttrInfo == nullptr) {
5246         return NAME_NOT_FOUND;
5247     }
5248     if (preferredMixerAttrInfo->getUid() != uid) {
5249         ALOGE("%s, requested uid=%d, owned uid=%d",
5250               __func__, uid, preferredMixerAttrInfo->getUid());
5251         return PERMISSION_DENIED;
5252     }
5253     mPreferredMixerAttrInfos[portId].erase(strategy);
5254     if (mPreferredMixerAttrInfos[portId].empty()) {
5255         mPreferredMixerAttrInfos.erase(portId);
5256     }
5257 
5258     // Reconfig existing output
5259     std::vector<audio_io_handle_t> potentialOutputsToReopen;
5260     for (size_t i = 0; i < mOutputs.size(); i++) {
5261         if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5262             potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5263         }
5264     }
5265     for (const auto output : potentialOutputsToReopen) {
5266         sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5267         if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5268                                          preferredMixerAttrInfo->getFlags())) {
5269             reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5270         }
5271     }
5272     return NO_ERROR;
5273 }
5274 
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port_v7 * ports,unsigned int * generation)5275 status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5276                                             audio_port_type_t type,
5277                                             unsigned int *num_ports,
5278                                             struct audio_port_v7 *ports,
5279                                             unsigned int *generation)
5280 {
5281     if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5282             generation == nullptr) {
5283         return BAD_VALUE;
5284     }
5285     ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
5286     if (ports == nullptr) {
5287         *num_ports = 0;
5288     }
5289 
5290     size_t portsWritten = 0;
5291     size_t portsMax = *num_ports;
5292     *num_ports = 0;
5293     if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
5294         // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5295         // as they are used by stub HALs by convention
5296         if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5297             for (const auto& dev : mAvailableOutputDevices) {
5298                 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
5299                     continue;
5300                 }
5301                 if (portsWritten < portsMax) {
5302                     dev->toAudioPort(&ports[portsWritten++]);
5303                 }
5304                 (*num_ports)++;
5305             }
5306         }
5307         if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
5308             for (const auto& dev : mAvailableInputDevices) {
5309                 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
5310                     continue;
5311                 }
5312                 if (portsWritten < portsMax) {
5313                     dev->toAudioPort(&ports[portsWritten++]);
5314                 }
5315                 (*num_ports)++;
5316             }
5317         }
5318     }
5319     if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5320         if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5321             for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5322                 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5323             }
5324             *num_ports += mInputs.size();
5325         }
5326         if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
5327             size_t numOutputs = 0;
5328             for (size_t i = 0; i < mOutputs.size(); i++) {
5329                 if (!mOutputs[i]->isDuplicated()) {
5330                     numOutputs++;
5331                     if (portsWritten < portsMax) {
5332                         mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5333                     }
5334                 }
5335             }
5336             *num_ports += numOutputs;
5337         }
5338     }
5339 
5340     *generation = curAudioPortGeneration();
5341     ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
5342     return NO_ERROR;
5343 }
5344 
listDeclaredDevicePorts(media::AudioPortRole role,std::vector<media::AudioPortFw> * _aidl_return)5345 status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5346         std::vector<media::AudioPortFw>* _aidl_return) {
5347     auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5348         audio_port_v7 port;
5349         dev->toAudioPort(&port);
5350         auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5351         _aidl_return->push_back(std::move(aidlPort));
5352         return OK;
5353     };
5354 
5355     for (const auto& module : mHwModules) {
5356         for (const auto& dev : module->getDeclaredDevices()) {
5357             if (role == media::AudioPortRole::NONE ||
5358                     ((role == media::AudioPortRole::SOURCE)
5359                             == audio_is_input_device(dev->type()))) {
5360                 RETURN_STATUS_IF_ERROR(pushPort(dev));
5361             }
5362         }
5363     }
5364     return OK;
5365 }
5366 
getAudioPort(struct audio_port_v7 * port)5367 status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
5368 {
5369     if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5370         return BAD_VALUE;
5371     }
5372     sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5373     if (dev != 0) {
5374         dev->toAudioPort(port);
5375         return NO_ERROR;
5376     }
5377     dev = mAvailableInputDevices.getDeviceFromId(port->id);
5378     if (dev != 0) {
5379         dev->toAudioPort(port);
5380         return NO_ERROR;
5381     }
5382     sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5383     if (out != 0) {
5384         out->toAudioPort(port);
5385         return NO_ERROR;
5386     }
5387     sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5388     if (in != 0) {
5389         in->toAudioPort(port);
5390         return NO_ERROR;
5391     }
5392     return BAD_VALUE;
5393 }
5394 
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid)5395 status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5396                                               audio_patch_handle_t *handle,
5397                                               uid_t uid)
5398 {
5399     ALOGV("%s", __func__);
5400     if (handle == NULL || patch == NULL) {
5401         return BAD_VALUE;
5402     }
5403     ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
5404     if (!audio_patch_is_valid(patch)) {
5405         return BAD_VALUE;
5406     }
5407     // only one source per audio patch supported for now
5408     if (patch->num_sources > 1) {
5409         return INVALID_OPERATION;
5410     }
5411     if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
5412         return INVALID_OPERATION;
5413     }
5414     for (size_t i = 0; i < patch->num_sinks; i++) {
5415         if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5416             return INVALID_OPERATION;
5417         }
5418     }
5419 
5420     sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5421     sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5422     if (srcDevice == nullptr || sinkDevice == nullptr) {
5423         ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5424         return BAD_VALUE;
5425     }
5426     ALOGV("%s between source %s and sink %s", __func__,
5427             srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5428     audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5429     // Default attributes, default volume priority, not to infer with non raw audio patches.
5430     audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5431     const struct audio_port_config *source = &patch->sources[0];
5432     sp<SourceClientDescriptor> sourceDesc =
5433             new SourceClientDescriptor(
5434                 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5435                 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
5436                 true, false /*isCallRx*/, false /*isCallTx*/);
5437     sourceDesc->setPreferredDeviceId(sinkDevice->getId());
5438 
5439     status_t status =
5440             connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5441 
5442     if (status != NO_ERROR) {
5443         return INVALID_OPERATION;
5444     }
5445     mAudioSources.add(portId, sourceDesc);
5446     return NO_ERROR;
5447 }
5448 
connectAudioSourceToSink(const sp<SourceClientDescriptor> & sourceDesc,const sp<DeviceDescriptor> & sinkDevice,const struct audio_patch * patch,audio_patch_handle_t & handle,uid_t uid,uint32_t delayMs)5449 status_t AudioPolicyManager::connectAudioSourceToSink(
5450         const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5451         const struct audio_patch *patch,
5452         audio_patch_handle_t &handle,
5453         uid_t uid, uint32_t delayMs)
5454 {
5455     status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5456     if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5457         ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5458         return INVALID_OPERATION;
5459     }
5460     sourceDesc->connect(handle, sinkDevice);
5461     if (isMsdPatch(handle)) {
5462         return NO_ERROR;
5463     }
5464     // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5465     sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5466     ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5467     if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5468         ALOGW("%s source portId has already been attached to outputDesc", __func__);
5469         goto FailurePatchAdded;
5470     }
5471     status = swOutput->start();
5472     if (status != NO_ERROR) {
5473         goto FailureSourceAdded;
5474     }
5475     swOutput->addClient(sourceDesc);
5476     status = startSource(swOutput, sourceDesc, &delayMs);
5477     if (status != NO_ERROR) {
5478         ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5479         goto FailureSourceActive;
5480     }
5481     if (delayMs != 0) {
5482         usleep(delayMs * 1000);
5483     }
5484     return NO_ERROR;
5485 
5486 FailureSourceActive:
5487     swOutput->stop();
5488     releaseOutput(sourceDesc->portId());
5489 FailureSourceAdded:
5490     sourceDesc->setSwOutput(nullptr);
5491 FailurePatchAdded:
5492     releaseAudioPatchInternal(handle);
5493     return INVALID_OPERATION;
5494 }
5495 
createAudioPatchInternal(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid,uint32_t delayMs,const sp<SourceClientDescriptor> & sourceDesc)5496 status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5497                                                       audio_patch_handle_t *handle,
5498                                                       uid_t uid, uint32_t delayMs,
5499                                                       const sp<SourceClientDescriptor>& sourceDesc)
5500 {
5501     ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
5502     sp<AudioPatch> patchDesc;
5503     ssize_t index = mAudioPatches.indexOfKey(*handle);
5504 
5505     ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5506                                                        patch->sources[0].role,
5507                                                        patch->sources[0].type);
5508 #if LOG_NDEBUG == 0
5509     for (size_t i = 0; i < patch->num_sinks; i++) {
5510         ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5511                                                                  patch->sinks[i].role,
5512                                                                  patch->sinks[i].type);
5513     }
5514 #endif
5515 
5516     if (index >= 0) {
5517         patchDesc = mAudioPatches.valueAt(index);
5518         ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5519               __func__, mUidCached, patchDesc->getUid(), uid);
5520         if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
5521             return INVALID_OPERATION;
5522         }
5523     } else {
5524         *handle = AUDIO_PATCH_HANDLE_NONE;
5525     }
5526 
5527     if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
5528         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
5529         if (outputDesc == NULL) {
5530             ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
5531             return BAD_VALUE;
5532         }
5533         ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5534                                                 outputDesc->mIoHandle);
5535         if (patchDesc != 0) {
5536             if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
5537                 ALOGV("%s source id differs for patch current id %d new id %d",
5538                       __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
5539                 return BAD_VALUE;
5540             }
5541         }
5542         DeviceVector devices;
5543         for (size_t i = 0; i < patch->num_sinks; i++) {
5544             // Only support mix to devices connection
5545             // TODO add support for mix to mix connection
5546             if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
5547                 ALOGV("%s source mix but sink is not a device", __func__);
5548                 return INVALID_OPERATION;
5549             }
5550             sp<DeviceDescriptor> devDesc =
5551                     mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5552             if (devDesc == 0) {
5553                 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
5554                 return BAD_VALUE;
5555             }
5556 
5557             if (outputDesc->mProfile->getCompatibilityScore(
5558                     DeviceVector(devDesc),
5559                     patch->sources[0].sample_rate,
5560                     nullptr,  // updatedSamplingRate
5561                     patch->sources[0].format,
5562                     nullptr,  // updatedFormat
5563                     patch->sources[0].channel_mask,
5564                     nullptr,  // updatedChannelMask
5565                     AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
5566                 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
5567                 return INVALID_OPERATION;
5568             }
5569             devices.add(devDesc);
5570         }
5571         if (devices.size() == 0) {
5572             return INVALID_OPERATION;
5573         }
5574 
5575         // TODO: reconfigure output format and channels here
5576         ALOGV("%s setting device %s on output %d",
5577               __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
5578         setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
5579         index = mAudioPatches.indexOfKey(*handle);
5580         if (index >= 0) {
5581             if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
5582                 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
5583             }
5584             patchDesc = mAudioPatches.valueAt(index);
5585             patchDesc->setUid(uid);
5586             ALOGV("%s success", __func__);
5587         } else {
5588             ALOGW("%s setOutputDevice() failed to create a patch", __func__);
5589             return INVALID_OPERATION;
5590         }
5591     } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5592         if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5593             // input device to input mix connection
5594             // only one sink supported when connecting an input device to a mix
5595             if (patch->num_sinks > 1) {
5596                 return INVALID_OPERATION;
5597             }
5598             sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
5599             if (inputDesc == NULL) {
5600                 return BAD_VALUE;
5601             }
5602             if (patchDesc != 0) {
5603                 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5604                     return BAD_VALUE;
5605                 }
5606             }
5607             sp<DeviceDescriptor> device =
5608                     mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5609             if (device == 0) {
5610                 return BAD_VALUE;
5611             }
5612 
5613             if (inputDesc->mProfile->getCompatibilityScore(
5614                     DeviceVector(device),
5615                     patch->sinks[0].sample_rate,
5616                     nullptr, /*updatedSampleRate*/
5617                     patch->sinks[0].format,
5618                     nullptr, /*updatedFormat*/
5619                     patch->sinks[0].channel_mask,
5620                     nullptr, /*updatedChannelMask*/
5621                     // FIXME for the parameter type,
5622                     // and the NONE
5623                     (audio_output_flags_t)
5624                     AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
5625                 return INVALID_OPERATION;
5626             }
5627             // TODO: reconfigure output format and channels here
5628             ALOGV("%s setting device %s on output %d", __func__,
5629                   device->toString().c_str(), inputDesc->mIoHandle);
5630             setInputDevice(inputDesc->mIoHandle, device, true, handle);
5631             index = mAudioPatches.indexOfKey(*handle);
5632             if (index >= 0) {
5633                 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
5634                     ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
5635                 }
5636                 patchDesc = mAudioPatches.valueAt(index);
5637                 patchDesc->setUid(uid);
5638                 ALOGV("%s success", __func__);
5639             } else {
5640                 ALOGW("%s setInputDevice() failed to create a patch", __func__);
5641                 return INVALID_OPERATION;
5642             }
5643         } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5644             // device to device connection
5645             if (patchDesc != 0) {
5646                 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
5647                     return BAD_VALUE;
5648                 }
5649             }
5650             sp<DeviceDescriptor> srcDevice =
5651                     mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5652             if (srcDevice == 0) {
5653                 return BAD_VALUE;
5654             }
5655 
5656             //update source and sink with our own data as the data passed in the patch may
5657             // be incomplete.
5658             PatchBuilder patchBuilder;
5659             audio_port_config sourcePortConfig = {};
5660 
5661             // if first sink is to MSD, establish single MSD patch
5662             if (getMsdAudioOutDevices().contains(
5663                         mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5664                 ALOGV("%s patching to MSD", __FUNCTION__);
5665                 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5666                 goto installPatch;
5667             }
5668 
5669             srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5670             patchBuilder.addSource(sourcePortConfig);
5671 
5672             for (size_t i = 0; i < patch->num_sinks; i++) {
5673                 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
5674                     ALOGV("%s source device but one sink is not a device", __func__);
5675                     return INVALID_OPERATION;
5676                 }
5677                 sp<DeviceDescriptor> sinkDevice =
5678                         mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5679                 if (sinkDevice == 0) {
5680                     return BAD_VALUE;
5681                 }
5682                 audio_port_config sinkPortConfig = {};
5683                 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5684                 patchBuilder.addSink(sinkPortConfig);
5685 
5686                 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5687                 // volume management purpose (tracking activity)
5688                 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5689                 // in config XML to reach the sink so that is can be declared as available.
5690                 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
5691                 sp<SwAudioOutputDescriptor> outputDesc;
5692                 if (!sourceDesc->isInternal()) {
5693                     // take care of dynamic routing for SwOutput selection,
5694                     audio_attributes_t attributes = sourceDesc->attributes();
5695                     audio_stream_type_t stream = sourceDesc->stream();
5696                     audio_attributes_t resultAttr;
5697                     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5698                     config.sample_rate = sourceDesc->config().sample_rate;
5699                     audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5700                     config.channel_mask =
5701                             (audio_channel_mask_get_representation(sourceMask)
5702                                 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5703                                     : audio_channel_mask_in_to_out(sourceMask);
5704                     config.format = sourceDesc->config().format;
5705                     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5706                     DeviceIdVector selectedDeviceIds;
5707                     bool isRequestedDeviceForExclusiveUse = false;
5708                     output_type_t outputType;
5709                     bool isSpatialized;
5710                     bool isBitPerfect;
5711                     getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5712                                         &stream, sourceDesc->uid(), &config, &flags,
5713                                         &selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
5714                                         nullptr, &outputType, &isSpatialized, &isBitPerfect);
5715                     if (output == AUDIO_IO_HANDLE_NONE) {
5716                         ALOGV("%s no output for device %s",
5717                               __FUNCTION__, sinkDevice->toString().c_str());
5718                         return INVALID_OPERATION;
5719                     }
5720                     outputDesc = mOutputs.valueFor(output);
5721                     if (outputDesc->isDuplicated()) {
5722                         ALOGE("%s output is duplicated", __func__);
5723                         return INVALID_OPERATION;
5724                     }
5725                     bool closeOutput = outputDesc->mDirectOpenCount != 0;
5726                     sourceDesc->setSwOutput(outputDesc, closeOutput);
5727                 } else {
5728                     // Same for "raw patches" aka created from createAudioPatch API
5729                     SortedVector<audio_io_handle_t> outputs =
5730                             getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5731                     // if the sink device is reachable via an opened output stream, request to
5732                     // go via this output stream by adding a second source to the patch
5733                     // description
5734                     output = selectOutput(outputs);
5735                     if (output == AUDIO_IO_HANDLE_NONE) {
5736                         ALOGE("%s no output available for internal patch sink", __func__);
5737                         return INVALID_OPERATION;
5738                     }
5739                     outputDesc = mOutputs.valueFor(output);
5740                     if (outputDesc->isDuplicated()) {
5741                         ALOGV("%s output for device %s is duplicated",
5742                               __func__, sinkDevice->toString().c_str());
5743                         return INVALID_OPERATION;
5744                     }
5745                     sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
5746                 }
5747                 // create a software bridge in PatchPanel if:
5748                 // - source and sink devices are on different HW modules OR
5749                 // - audio HAL version is < 3.0
5750                 // - audio HAL version is >= 3.0 but no route has been declared between devices
5751                 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5752                 //   does not have a gain controller
5753                 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5754                         (srcDevice->getModuleVersionMajor() < 3) ||
5755                         !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
5756                         (!sourceDesc->isInternal() &&
5757                          srcDevice->getAudioPort()->getGains().size() == 0)) {
5758                     // support only one sink device for now to simplify output selection logic
5759                     if (patch->num_sinks > 1) {
5760                         return INVALID_OPERATION;
5761                     }
5762                     sourceDesc->setUseSwBridge();
5763                     if (outputDesc != nullptr) {
5764                         audio_port_config srcMixPortConfig = {};
5765                         outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
5766                         // for volume control, we may need a valid stream
5767                         srcMixPortConfig.ext.mix.usecase.stream =
5768                             (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
5769                                     mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5770                                     AUDIO_STREAM_PATCH;
5771                         patchBuilder.addSource(srcMixPortConfig);
5772                     }
5773                 }
5774             }
5775             // TODO: check from routing capabilities in config file and other conflicting patches
5776 
5777 installPatch:
5778             status_t status = installPatch(
5779                         __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
5780             if (status != NO_ERROR) {
5781                 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5782                 return INVALID_OPERATION;
5783             }
5784         } else {
5785             return BAD_VALUE;
5786         }
5787     } else {
5788         return BAD_VALUE;
5789     }
5790     return NO_ERROR;
5791 }
5792 
releaseAudioPatch(audio_patch_handle_t handle,uid_t uid)5793 status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
5794 {
5795     ALOGV("%s patch %d", __func__, handle);
5796     ssize_t index = mAudioPatches.indexOfKey(handle);
5797 
5798     if (index < 0) {
5799         return BAD_VALUE;
5800     }
5801     sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5802     ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5803           __func__, mUidCached, patchDesc->getUid(), uid);
5804     if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
5805         return INVALID_OPERATION;
5806     }
5807     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5808     for (size_t i = 0; i < mAudioSources.size(); i++)  {
5809         sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5810         if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5811             portId = sourceDesc->portId();
5812             break;
5813         }
5814     }
5815     return portId != AUDIO_PORT_HANDLE_NONE ?
5816                 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
5817 }
5818 
releaseAudioPatchInternal(audio_patch_handle_t handle,uint32_t delayMs,const sp<SourceClientDescriptor> & sourceDesc)5819 status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
5820                                                        uint32_t delayMs,
5821                                                        const sp<SourceClientDescriptor>& sourceDesc)
5822 {
5823     ALOGV("%s patch %d", __func__, handle);
5824     if (mAudioPatches.indexOfKey(handle) < 0) {
5825         ALOGE("%s: no patch found with handle=%d", __func__, handle);
5826         return BAD_VALUE;
5827     }
5828     sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
5829     struct audio_patch *patch = &patchDesc->mPatch;
5830     patchDesc->setUid(mUidCached);
5831     if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
5832         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
5833         if (outputDesc == NULL) {
5834             ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
5835             return BAD_VALUE;
5836         }
5837 
5838         setOutputDevices(__func__, outputDesc,
5839                          getNewOutputDevices(outputDesc, true /*fromCache*/),
5840                          true,
5841                          0,
5842                          NULL);
5843     } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5844         if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5845             sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
5846             if (inputDesc == NULL) {
5847                 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
5848                 return BAD_VALUE;
5849             }
5850             setInputDevice(inputDesc->mIoHandle,
5851                            getNewInputDevice(inputDesc),
5852                            true,
5853                            NULL);
5854         } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5855             status_t status =
5856                     mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5857             ALOGV("%s patch panel returned %d patchHandle %d",
5858                   __func__, status, patchDesc->getAfHandle());
5859             removeAudioPatch(patchDesc->getHandle());
5860             nextAudioPortGeneration();
5861             mpClientInterface->onAudioPatchListUpdate();
5862             // SW or HW Bridge
5863             sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5864             audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
5865             if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
5866                 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5867             } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5868                 outputDesc = sourceDesc->swOutput().promote();
5869             }
5870             if (outputDesc == nullptr) {
5871                 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5872                 // releaseOutput has already called closeOutput in case of direct output
5873                 return NO_ERROR;
5874             }
5875             patchHandle = outputDesc->getPatchHandle();
5876             // While using a HwBridge, force reconsidering device only if not reusing an existing
5877             // output and no more activity on output (will force to close).
5878             const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
5879             // APM pattern is to have always outputs opened / patch realized for reachable devices.
5880             // Update device may result to NONE (empty), coupled with force, it releases the patch.
5881             // Reconsider device only for cases:
5882             //      1 / Active Output
5883             //      2 / Inactive Output previously hosting HwBridge
5884             //      3 / Inactive Output previously hosting SwBridge that can be closed.
5885             bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5886                     sourceDesc->canCloseOutput();
5887             setOutputDevices(__func__, outputDesc,
5888                              updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5889                                             outputDesc->devices(),
5890                              force,
5891                              0,
5892                              patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
5893         } else {
5894             return BAD_VALUE;
5895         }
5896     } else {
5897         return BAD_VALUE;
5898     }
5899     return NO_ERROR;
5900 }
5901 
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)5902 status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5903                                               struct audio_patch *patches,
5904                                               unsigned int *generation)
5905 {
5906     if (generation == NULL) {
5907         return BAD_VALUE;
5908     }
5909     *generation = curAudioPortGeneration();
5910     return mAudioPatches.listAudioPatches(num_patches, patches);
5911 }
5912 
setAudioPortConfig(const struct audio_port_config * config)5913 status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
5914 {
5915     ALOGV("setAudioPortConfig()");
5916 
5917     if (config == NULL) {
5918         return BAD_VALUE;
5919     }
5920     ALOGV("setAudioPortConfig() on port handle %d", config->id);
5921     // Only support gain configuration for now
5922     if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5923         return INVALID_OPERATION;
5924     }
5925 
5926     sp<AudioPortConfig> audioPortConfig;
5927     if (config->type == AUDIO_PORT_TYPE_MIX) {
5928         if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5929             sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
5930             if (outputDesc == NULL) {
5931                 return BAD_VALUE;
5932             }
5933             ALOG_ASSERT(!outputDesc->isDuplicated(),
5934                         "setAudioPortConfig() called on duplicated output %d",
5935                         outputDesc->mIoHandle);
5936             audioPortConfig = outputDesc;
5937         } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5938             sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
5939             if (inputDesc == NULL) {
5940                 return BAD_VALUE;
5941             }
5942             audioPortConfig = inputDesc;
5943         } else {
5944             return BAD_VALUE;
5945         }
5946     } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5947         sp<DeviceDescriptor> deviceDesc;
5948         if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5949             deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5950         } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5951             deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5952         } else {
5953             return BAD_VALUE;
5954         }
5955         if (deviceDesc == NULL) {
5956             return BAD_VALUE;
5957         }
5958         audioPortConfig = deviceDesc;
5959     } else {
5960         return BAD_VALUE;
5961     }
5962 
5963     struct audio_port_config backupConfig = {};
5964     status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5965     if (status == NO_ERROR) {
5966         struct audio_port_config newConfig = {};
5967         audioPortConfig->toAudioPortConfig(&newConfig, config);
5968         status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
5969     }
5970     if (status != NO_ERROR) {
5971         audioPortConfig->applyAudioPortConfig(&backupConfig);
5972     }
5973 
5974     return status;
5975 }
5976 
releaseResourcesForUid(uid_t uid)5977 void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5978 {
5979     clearAudioSources(uid);
5980     clearAudioPatches(uid);
5981     clearSessionRoutes(uid);
5982 }
5983 
clearAudioPatches(uid_t uid)5984 void AudioPolicyManager::clearAudioPatches(uid_t uid)
5985 {
5986     for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--)  {
5987         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5988         if (patchDesc->getUid() == uid) {
5989             releaseAudioPatch(mAudioPatches.keyAt(i), uid);
5990         }
5991     }
5992 }
5993 
checkStrategyRoute(product_strategy_t ps,audio_io_handle_t ouptutToSkip)5994 void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
5995 {
5996     // Take the first attributes following the product strategy as it is used to retrieve the routed
5997     // device. All attributes wihin a strategy follows the same "routing strategy"
5998     auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5999     DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
6000     SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
6001     std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
6002     for (size_t j = 0; j < mOutputs.size(); j++) {
6003         if (mOutputs.keyAt(j) == ouptutToSkip) {
6004             continue;
6005         }
6006         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
6007         if (!outputDesc->isStrategyActive(ps)) {
6008             continue;
6009         }
6010         // If the default device for this strategy is on another output mix,
6011         // invalidate all tracks in this strategy to force re connection.
6012         // Otherwise select new device on the output mix.
6013         if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
6014             invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
6015         } else {
6016             DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
6017             if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
6018                 // If the device is using preferred mixer attributes, the output need to reopen
6019                 // with default configuration when the new selected devices are different from
6020                 // current routing devices.
6021                 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
6022                 continue;
6023             }
6024             setOutputDevices(__func__, outputDesc, newDevices, false);
6025         }
6026     }
6027     reopenOutputsWithDevices(outputsToReopen);
6028 }
6029 
clearSessionRoutes(uid_t uid)6030 void AudioPolicyManager::clearSessionRoutes(uid_t uid)
6031 {
6032     // remove output routes associated with this uid
6033     std::vector<product_strategy_t> affectedStrategies;
6034     for (size_t i = 0; i < mOutputs.size(); i++) {
6035         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
6036         for (const auto& client : outputDesc->getClientIterable()) {
6037             if (client->hasPreferredDevice() && client->uid() == uid) {
6038                 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
6039                 auto clientStrategy = client->strategy();
6040                 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
6041                         end(affectedStrategies)) {
6042                     continue;
6043                 }
6044                 affectedStrategies.push_back(client->strategy());
6045             }
6046         }
6047     }
6048     // reroute outputs if necessary
6049     for (const auto& strategy : affectedStrategies) {
6050         checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
6051     }
6052 
6053     // remove input routes associated with this uid
6054     SortedVector<audio_source_t> affectedSources;
6055     for (size_t i = 0; i < mInputs.size(); i++) {
6056         sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
6057         for (const auto& client : inputDesc->getClientIterable()) {
6058             if (client->hasPreferredDevice() && client->uid() == uid) {
6059                 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
6060                 affectedSources.add(client->source());
6061             }
6062         }
6063     }
6064     // reroute inputs if necessary
6065     SortedVector<audio_io_handle_t> inputsToClose;
6066     for (size_t i = 0; i < mInputs.size(); i++) {
6067         sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
6068         if (affectedSources.indexOf(inputDesc->source()) >= 0) {
6069             inputsToClose.add(inputDesc->mIoHandle);
6070         }
6071     }
6072     for (const auto& input : inputsToClose) {
6073         closeInput(input);
6074     }
6075 }
6076 
clearAudioSources(uid_t uid)6077 void AudioPolicyManager::clearAudioSources(uid_t uid)
6078 {
6079     for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--)  {
6080         sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6081         if (sourceDesc->uid() == uid) {
6082             stopAudioSource(mAudioSources.keyAt(i));
6083         }
6084     }
6085 }
6086 
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)6087 status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
6088                                        audio_io_handle_t *ioHandle,
6089                                        audio_devices_t *device)
6090 {
6091     *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
6092     *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
6093     audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
6094     sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
6095     if (deviceDesc == nullptr) {
6096         return INVALID_OPERATION;
6097     }
6098     *device = deviceDesc->type();
6099 
6100     return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
6101 }
6102 
startAudioSource(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_port_handle_t * portId,uid_t uid)6103 status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
6104                                               const audio_attributes_t *attributes,
6105                                               audio_port_handle_t *portId,
6106                                               uid_t uid) {
6107     return startAudioSourceInternal(source, attributes, portId, uid,
6108                                     false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
6109 }
6110 
startAudioSourceInternal(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_port_handle_t * portId,uid_t uid,bool internal,bool isCallRx,uint32_t delayMs)6111 status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
6112                                               const audio_attributes_t *attributes,
6113                                               audio_port_handle_t *portId,
6114                                               uid_t uid, bool internal, bool isCallRx,
6115                                               uint32_t delayMs)
6116 {
6117     ALOGV("%s", __FUNCTION__);
6118     *portId = AUDIO_PORT_HANDLE_NONE;
6119 
6120     if (source == NULL || attributes == NULL || portId == NULL) {
6121         ALOGW("%s invalid argument: source %p attributes %p handle %p",
6122               __FUNCTION__, source, attributes, portId);
6123         return BAD_VALUE;
6124     }
6125 
6126     if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6127             source->type != AUDIO_PORT_TYPE_DEVICE) {
6128         ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6129               __FUNCTION__, source->role, source->type);
6130         return INVALID_OPERATION;
6131     }
6132 
6133     sp<DeviceDescriptor> srcDevice =
6134             mAvailableInputDevices.getDevice(source->ext.device.type,
6135                                              String8(source->ext.device.address),
6136                                              AUDIO_FORMAT_DEFAULT);
6137     if (srcDevice == 0) {
6138         ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
6139         return BAD_VALUE;
6140     }
6141 
6142     *portId = PolicyAudioPort::getNextUniqueId();
6143 
6144     sp<SourceClientDescriptor> sourceDesc =
6145         new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
6146                                    mEngine->getStreamTypeForAttributes(*attributes),
6147                                    mEngine->getProductStrategyForAttributes(*attributes),
6148                                    toVolumeSource(*attributes), internal, isCallRx, false);
6149 
6150     status_t status = connectAudioSource(sourceDesc, delayMs);
6151     if (status == NO_ERROR) {
6152         mAudioSources.add(*portId, sourceDesc);
6153     }
6154     return status;
6155 }
6156 
connectAudioSource(const sp<SourceClientDescriptor> & sourceDesc,uint32_t delayMs)6157 status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6158                                                 uint32_t delayMs)
6159 {
6160     ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
6161 
6162     // make sure we only have one patch per source.
6163     disconnectAudioSource(sourceDesc);
6164 
6165     audio_attributes_t attributes = sourceDesc->attributes();
6166     // May the device (dynamic) have been disconnected/reconnected, id has changed.
6167     sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6168                 sourceDesc->srcDevice()->type(),
6169                 String8(sourceDesc->srcDevice()->address().c_str()),
6170                 AUDIO_FORMAT_DEFAULT);
6171     DeviceVector sinkDevices =
6172             mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
6173     ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
6174     sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
6175     if (!mAvailableOutputDevices.contains(sinkDevice)) {
6176         ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6177         return INVALID_OPERATION;
6178     }
6179     PatchBuilder patchBuilder;
6180     patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6181     audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
6182 
6183     return connectAudioSourceToSink(
6184                 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
6185 }
6186 
stopAudioSource(audio_port_handle_t portId)6187 status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
6188 {
6189     sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6190     ALOGV("%s port ID %d", __FUNCTION__, portId);
6191     if (sourceDesc == 0) {
6192         ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
6193         return BAD_VALUE;
6194     }
6195     status_t status = disconnectAudioSource(sourceDesc);
6196 
6197     mAudioSources.removeItem(portId);
6198     return status;
6199 }
6200 
setMasterMono(bool mono)6201 status_t AudioPolicyManager::setMasterMono(bool mono)
6202 {
6203     if (mMasterMono == mono) {
6204         return NO_ERROR;
6205     }
6206     mMasterMono = mono;
6207     // if enabling mono we close all offloaded devices, which will invalidate the
6208     // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6209     // for recreating the new AudioTrack as non-offloaded PCM.
6210     //
6211     // If disabling mono, we leave all tracks as is: we don't know which clients
6212     // and tracks are able to be recreated as offloaded. The next "song" should
6213     // play back offloaded.
6214     if (mMasterMono) {
6215         Vector<audio_io_handle_t> offloaded;
6216         for (size_t i = 0; i < mOutputs.size(); ++i) {
6217             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6218             if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6219                 offloaded.push(desc->mIoHandle);
6220             }
6221         }
6222         for (const auto& handle : offloaded) {
6223             closeOutput(handle);
6224         }
6225     }
6226     // update master mono for all remaining outputs
6227     for (size_t i = 0; i < mOutputs.size(); ++i) {
6228         updateMono(mOutputs.keyAt(i));
6229     }
6230     return NO_ERROR;
6231 }
6232 
getMasterMono(bool * mono)6233 status_t AudioPolicyManager::getMasterMono(bool *mono)
6234 {
6235     *mono = mMasterMono;
6236     return NO_ERROR;
6237 }
6238 
getStreamVolumeDB(audio_stream_type_t stream,int index,audio_devices_t device)6239 float AudioPolicyManager::getStreamVolumeDB(
6240         audio_stream_type_t stream, int index, audio_devices_t device)
6241 {
6242     return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6243                          {device}, /* adjustAttenuation= */false);
6244 }
6245 
getSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats,bool * surroundFormatsEnabled)6246 status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6247                                                 audio_format_t *surroundFormats,
6248                                                 bool *surroundFormatsEnabled)
6249 {
6250     if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6251             (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
6252         return BAD_VALUE;
6253     }
6254     ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6255             __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
6256 
6257     size_t formatsWritten = 0;
6258     size_t formatsMax = *numSurroundFormats;
6259 
6260     *numSurroundFormats = mConfig->getSurroundFormats().size();
6261     audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6262             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6263     for (const auto& format: mConfig->getSurroundFormats()) {
6264         if (formatsWritten < formatsMax) {
6265             surroundFormats[formatsWritten] = format.first;
6266             bool formatEnabled = true;
6267             switch (forceUse) {
6268                 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
6269                     formatEnabled = mManualSurroundFormats.count(format.first) != 0;
6270                     break;
6271                 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6272                     formatEnabled = false;
6273                     break;
6274                 default: // AUTO or ALWAYS => true
6275                     break;
6276             }
6277             surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6278         }
6279     }
6280     return NO_ERROR;
6281 }
6282 
getReportedSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats)6283 status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6284                                                         audio_format_t *surroundFormats) {
6285     if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6286         return BAD_VALUE;
6287     }
6288     ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6289             __func__, *numSurroundFormats, surroundFormats);
6290 
6291     size_t formatsWritten = 0;
6292     size_t formatsMax = *numSurroundFormats;
6293     std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6294 
6295     // Return formats from all device profiles that have already been resolved by
6296     // checkOutputsForDevice().
6297     for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6298         sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6299         audio_devices_t deviceType = device->type();
6300         // Enabling/disabling formats are applied to only HDMI devices. So, this function
6301         // returns formats reported by HDMI devices.
6302         if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6303             deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
6304             continue;
6305         }
6306         // Formats reported by sink devices
6307         std::unordered_set<audio_format_t> formatset;
6308         if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6309             formatset.insert(it->second.begin(), it->second.end());
6310         }
6311 
6312         // Formats hard-coded in the in policy configuration file (if any).
6313         FormatVector encodedFormats = device->encodedFormats();
6314         formatset.insert(encodedFormats.begin(), encodedFormats.end());
6315         // Filter the formats which are supported by the vendor hardware.
6316         for (auto it = formatset.begin(); it != formatset.end(); ++it) {
6317             if (mConfig->getSurroundFormats().count(*it) != 0) {
6318                 formats.insert(*it);
6319             } else {
6320                 for (const auto& pair : mConfig->getSurroundFormats()) {
6321                     if (pair.second.count(*it) != 0) {
6322                         formats.insert(pair.first);
6323                         break;
6324                     }
6325                 }
6326             }
6327         }
6328     }
6329     *numSurroundFormats = formats.size();
6330     for (const auto& format: formats) {
6331         if (formatsWritten < formatsMax) {
6332             surroundFormats[formatsWritten++] = format;
6333         }
6334     }
6335     return NO_ERROR;
6336 }
6337 
setSurroundFormatEnabled(audio_format_t audioFormat,bool enabled)6338 status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6339 {
6340     ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
6341     const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6342     if (formatIter == mConfig->getSurroundFormats().end()) {
6343         ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
6344         return BAD_VALUE;
6345     }
6346 
6347     if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6348             AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
6349         ALOGW("%s() not in manual mode for surround sound format selection", __func__);
6350         return INVALID_OPERATION;
6351     }
6352 
6353     if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
6354         return NO_ERROR;
6355     }
6356 
6357     std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
6358     if (enabled) {
6359         mManualSurroundFormats.insert(audioFormat);
6360         for (const auto& subFormat : formatIter->second) {
6361             mManualSurroundFormats.insert(subFormat);
6362         }
6363     } else {
6364         mManualSurroundFormats.erase(audioFormat);
6365         for (const auto& subFormat : formatIter->second) {
6366             mManualSurroundFormats.erase(subFormat);
6367         }
6368     }
6369 
6370     sp<SwAudioOutputDescriptor> outputDesc;
6371     bool profileUpdated = false;
6372     DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6373         {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
6374     for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6375         // Simulate reconnection to update enabled surround sound formats.
6376         String8 address = String8(hdmiOutputDevices[i]->address().c_str());
6377         std::string name = hdmiOutputDevices[i]->getName();
6378         status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
6379                                                       AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6380                                                       address.c_str(),
6381                                                       name.c_str(),
6382                                                       AUDIO_FORMAT_DEFAULT);
6383         if (status != NO_ERROR) {
6384             continue;
6385         }
6386         status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
6387                                              AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6388                                              address.c_str(),
6389                                              name.c_str(),
6390                                              AUDIO_FORMAT_DEFAULT);
6391         profileUpdated |= (status == NO_ERROR);
6392     }
6393     // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
6394     DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
6395                 AUDIO_DEVICE_IN_HDMI);
6396     for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6397         // Simulate reconnection to update enabled surround sound formats.
6398         String8 address = String8(hdmiInputDevices[i]->address().c_str());
6399         std::string name = hdmiInputDevices[i]->getName();
6400         status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6401                                                       AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6402                                                       address.c_str(),
6403                                                       name.c_str(),
6404                                                       AUDIO_FORMAT_DEFAULT);
6405         if (status != NO_ERROR) {
6406             continue;
6407         }
6408         status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6409                                              AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6410                                              address.c_str(),
6411                                              name.c_str(),
6412                                              AUDIO_FORMAT_DEFAULT);
6413         profileUpdated |= (status == NO_ERROR);
6414     }
6415 
6416     if (!profileUpdated) {
6417         ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
6418         mManualSurroundFormats = std::move(surroundFormatsBackup);
6419     }
6420 
6421     return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6422 }
6423 
setAppState(audio_port_handle_t portId,app_state_t state)6424 void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
6425 {
6426     ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
6427     for (size_t i = 0; i < mInputs.size(); i++) {
6428         mInputs.valueAt(i)->setAppState(portId, state);
6429     }
6430 }
6431 
isHapticPlaybackSupported()6432 bool AudioPolicyManager::isHapticPlaybackSupported()
6433 {
6434     for (const auto& hwModule : mHwModules) {
6435         const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6436         for (const auto &outProfile : outputProfiles) {
6437             struct audio_port audioPort;
6438             outProfile->toAudioPort(&audioPort);
6439             for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6440                 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6441                     return true;
6442                 }
6443             }
6444         }
6445     }
6446     return false;
6447 }
6448 
isUltrasoundSupported()6449 bool AudioPolicyManager::isUltrasoundSupported()
6450 {
6451     bool hasUltrasoundOutput = false;
6452     bool hasUltrasoundInput = false;
6453     for (const auto& hwModule : mHwModules) {
6454         const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6455         if (!hasUltrasoundOutput) {
6456             for (const auto &outProfile : outputProfiles) {
6457                 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6458                     hasUltrasoundOutput = true;
6459                     break;
6460                 }
6461             }
6462         }
6463 
6464         const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6465         if (!hasUltrasoundInput) {
6466             for (const auto &inputProfile : inputProfiles) {
6467                 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6468                     hasUltrasoundInput = true;
6469                     break;
6470                 }
6471             }
6472         }
6473 
6474         if (hasUltrasoundOutput && hasUltrasoundInput)
6475             return true;
6476     }
6477     return false;
6478 }
6479 
isHotwordStreamSupported(bool lookbackAudio)6480 bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6481 {
6482     const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6483         (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6484     for (const auto& hwModule : mHwModules) {
6485         const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6486         for (const auto &inputProfile : inputProfiles) {
6487             if ((inputProfile->getFlags() & mask) == mask) {
6488                 return true;
6489             }
6490         }
6491     }
6492     return false;
6493 }
6494 
isCallScreenModeSupported()6495 bool AudioPolicyManager::isCallScreenModeSupported()
6496 {
6497     return mConfig->isCallScreenModeSupported();
6498 }
6499 
6500 
disconnectAudioSource(const sp<SourceClientDescriptor> & sourceDesc)6501 status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
6502 {
6503     ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
6504     if (!sourceDesc->isConnected()) {
6505         ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6506         return NO_ERROR;
6507     }
6508     sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6509     if (swOutput != 0) {
6510         status_t status = stopSource(swOutput, sourceDesc);
6511         if (status == NO_ERROR) {
6512             swOutput->stop();
6513         }
6514         if (releaseOutput(sourceDesc->portId())) {
6515             // The output descriptor is reopened to query dynamic profiles. In that case, there is
6516             // no need to release audio patch here but just return NO_ERROR.
6517             return NO_ERROR;
6518         }
6519     } else {
6520         sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
6521         if (hwOutputDesc != 0) {
6522           //   close Hwoutput and remove from mHwOutputs
6523         } else {
6524             ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6525         }
6526     }
6527     status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
6528     sourceDesc->disconnect();
6529     return status;
6530 }
6531 
getSourceForAttributesOnOutput(audio_io_handle_t output,const audio_attributes_t & attr)6532 sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6533         audio_io_handle_t output, const audio_attributes_t &attr)
6534 {
6535     sp<SourceClientDescriptor> source;
6536     for (size_t i = 0; i < mAudioSources.size(); i++)  {
6537         sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6538         sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
6539         if (followsSameRouting(attr, sourceDesc->attributes()) &&
6540                                outputDesc != 0 && outputDesc->mIoHandle == output) {
6541             source = sourceDesc;
6542             break;
6543         }
6544     }
6545     return source;
6546 }
6547 
canBeSpatializedInt(const audio_attributes_t * attr,const audio_config_t * config,const AudioDeviceTypeAddrVector & devices) const6548 bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
6549                                       const audio_config_t *config,
6550                                       const AudioDeviceTypeAddrVector &devices)  const
6551 {
6552     // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6553     // the AUDIO_ATTRIBUTES_INITIALIZER value.
6554     // If attributes are specified, current policy is to only allow spatialization for media
6555     // and game usages.
6556     if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6557         if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6558             return false;
6559         }
6560         if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6561             return false;
6562         }
6563     }
6564 
6565     // The caller can have the audio config criteria ignored by either passing a null ptr or
6566     // the AUDIO_CONFIG_INITIALIZER value.
6567     // If an audio config is specified, current policy is to only allow spatialization for
6568     // some positional channel masks and PCM format and for stereo if low latency performance
6569     // mode is not requested.
6570 
6571     if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
6572         const bool channel_mask_spatialized =
6573                 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6574                         ? audio_channel_mask_contains_stereo(config->channel_mask)
6575                         : audio_is_channel_mask_spatialized(config->channel_mask);
6576         if (!channel_mask_spatialized) {
6577             return false;
6578         }
6579         if (!audio_is_linear_pcm(config->format)) {
6580             return false;
6581         }
6582         if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6583                 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6584             return false;
6585         }
6586     }
6587 
6588     sp<IOProfile> profile =
6589             getSpatializerOutputProfile(config, devices);
6590     if (profile == nullptr) {
6591         return false;
6592     }
6593 
6594     return true;
6595 }
6596 
6597 // The Spatializer output is compatible with Haptic use cases if:
6598 // 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6599 // with client if client haptic channel bits were set, or
6600 // 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6601 // including the haptic bits or creating the HapticGenerator effect for same session.
checkHapticCompatibilityOnSpatializerOutput(const audio_config_t * config,audio_session_t sessionId) const6602 bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6603         const audio_config_t* config, audio_session_t sessionId) const {
6604     const auto clientHapticChannel =
6605             audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6606     const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6607             mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6608 
6609     if (threadOutputHapticChannel) {
6610         // check format and sampleRate match if client haptic channel mask exist
6611         if (clientHapticChannel) {
6612             return mSpatializerOutput->getFormat() == config->format &&
6613                    mSpatializerOutput->getSamplingRate() == config->sample_rate;
6614         }
6615         return true;
6616     } else {
6617         // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6618         // means haptic use cases (either the client channelmask includes haptic bits, or created a
6619         // HapticGenerator effect for this session) are not supported.
6620         return clientHapticChannel == 0 &&
6621                !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
6622     }
6623 }
6624 
checkVirtualizerClientRoutes()6625 void AudioPolicyManager::checkVirtualizerClientRoutes() {
6626     std::set<audio_stream_type_t> streamsToInvalidate;
6627     for (size_t i = 0; i < mOutputs.size(); i++) {
6628         const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6629         for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6630             audio_attributes_t attr = client->attributes();
6631             DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6632             AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6633             audio_config_base_t clientConfig = client->config();
6634             audio_config_t config = audio_config_initializer(&clientConfig);
6635             if (desc != mSpatializerOutput
6636                     && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
6637                 streamsToInvalidate.insert(client->stream());
6638             }
6639         }
6640     }
6641 
6642     invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
6643 }
6644 
6645 
isOutputOnlyAvailableRouteToSomeDevice(const sp<SwAudioOutputDescriptor> & outputDesc)6646 bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6647         const sp<SwAudioOutputDescriptor>& outputDesc) {
6648     if (outputDesc->isDuplicated()) {
6649         return false;
6650     }
6651     DeviceVector devices = outputDesc->supportedDevices();
6652     for (size_t i = 0; i < mOutputs.size(); i++) {
6653         sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6654         if (desc == outputDesc || desc->isDuplicated()) {
6655             continue;
6656         }
6657         DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6658         if (!sharedDevices.isEmpty()
6659                 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6660                     == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6661             return false;
6662         }
6663     }
6664     return true;
6665 }
6666 
6667 
getSpatializerOutput(const audio_config_base_t * mixerConfig,const audio_attributes_t * attr,audio_io_handle_t * output)6668 status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
6669                                                         const audio_attributes_t *attr,
6670                                                         audio_io_handle_t *output) {
6671     *output = AUDIO_IO_HANDLE_NONE;
6672 
6673     DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6674     AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6675     audio_config_t *configPtr = nullptr;
6676     audio_config_t config;
6677     if (mixerConfig != nullptr) {
6678         config = audio_config_initializer(mixerConfig);
6679         configPtr = &config;
6680     }
6681     if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
6682         ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
6683         return BAD_VALUE;
6684     }
6685 
6686     sp<IOProfile> profile =
6687             getSpatializerOutputProfile(configPtr, devicesTypeAddress);
6688     if (profile == nullptr) {
6689         ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
6690         return BAD_VALUE;
6691     }
6692 
6693     std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
6694     for (size_t i = 0; i < mOutputs.size(); i++) {
6695         sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6696         if (!desc->isDuplicated()
6697                 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6698             spatializerOutputs.push_back(desc);
6699             ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
6700         }
6701     }
6702     mSpatializerOutput.clear();
6703     bool outputsChanged = false;
6704     for (const auto& desc : spatializerOutputs) {
6705         if (desc->mProfile == profile
6706                 && (configPtr == nullptr
6707                    || configPtr->channel_mask == desc->mMixerChannelMask)) {
6708             mSpatializerOutput = desc;
6709             ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6710         } else {
6711             ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6712                     " and devices %s", __func__, desc->mIoHandle,
6713                     configPtr != nullptr ? configPtr->channel_mask : 0,
6714                     devices.toString().c_str());
6715             closeOutput(desc->mIoHandle);
6716             outputsChanged = true;
6717         }
6718     }
6719 
6720     if (mSpatializerOutput == nullptr) {
6721         sp<SwAudioOutputDescriptor> desc =
6722                 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
6723         if (desc != nullptr) {
6724             mSpatializerOutput = desc;
6725             outputsChanged = true;
6726         }
6727     }
6728 
6729     checkVirtualizerClientRoutes();
6730 
6731     if (outputsChanged) {
6732         mPreviousOutputs = mOutputs;
6733         mpClientInterface->onAudioPortListUpdate();
6734     }
6735 
6736     if (mSpatializerOutput == nullptr) {
6737         ALOGV("%s could not open spatializer output with requested config", __func__);
6738         return BAD_VALUE;
6739     }
6740     *output = mSpatializerOutput->mIoHandle;
6741     ALOGV("%s returning new spatializer output %d", __func__, *output);
6742     return OK;
6743 }
6744 
releaseSpatializerOutput(audio_io_handle_t output)6745 status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6746     if (mSpatializerOutput == nullptr) {
6747         return INVALID_OPERATION;
6748     }
6749     if (mSpatializerOutput->mIoHandle != output) {
6750         return BAD_VALUE;
6751     }
6752 
6753     if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6754         ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6755         closeOutput(mSpatializerOutput->mIoHandle);
6756         //from now on mSpatializerOutput is null
6757         checkVirtualizerClientRoutes();
6758     }
6759 
6760     return NO_ERROR;
6761 }
6762 
6763 // ----------------------------------------------------------------------------
6764 // AudioPolicyManager
6765 // ----------------------------------------------------------------------------
nextAudioPortGeneration()6766 uint32_t AudioPolicyManager::nextAudioPortGeneration()
6767 {
6768     return mAudioPortGeneration++;
6769 }
6770 
AudioPolicyManager(const sp<const AudioPolicyConfig> & config,EngineInstance && engine,AudioPolicyClientInterface * clientInterface)6771 AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
6772                                        EngineInstance&& engine,
6773                                        AudioPolicyClientInterface *clientInterface)
6774     :
6775     mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
6776     mConfig(config),
6777     mEngine(std::move(engine)),
6778     mpClientInterface(clientInterface),
6779     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
6780     mA2dpSuspended(false),
6781     mAudioPortGeneration(1),
6782     mBeaconMuteRefCount(0),
6783     mBeaconPlayingRefCount(0),
6784     mBeaconMuted(false),
6785     mTtsOutputAvailable(false),
6786     mMasterMono(false),
6787     mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
6788 {
6789 }
6790 
initialize()6791 status_t AudioPolicyManager::initialize() {
6792     if (mEngine == nullptr) {
6793         return NO_INIT;
6794     }
6795     mEngine->setObserver(this);
6796     status_t status = mEngine->initCheck();
6797     if (status != NO_ERROR) {
6798         LOG_FATAL("Policy engine not initialized(err=%d)", status);
6799         return status;
6800     }
6801 
6802     // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6803     // at the end of this function.
6804     mEngine->initializeDeviceSelectionCache();
6805     mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6806         mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6807 
6808     // after parsing the config, mConfig contain all known devices;
6809     // open all output streams needed to access attached devices
6810     onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
6811 
6812     // make sure default device is reachable
6813     if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6814             defaultOutputDevice == nullptr ||
6815             !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6816         ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6817                  defaultOutputDevice->toString().c_str());
6818         status = NO_INIT;
6819     }
6820     ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
6821 
6822     // Silence ALOGV statements
6823     property_set("log.tag." LOG_TAG, "D");
6824 
6825     updateDevicesAndOutputs();
6826     return status;
6827 }
6828 
~AudioPolicyManager()6829 AudioPolicyManager::~AudioPolicyManager()
6830 {
6831    for (size_t i = 0; i < mOutputs.size(); i++) {
6832         mOutputs.valueAt(i)->close();
6833    }
6834    for (size_t i = 0; i < mInputs.size(); i++) {
6835         mInputs.valueAt(i)->close();
6836    }
6837    mAvailableOutputDevices.clear();
6838    mAvailableInputDevices.clear();
6839    mOutputs.clear();
6840    mInputs.clear();
6841    mHwModules.clear();
6842    mManualSurroundFormats.clear();
6843    mConfig.clear();
6844 }
6845 
initCheck()6846 status_t AudioPolicyManager::initCheck()
6847 {
6848     return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
6849 }
6850 
6851 // ---
6852 
onNewAudioModulesAvailable()6853 void AudioPolicyManager::onNewAudioModulesAvailable()
6854 {
6855     DeviceVector newDevices;
6856     onNewAudioModulesAvailableInt(&newDevices);
6857     if (!newDevices.empty()) {
6858         nextAudioPortGeneration();
6859         mpClientInterface->onAudioPortListUpdate();
6860     }
6861 }
6862 
onNewAudioModulesAvailableInt(DeviceVector * newDevices)6863 void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6864 {
6865     for (const auto& hwModule : mConfig->getHwModules()) {
6866         if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6867             continue;
6868         }
6869         if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6870             if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6871                     handle != AUDIO_MODULE_HANDLE_NONE) {
6872                 hwModule->setHandle(handle);
6873             } else {
6874                 ALOGW("could not load HW module %s", hwModule->getName());
6875                 continue;
6876             }
6877         }
6878         mHwModules.push_back(hwModule);
6879         // open all output streams needed to access attached devices.
6880         // direct outputs are closed immediately after checking the availability of attached devices
6881         // This also validates mAvailableOutputDevices list
6882         for (const auto& outProfile : hwModule->getOutputProfiles()) {
6883             if (!outProfile->canOpenNewIo()) {
6884                 ALOGE("Invalid Output profile max open count %u for profile %s",
6885                       outProfile->maxOpenCount, outProfile->getTagName().c_str());
6886                 continue;
6887             }
6888             if (!outProfile->hasSupportedDevices()) {
6889                 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6890                 continue;
6891             }
6892             if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6893                 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
6894                 mTtsOutputAvailable = true;
6895             }
6896 
6897             const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6898             DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
6899             sp<DeviceDescriptor> supportedDevice = 0;
6900             if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6901                 supportedDevice = mConfig->getDefaultOutputDevice();
6902             } else {
6903                 // choose first device present in profile's SupportedDevices also part of
6904                 // mAvailableOutputDevices.
6905                 if (availProfileDevices.isEmpty()) {
6906                     continue;
6907                 }
6908                 supportedDevice = availProfileDevices.itemAt(0);
6909             }
6910             if (!mConfig->getOutputDevices().contains(supportedDevice)) {
6911                 continue;
6912             }
6913 
6914             if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6915                 && availProfileDevices.areAllDevicesAttached()) {
6916                 ALOGV("%s skip opening output for mmap profile %s", __func__,
6917                         outProfile->getTagName().c_str());
6918                 continue;
6919             }
6920 
6921             sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6922                                                                                  mpClientInterface);
6923             audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6924             audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
6925             audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
6926             status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6927                                                DeviceVector(supportedDevice),
6928                                                AUDIO_STREAM_DEFAULT,
6929                                                &flags, &output, attributes);
6930             if (status != NO_ERROR) {
6931                 ALOGW("Cannot open output stream for devices %s on hw module %s",
6932                       supportedDevice->toString().c_str(), hwModule->getName());
6933                 continue;
6934             }
6935             for (const auto &device : availProfileDevices) {
6936                 // give a valid ID to an attached device once confirmed it is reachable
6937                 if (!device->isAttached()) {
6938                     device->attach(hwModule);
6939                     mAvailableOutputDevices.add(device);
6940                     device->setEncapsulationInfoFromHal(mpClientInterface);
6941                     if (newDevices) newDevices->add(device);
6942                     setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6943                 }
6944             }
6945             if (mPrimaryOutput == nullptr &&
6946                     outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6947                 mPrimaryOutput = outputDesc;
6948                 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
6949             }
6950             if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
6951                 outputDesc->close();
6952             } else {
6953                 addOutput(output, outputDesc);
6954                 setOutputDevices(__func__, outputDesc,
6955                                  DeviceVector(supportedDevice),
6956                                  true,
6957                                  0,
6958                                  NULL);
6959             }
6960         }
6961         // open input streams needed to access attached devices to validate
6962         // mAvailableInputDevices list
6963         for (const auto& inProfile : hwModule->getInputProfiles()) {
6964             if (!inProfile->canOpenNewIo()) {
6965                 ALOGE("Invalid Input profile max open count %u for profile %s",
6966                       inProfile->maxOpenCount, inProfile->getTagName().c_str());
6967                 continue;
6968             }
6969             if (!inProfile->hasSupportedDevices()) {
6970                 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6971                 continue;
6972             }
6973             // chose first device present in profile's SupportedDevices also part of
6974             // available input devices
6975             const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6976             DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
6977             if (availProfileDevices.isEmpty()) {
6978                 ALOGV("%s: Input device list is empty! for profile %s",
6979                     __func__, inProfile->getTagName().c_str());
6980                 continue;
6981             }
6982 
6983             if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6984                 && availProfileDevices.areAllDevicesAttached()) {
6985                 ALOGV("%s skip opening input for mmap profile %s", __func__,
6986                         inProfile->getTagName().c_str());
6987                 continue;
6988             }
6989 
6990             sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6991                     inProfile, mpClientInterface, false /*isPreemptor*/);
6992 
6993             audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6994             status_t status = inputDesc->open(nullptr,
6995                                               availProfileDevices.itemAt(0),
6996                                               AUDIO_SOURCE_MIC,
6997                                               (audio_input_flags_t) inProfile->getFlags(),
6998                                               &input);
6999             if (status != NO_ERROR) {
7000                 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
7001                         __func__, availProfileDevices.toString().c_str(),
7002                         inProfile->getTagName().c_str(), hwModule->getName());
7003                 continue;
7004             }
7005             for (const auto &device : availProfileDevices) {
7006                 // give a valid ID to an attached device once confirmed it is reachable
7007                 if (!device->isAttached()) {
7008                     device->attach(hwModule);
7009                     device->importAudioPortAndPickAudioProfile(inProfile, true);
7010                     mAvailableInputDevices.add(device);
7011                     if (newDevices) newDevices->add(device);
7012                     setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
7013                 }
7014             }
7015             inputDesc->close();
7016         }
7017     }
7018 
7019     // Check if spatializer outputs can be closed until used.
7020     // mOutputs vector never contains duplicated outputs at this point.
7021     std::vector<audio_io_handle_t> outputsClosed;
7022     for (size_t i = 0; i < mOutputs.size(); i++) {
7023         sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
7024         if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
7025                 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
7026             outputsClosed.push_back(desc->mIoHandle);
7027             nextAudioPortGeneration();
7028             ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
7029             if (index >= 0) {
7030                 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7031                 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7032                             patchDesc->getAfHandle(), 0);
7033                 mAudioPatches.removeItemsAt(index);
7034                 mpClientInterface->onAudioPatchListUpdate();
7035             }
7036             desc->close();
7037         }
7038     }
7039     for (auto output : outputsClosed) {
7040         removeOutput(output);
7041     }
7042 }
7043 
addOutput(audio_io_handle_t output,const sp<SwAudioOutputDescriptor> & outputDesc)7044 void AudioPolicyManager::addOutput(audio_io_handle_t output,
7045                                    const sp<SwAudioOutputDescriptor>& outputDesc)
7046 {
7047     mOutputs.add(output, outputDesc);
7048     applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
7049     updateMono(output); // update mono status when adding to output list
7050     selectOutputForMusicEffects();
7051     nextAudioPortGeneration();
7052 }
7053 
removeOutput(audio_io_handle_t output)7054 void AudioPolicyManager::removeOutput(audio_io_handle_t output)
7055 {
7056     if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
7057         ALOGV("%s: removing primary output", __func__);
7058         mPrimaryOutput = nullptr;
7059     }
7060     mOutputs.removeItem(output);
7061     selectOutputForMusicEffects();
7062 }
7063 
addInput(audio_io_handle_t input,const sp<AudioInputDescriptor> & inputDesc)7064 void AudioPolicyManager::addInput(audio_io_handle_t input,
7065                                   const sp<AudioInputDescriptor>& inputDesc)
7066 {
7067     mInputs.add(input, inputDesc);
7068     nextAudioPortGeneration();
7069 }
7070 
checkOutputsForDevice(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state,SortedVector<audio_io_handle_t> & outputs)7071 status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
7072                                                    audio_policy_dev_state_t state,
7073                                                    SortedVector<audio_io_handle_t>& outputs)
7074 {
7075     audio_devices_t deviceType = device->type();
7076     const String8 &address = String8(device->address().c_str());
7077     sp<SwAudioOutputDescriptor> desc;
7078 
7079     if (audio_device_is_digital(deviceType)) {
7080         // erase all current sample rates, formats and channel masks
7081         device->clearAudioProfiles();
7082     }
7083 
7084     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
7085         // first call getAudioPort to get the supported attributes from the HAL
7086         struct audio_port_v7 port = {};
7087         device->toAudioPort(&port);
7088         status_t status = mpClientInterface->getAudioPort(&port);
7089         if (status == NO_ERROR) {
7090             device->importAudioPort(port);
7091         }
7092 
7093         // then list already open outputs that can be routed to this device
7094         for (size_t i = 0; i < mOutputs.size(); i++) {
7095             desc = mOutputs.valueAt(i);
7096             if (!desc->isDuplicated() && desc->supportsDevice(device)
7097                     && desc->devicesSupportEncodedFormats({deviceType})) {
7098                 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
7099                       mOutputs.keyAt(i), device->toString().c_str());
7100                 outputs.add(mOutputs.keyAt(i));
7101             }
7102         }
7103         // then look for output profiles that can be routed to this device
7104         SortedVector< sp<IOProfile> > profiles;
7105         for (const auto& hwModule : mHwModules) {
7106             for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7107                 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
7108                 if (profile->supportsDevice(device)) {
7109                     profiles.add(profile);
7110                     ALOGV("%s(): adding profile %s from module %s",
7111                             __func__, profile->getTagName().c_str(), hwModule->getName());
7112                 }
7113             }
7114         }
7115 
7116         ALOGV("  found %zu profiles, %zu outputs", profiles.size(), outputs.size());
7117 
7118         if (profiles.isEmpty() && outputs.isEmpty()) {
7119             ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
7120             return BAD_VALUE;
7121         }
7122 
7123         // open outputs for matching profiles if needed. Direct outputs are also opened to
7124         // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7125         for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7126             sp<IOProfile> profile = profiles[profile_index];
7127 
7128             // nothing to do if one output is already opened for this profile
7129             size_t j;
7130             for (j = 0; j < outputs.size(); j++) {
7131                 desc = mOutputs.valueFor(outputs.itemAt(j));
7132                 if (!desc->isDuplicated() && desc->mProfile == profile) {
7133                     // matching profile: save the sample rates, format and channel masks supported
7134                     // by the profile in our device descriptor
7135                     if (audio_device_is_digital(deviceType)) {
7136                         device->importAudioPortAndPickAudioProfile(profile);
7137                     }
7138                     break;
7139                 }
7140             }
7141             if (j != outputs.size()) {
7142                 continue;
7143             }
7144             if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7145                 ALOGV("%s skip opening output for mmap profile %s",
7146                       __func__, profile->getTagName().c_str());
7147                 continue;
7148             }
7149             if (!profile->canOpenNewIo()) {
7150                 ALOGW("Max Output number %u already opened for this profile %s",
7151                       profile->maxOpenCount, profile->getTagName().c_str());
7152                 continue;
7153             }
7154 
7155             ALOGV("opening output for device %08x with params %s profile %p name %s",
7156                   deviceType, address.c_str(), profile.get(), profile->getName().c_str());
7157             desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7158             audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
7159             if (output == AUDIO_IO_HANDLE_NONE) {
7160                 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
7161                 profiles.removeAt(profile_index);
7162                 profile_index--;
7163             } else {
7164                 outputs.add(output);
7165                 // Load digital format info only for digital devices
7166                 if (audio_device_is_digital(deviceType)) {
7167                     // TODO: when getAudioPort is ready, it may not be needed to import the audio
7168                     // port but just pick audio profile
7169                     device->importAudioPortAndPickAudioProfile(profile);
7170                 }
7171 
7172                 if (device_distinguishes_on_address(deviceType)) {
7173                     ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7174                             device->toString().c_str());
7175                     setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7176                                       0/*delay*/, NULL/*patch handle*/);
7177                 }
7178                 ALOGV("checkOutputsForDevice(): adding output %d", output);
7179             }
7180         }
7181 
7182         if (profiles.isEmpty()) {
7183             ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
7184             return BAD_VALUE;
7185         }
7186     } else { // Disconnect
7187         // check if one opened output is not needed any more after disconnecting one device
7188         for (size_t i = 0; i < mOutputs.size(); i++) {
7189             desc = mOutputs.valueAt(i);
7190             if (!desc->isDuplicated()) {
7191                 // exact match on device
7192                 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
7193                         && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
7194                     outputs.add(mOutputs.keyAt(i));
7195                 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
7196                     ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7197                             mOutputs.keyAt(i));
7198                     outputs.add(mOutputs.keyAt(i));
7199                 }
7200             }
7201         }
7202         // Clear any profiles associated with the disconnected device.
7203         for (const auto& hwModule : mHwModules) {
7204             for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7205                 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
7206                 if (!profile->supportsDevice(device)) {
7207                     continue;
7208                 }
7209                 ALOGV("%s(): clearing direct output profile %s on module %s",
7210                         __func__, profile->getTagName().c_str(), hwModule->getName());
7211                 profile->clearAudioProfiles();
7212                 if (!profile->hasDynamicAudioProfile()) {
7213                     continue;
7214                 }
7215                 // When a device is disconnected, if there is an IOProfile that contains dynamic
7216                 // profiles and supports the disconnected device, call getAudioPort to repopulate
7217                 // the capabilities of the devices that is supported by the IOProfile.
7218                 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7219                     if (supportedDevice == device ||
7220                             !mAvailableOutputDevices.contains(supportedDevice)) {
7221                         continue;
7222                     }
7223                     struct audio_port_v7 port;
7224                     supportedDevice->toAudioPort(&port);
7225                     status_t status = mpClientInterface->getAudioPort(&port);
7226                     if (status == NO_ERROR) {
7227                         supportedDevice->importAudioPort(port);
7228                     }
7229                 }
7230             }
7231         }
7232     }
7233     return NO_ERROR;
7234 }
7235 
checkInputsForDevice(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state)7236 status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
7237                                                   audio_policy_dev_state_t state)
7238 {
7239     if (audio_device_is_digital(device->type())) {
7240         // erase all current sample rates, formats and channel masks
7241         device->clearAudioProfiles();
7242     }
7243 
7244     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
7245         sp<AudioInputDescriptor> desc;
7246 
7247         // first call getAudioPort to get the supported attributes from the HAL
7248         struct audio_port_v7 port = {};
7249         device->toAudioPort(&port);
7250         status_t status = mpClientInterface->getAudioPort(&port);
7251         if (status == NO_ERROR) {
7252             device->importAudioPort(port);
7253         }
7254 
7255         // look for input profiles that can be routed to this device
7256         SortedVector< sp<IOProfile> > profiles;
7257         for (const auto& hwModule : mHwModules) {
7258             for (size_t profile_index = 0;
7259                  profile_index < hwModule->getInputProfiles().size();
7260                  profile_index++) {
7261                 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
7262 
7263                 if (profile->supportsDevice(device)) {
7264                     profiles.add(profile);
7265                     ALOGV("%s : adding profile %s from module %s", __func__,
7266                           profile->getTagName().c_str(), hwModule->getName());
7267                 }
7268             }
7269         }
7270 
7271         if (profiles.isEmpty()) {
7272             ALOGW("%s: No input profile available for device %s",
7273                 __func__, device->toString().c_str());
7274             return BAD_VALUE;
7275         }
7276 
7277         // open inputs for matching profiles if needed. Direct inputs are also opened to
7278         // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7279         for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7280 
7281             sp<IOProfile> profile = profiles[profile_index];
7282 
7283             // nothing to do if one input is already opened for this profile
7284             size_t input_index;
7285             for (input_index = 0; input_index < mInputs.size(); input_index++) {
7286                 desc = mInputs.valueAt(input_index);
7287                 if (desc->mProfile == profile) {
7288                     if (audio_device_is_digital(device->type())) {
7289                         device->importAudioPortAndPickAudioProfile(profile);
7290                     }
7291                     break;
7292                 }
7293             }
7294             if (input_index != mInputs.size()) {
7295                 continue;
7296             }
7297 
7298             if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7299                 ALOGV("%s skip opening input for mmap profile %s",
7300                       __func__, profile->getTagName().c_str());
7301                 continue;
7302             }
7303             if (!profile->canOpenNewIo()) {
7304                 ALOGW("%s Max Input number %u already opened for this profile %s",
7305                       __func__, profile->maxOpenCount, profile->getTagName().c_str());
7306                 continue;
7307             }
7308 
7309             desc = new AudioInputDescriptor(profile, mpClientInterface, false  /*isPreemptor*/);
7310             audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
7311             ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
7312             status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7313                                 (audio_input_flags_t) profile->getFlags(), &input);
7314 
7315             if (status == NO_ERROR) {
7316                 const String8& address = String8(device->address().c_str());
7317                 if (!address.empty()) {
7318                     char *param = audio_device_address_to_parameter(device->type(), address);
7319                     mpClientInterface->setParameters(input, String8(param));
7320                     free(param);
7321                 }
7322                 updateAudioProfiles(device, input, profile);
7323                 if (!profile->hasValidAudioProfile()) {
7324                     ALOGW("%s direct input missing param for profile %s", __func__,
7325                             profile->getTagName().c_str());
7326                     desc->close();
7327                     input = AUDIO_IO_HANDLE_NONE;
7328                 }
7329 
7330                 if (input != AUDIO_IO_HANDLE_NONE) {
7331                     addInput(input, desc);
7332                 }
7333             } // endif input != 0
7334 
7335             if (input == AUDIO_IO_HANDLE_NONE) {
7336                 ALOGW("%s could not open input for device %s on profile %s", __func__,
7337                        device->toString().c_str(), profile->getTagName().c_str());
7338                 profiles.removeAt(profile_index);
7339                 profile_index--;
7340             } else {
7341                 if (audio_device_is_digital(device->type())) {
7342                     device->importAudioPortAndPickAudioProfile(profile);
7343                 }
7344                 ALOGV("%s: adding input %d for profile %s", __func__,
7345                         input, profile->getTagName().c_str());
7346 
7347                 if (checkCloseInput(desc)) {
7348                     ALOGV("%s: closing input %d for profile %s", __func__,
7349                             input, profile->getTagName().c_str());
7350                     closeInput(input);
7351                 }
7352             }
7353         } // end scan profiles
7354 
7355         if (profiles.isEmpty()) {
7356             ALOGW("%s: No input available for device %s", __func__,  device->toString().c_str());
7357             return BAD_VALUE;
7358         }
7359     } else {
7360         // Disconnect
7361         // Clear any profiles associated with the disconnected device.
7362         for (const auto& hwModule : mHwModules) {
7363             for (size_t profile_index = 0;
7364                  profile_index < hwModule->getInputProfiles().size();
7365                  profile_index++) {
7366                 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
7367                 if (profile->supportsDevice(device)) {
7368                     ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7369                             profile->getTagName().c_str(), hwModule->getName());
7370                     profile->clearAudioProfiles();
7371                 }
7372             }
7373         }
7374     } // end disconnect
7375 
7376     return NO_ERROR;
7377 }
7378 
7379 
closeOutput(audio_io_handle_t output)7380 void AudioPolicyManager::closeOutput(audio_io_handle_t output)
7381 {
7382     ALOGV("closeOutput(%d)", output);
7383 
7384     sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7385     if (closingOutput == NULL) {
7386         ALOGW("closeOutput() unknown output %d", output);
7387         return;
7388     }
7389     const bool closingOutputWasActive = closingOutput->isActive();
7390     mPolicyMixes.closeOutput(closingOutput, mOutputs);
7391 
7392     // look for duplicated outputs connected to the output being removed.
7393     for (size_t i = 0; i < mOutputs.size(); i++) {
7394         sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7395         if (dupOutput->isDuplicated() &&
7396                 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7397             sp<SwAudioOutputDescriptor> remainingOutput =
7398                 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
7399             // As all active tracks on duplicated output will be deleted,
7400             // and as they were also referenced on the other output, the reference
7401             // count for their stream type must be adjusted accordingly on
7402             // the other output.
7403             const bool wasActive = remainingOutput->isActive();
7404             // Note: no-op on the closing output where all clients has already been set inactive
7405             dupOutput->setAllClientsInactive();
7406             // stop() will be a no op if the output is still active but is needed in case all
7407             // active streams refcounts where cleared above
7408             if (wasActive) {
7409                 remainingOutput->stop();
7410             }
7411             audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7412             ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7413 
7414             mpClientInterface->closeOutput(duplicatedOutput);
7415             removeOutput(duplicatedOutput);
7416         }
7417     }
7418 
7419     nextAudioPortGeneration();
7420 
7421     ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
7422     if (index >= 0) {
7423         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7424         (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7425                     patchDesc->getAfHandle(), 0);
7426         mAudioPatches.removeItemsAt(index);
7427         mpClientInterface->onAudioPatchListUpdate();
7428     }
7429 
7430     if (closingOutputWasActive) {
7431         closingOutput->stop();
7432     }
7433     closingOutput->close();
7434     if (closingOutput->isBitPerfect()) {
7435         for (const auto device : closingOutput->devices()) {
7436             device->setPreferredConfig(nullptr);
7437         }
7438     }
7439 
7440     removeOutput(output);
7441     mPreviousOutputs = mOutputs;
7442     if (closingOutput == mSpatializerOutput) {
7443         mSpatializerOutput.clear();
7444     }
7445 
7446     // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7447     // no direct outputs are open.
7448     if (!getMsdAudioOutDevices().isEmpty()) {
7449         bool directOutputOpen = false;
7450         for (size_t i = 0; i < mOutputs.size(); i++) {
7451             if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7452                 directOutputOpen = true;
7453                 break;
7454             }
7455         }
7456         if (!directOutputOpen) {
7457             ALOGV("no direct outputs open, reset MSD patches");
7458             // TODO: The MSD patches to be established here may differ to current MSD patches due to
7459             // how output devices for patching are resolved. Avoid by caching and reusing the
7460             // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7461             // devices to patch to. This may be complicated by the fact that devices may become
7462             // unavailable.
7463             setMsdOutputPatches();
7464         }
7465     }
7466 
7467     if (closingOutput->mPreferredAttrInfo != nullptr) {
7468         closingOutput->mPreferredAttrInfo->resetActiveClient();
7469     }
7470 }
7471 
closeInput(audio_io_handle_t input)7472 void AudioPolicyManager::closeInput(audio_io_handle_t input)
7473 {
7474     ALOGV("closeInput(%d)", input);
7475 
7476     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7477     if (inputDesc == NULL) {
7478         ALOGW("closeInput() unknown input %d", input);
7479         return;
7480     }
7481 
7482     nextAudioPortGeneration();
7483 
7484     sp<DeviceDescriptor> device = inputDesc->getDevice();
7485     ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
7486     if (index >= 0) {
7487         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7488         (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7489                     patchDesc->getAfHandle(), 0);
7490         mAudioPatches.removeItemsAt(index);
7491         mpClientInterface->onAudioPatchListUpdate();
7492     }
7493 
7494     mEffects.putOrphanEffectsForIo(input);
7495     inputDesc->close();
7496     mInputs.removeItem(input);
7497 
7498     DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7499     if (primaryInputDevices.contains(device) &&
7500             mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
7501         mpClientInterface->setSoundTriggerCaptureState(false);
7502     }
7503 }
7504 
getOutputsForDevices(const DeviceVector & devices,const SwAudioOutputCollection & openOutputs)7505 SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7506             const DeviceVector &devices,
7507             const SwAudioOutputCollection& openOutputs)
7508 {
7509     SortedVector<audio_io_handle_t> outputs;
7510 
7511     ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
7512     for (size_t i = 0; i < openOutputs.size(); i++) {
7513         ALOGVV("output %zu isDuplicated=%d device=%s",
7514                 i, openOutputs.valueAt(i)->isDuplicated(),
7515                 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
7516         if (openOutputs.valueAt(i)->supportsAllDevices(devices)
7517                 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
7518             ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
7519             outputs.add(openOutputs.keyAt(i));
7520         }
7521     }
7522     return outputs;
7523 }
7524 
checkForDeviceAndOutputChanges(std::function<bool ()> onOutputsChecked)7525 void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7526 {
7527     // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7528     // output is suspended before any tracks are moved to it
7529     checkA2dpSuspend();
7530     checkOutputForAllStrategies();
7531     checkSecondaryOutputs();
7532     if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
7533     updateDevicesAndOutputs();
7534     if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
7535         // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7536         // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7537         // configuration changes will ultimately be rerouted correctly. We can still avoid
7538         // unnecessary rerouting by caching and reusing the arguments to
7539         // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7540         // This may be complicated by the fact that devices may become unavailable.
7541         setMsdOutputPatches();
7542     }
7543     // an event that changed routing likely occurred, inform upper layers
7544     mpClientInterface->onRoutingUpdated();
7545 }
7546 
followsSameRouting(const audio_attributes_t & lAttr,const audio_attributes_t & rAttr) const7547 bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7548                                             const audio_attributes_t &rAttr) const
7549 {
7550     return mEngine->getProductStrategyForAttributes(lAttr) ==
7551             mEngine->getProductStrategyForAttributes(rAttr);
7552 }
7553 
checkAudioSourceForAttributes(const audio_attributes_t & attr)7554 void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7555 {
7556     for (size_t i = 0; i < mAudioSources.size(); i++)  {
7557         sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7558         if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
7559                 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
7560                 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
7561             connectAudioSource(sourceDesc, 0 /*delayMs*/);
7562         }
7563     }
7564 }
7565 
clearAudioSourcesForOutput(audio_io_handle_t output)7566 void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7567 {
7568     for (size_t i = 0; i < mAudioSources.size(); i++)  {
7569         sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7570         if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7571                 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7572             disconnectAudioSource(sourceDesc);
7573         }
7574     }
7575 }
7576 
checkOutputForAttributes(const audio_attributes_t & attr)7577 void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7578 {
7579     auto psId = mEngine->getProductStrategyForAttributes(attr);
7580 
7581     DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7582     DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
7583 
7584     SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7585     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
7586 
7587     uint32_t maxLatency = 0;
7588     bool unneededUsePrimaryOutputFromPolicyMixes = false;
7589     std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
7590     // take into account dynamic audio policies related changes: if a client is now associated
7591     // to a different policy mix than at creation time, invalidate corresponding stream
7592     // invalidate clients on outputs that do not support all the newly selected devices for the
7593     // strategy
7594     for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
7595         const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7596         if (desc->isDuplicated() || desc->getClientCount() == 0) {
7597             continue;
7598         }
7599 
7600         for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7601             if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId
7602                     || client->isInvalid()) {
7603                 continue;
7604             }
7605             if (!desc->supportsAllDevices(newDevices)) {
7606                 invalidatedOutputs.push_back(desc);
7607                 break;
7608             }
7609             sp<AudioPolicyMix> primaryMix;
7610             status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
7611                     client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7612                     nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7613                     unneededUsePrimaryOutputFromPolicyMixes);
7614             if (status == OK) {
7615                 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7616                     if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7617                         maxLatency = desc->latency();
7618                     }
7619                     invalidatedOutputs.push_back(desc);
7620                     break;
7621                 }
7622             }
7623         }
7624     }
7625 
7626     if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
7627         // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7628         // audio from invalidated tracks will be rendered when unmuting
7629         for (audio_io_handle_t srcOut : srcOutputs) {
7630             sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
7631             if (desc == nullptr) continue;
7632             if (desc == mSpatializerOutput && newDevices == oldDevices) {
7633                 continue;
7634             }
7635 
7636             if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7637                 maxLatency = desc->latency();
7638             }
7639 
7640             bool invalidate = false;
7641             for (auto client : desc->clientsList(false /*activeOnly*/)) {
7642                 if (client->isInvalid()) {
7643                     continue;
7644                 }
7645                 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
7646                     // a client on a non direct outputs has necessarily a linear PCM format
7647                     // so we can call selectOutput() safely
7648                     const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7649                                                                      client->flags(),
7650                                                                      client->config().format,
7651                                                                      client->config().channel_mask,
7652                                                                      client->config().sample_rate,
7653                                                                      client->session());
7654                     if (newOutput != srcOut) {
7655                         invalidate = true;
7656                         break;
7657                     }
7658                 } else {
7659                     sp<IOProfile> profile = getProfileForOutput(newDevices,
7660                                    client->config().sample_rate,
7661                                    client->config().format,
7662                                    client->config().channel_mask,
7663                                    client->flags(),
7664                                    true /* directOnly */);
7665                     if (profile != desc->mProfile) {
7666                         invalidate = true;
7667                         break;
7668                     }
7669                 }
7670             }
7671             // mute strategy while moving tracks from one output to another
7672             if (invalidate) {
7673                 invalidatedOutputs.push_back(desc);
7674                 if (desc->isStrategyActive(psId)) {
7675                     setStrategyMute(psId, true, desc);
7676                     setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7677                                     newDevices.types());
7678                 }
7679             }
7680             sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
7681             if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
7682                 connectAudioSource(source, 0 /*delayMs*/);
7683             }
7684         }
7685 
7686         ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7687               "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7688               std::to_string(srcOutputs[0]).c_str(),
7689               std::to_string(dstOutputs[0]).c_str());
7690 
7691         // Move effects associated to this stream from previous output to new output
7692         if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
7693             selectOutputForMusicEffects();
7694         }
7695         // Move tracks associated to this stream (and linked) from previous output to new output
7696         if (!invalidatedOutputs.empty()) {
7697             invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
7698             for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
7699                 desc->setTracksInvalidatedStatusByStrategy(psId);
7700             }
7701         }
7702     }
7703 }
7704 
checkOutputForAllStrategies()7705 void AudioPolicyManager::checkOutputForAllStrategies()
7706 {
7707     for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7708         auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7709         checkOutputForAttributes(attributes);
7710         checkAudioSourceForAttributes(attributes);
7711     }
7712 }
7713 
checkSecondaryOutputs()7714 void AudioPolicyManager::checkSecondaryOutputs() {
7715     PortHandleVector clientsToInvalidate;
7716     TrackSecondaryOutputsMap trackSecondaryOutputs;
7717     bool unneededUsePrimaryOutputFromPolicyMixes = false;
7718     for (size_t i = 0; i < mOutputs.size(); i++) {
7719         const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7720         for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
7721             sp<AudioPolicyMix> primaryMix;
7722             std::vector<sp<AudioPolicyMix>> secondaryMixes;
7723             status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
7724                     client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7725                     nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7726                     unneededUsePrimaryOutputFromPolicyMixes);
7727             std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7728             for (auto &secondaryMix : secondaryMixes) {
7729                 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7730                 if (outputDesc != nullptr &&
7731                     outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE &&
7732                     outputDesc != outputDescriptor) {
7733                     secondaryDescs.push_back(outputDesc);
7734                 }
7735             }
7736 
7737             if (status != OK &&
7738                 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7739                 // When it failed to query secondary output, only invalidate the client that is not
7740                 // MMAP. The reason is that MMAP stream will not support secondary output.
7741                 clientsToInvalidate.push_back(client->portId());
7742             } else if (!std::equal(
7743                     client->getSecondaryOutputs().begin(),
7744                     client->getSecondaryOutputs().end(),
7745                     secondaryDescs.begin(), secondaryDescs.end())) {
7746                 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7747                         || !audio_is_linear_pcm(client->config().format)) {
7748                     // If the format is not PCM, the tracks should be invalidated to get correct
7749                     // behavior when the secondary output is changed.
7750                     clientsToInvalidate.push_back(client->portId());
7751                 } else {
7752                     std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7753                     std::vector<audio_io_handle_t> secondaryOutputIds;
7754                     for (const auto &secondaryDesc: secondaryDescs) {
7755                         secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7756                         weakSecondaryDescs.push_back(secondaryDesc);
7757                     }
7758                     trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7759                     client->setSecondaryOutputs(std::move(weakSecondaryDescs));
7760                 }
7761             }
7762         }
7763     }
7764     if (!trackSecondaryOutputs.empty()) {
7765         mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7766     }
7767     if (!clientsToInvalidate.empty()) {
7768         ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7769         mpClientInterface->invalidateTracks(clientsToInvalidate);
7770     }
7771 }
7772 
isScoRequestedForComm() const7773 bool AudioPolicyManager::isScoRequestedForComm() const {
7774     AudioDeviceTypeAddrVector devices;
7775     mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7776     for (const auto &device : devices) {
7777         if (audio_is_bluetooth_out_sco_device(device.mType)) {
7778             return true;
7779         }
7780     }
7781     return false;
7782 }
7783 
isHearingAidUsedForComm() const7784 bool AudioPolicyManager::isHearingAidUsedForComm() const {
7785     DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7786                                                        true /*fromCache*/);
7787     for (const auto &device : devices) {
7788         if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7789             return true;
7790         }
7791     }
7792     return false;
7793 }
7794 
7795 
checkA2dpSuspend()7796 void AudioPolicyManager::checkA2dpSuspend()
7797 {
7798     audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
7799     if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
7800         mA2dpSuspended = false;
7801         return;
7802     }
7803 
7804     bool isScoConnected =
7805             (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7806              !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
7807     bool isScoRequested = isScoRequestedForComm();
7808 
7809     // if suspended, restore A2DP output if:
7810     //      ((SCO device is NOT connected) ||
7811     //       ((SCO is not requested) &&
7812     //        (phone state is NOT in call) && (phone state is NOT ringing)))
7813     //
7814     // if not suspended, suspend A2DP output if:
7815     //      (SCO device is connected) &&
7816     //       ((SCO is requested) ||
7817     //       ((phone state is in call) || (phone state is ringing)))
7818     //
7819     if (mA2dpSuspended) {
7820         if (!isScoConnected ||
7821              (!isScoRequested &&
7822               (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
7823               (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
7824 
7825             mpClientInterface->restoreOutput(a2dpOutput);
7826             mA2dpSuspended = false;
7827         }
7828     } else {
7829         if (isScoConnected &&
7830              (isScoRequested ||
7831               (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
7832               (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
7833 
7834             mpClientInterface->suspendOutput(a2dpOutput);
7835             mA2dpSuspended = true;
7836         }
7837     }
7838 }
7839 
getNewOutputDevices(const sp<SwAudioOutputDescriptor> & outputDesc,bool fromCache)7840 DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7841                                                      bool fromCache)
7842 {
7843     if (outputDesc == nullptr) {
7844         return DeviceVector{};
7845     }
7846 
7847     ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
7848     if (index >= 0) {
7849         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7850         if (patchDesc->getUid() != mUidCached) {
7851             ALOGV("%s device %s forced by patch %d", __func__,
7852                   outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7853             return  outputDesc->devices();
7854         }
7855     }
7856 
7857     // Do not retrieve engine device for outputs through MSD
7858     // TODO: support explicit routing requests by resetting MSD patch to engine device.
7859     if (outputDesc->devices() == getMsdAudioOutDevices()) {
7860         return outputDesc->devices();
7861     }
7862 
7863     // Honor explicit routing requests only if no client using default routing is active on this
7864     // input: a specific app can not force routing for other apps by setting a preferred device.
7865     bool active; // unused
7866     sp<DeviceDescriptor> device =
7867         findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
7868     if (device != nullptr) {
7869         return DeviceVector(device);
7870     }
7871 
7872     // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7873     // of setForceUse / Default Bus device here
7874     device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7875     if (device != nullptr) {
7876         return DeviceVector(device);
7877     }
7878 
7879     DeviceVector devices;
7880     for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7881         StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7882         auto hasStreamActive = [&](auto stream) {
7883             return hasStream(streams, stream) && isStreamActive(stream, 0);
7884         };
7885 
7886         auto doGetOutputDevicesForVoice = [&]() {
7887             return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
7888                 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
7889                 (isInCall() ||
7890                  mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7891                 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
7892         };
7893 
7894         // With low-latency playing on speaker, music on WFD, when the first low-latency
7895         // output is stopped, getNewOutputDevices checks for a product strategy
7896         // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
7897         // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
7898         // devices are returned for STRATEGY_SONIFICATION without checking whether the
7899         // stream is associated to the output descriptor.
7900         if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7901                ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7902                 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7903                 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
7904             // Retrieval of devices for voice DL is done on primary output profile, cannot
7905             // check the route (would force modifying configuration file for this profile)
7906             auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7907             devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7908             break;
7909         }
7910     }
7911     ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
7912     return devices;
7913 }
7914 
getNewInputDevice(const sp<AudioInputDescriptor> & inputDesc)7915 sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7916         const sp<AudioInputDescriptor>& inputDesc)
7917 {
7918     sp<DeviceDescriptor> device;
7919 
7920     ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
7921     if (index >= 0) {
7922         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7923         if (patchDesc->getUid() != mUidCached) {
7924             ALOGV("getNewInputDevice() device %s forced by patch %d",
7925                   inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7926             return inputDesc->getDevice();
7927         }
7928     }
7929 
7930     // Honor explicit routing requests only if no client using default routing is active on this
7931     // input or if all active clients are from the same app: a specific app can not force routing
7932     // for other apps by setting a preferred device.
7933     bool active;
7934     device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7935     if (device != nullptr) {
7936         return device;
7937     }
7938 
7939     // If we are not in call and no client is active on this input, this methods returns
7940     // a null sp<>, causing the patch on the input stream to be released.
7941     audio_attributes_t attributes;
7942     uid_t uid;
7943     audio_session_t session;
7944     sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7945     if (topClient != nullptr) {
7946         attributes = topClient->attributes();
7947         uid = topClient->uid();
7948         session = topClient->session();
7949     } else {
7950         attributes = { .source = AUDIO_SOURCE_DEFAULT };
7951         uid = 0;
7952         session = AUDIO_SESSION_NONE;
7953     }
7954 
7955     if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7956         attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
7957     }
7958     if (attributes.source != AUDIO_SOURCE_DEFAULT) {
7959         device = mEngine->getInputDeviceForAttributes(
7960                 attributes, false /*ignorePreferredDevice*/, uid, session);
7961     }
7962 
7963     return device;
7964 }
7965 
streamsMatchForvolume(audio_stream_type_t stream1,audio_stream_type_t stream2)7966 bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7967                                                audio_stream_type_t stream2) {
7968     return (stream1 == stream2);
7969 }
7970 
getDevicesForAttributes(const audio_attributes_t & attr,AudioDeviceTypeAddrVector * devices,bool forVolume)7971 status_t AudioPolicyManager::getDevicesForAttributes(
7972         const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
7973     if (devices == nullptr) {
7974         return BAD_VALUE;
7975     }
7976 
7977     DeviceVector curDevices;
7978     if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7979         return status;
7980     }
7981     for (const auto& device : curDevices) {
7982         devices->push_back(device->getDeviceTypeAddr());
7983     }
7984     return NO_ERROR;
7985 }
7986 
handleNotificationRoutingForStream(audio_stream_type_t stream)7987 void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
7988     switch(stream) {
7989     case AUDIO_STREAM_MUSIC:
7990         checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
7991         updateDevicesAndOutputs();
7992         break;
7993     default:
7994         break;
7995     }
7996 }
7997 
handleEventForBeacon(int event)7998 uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
7999 
8000     // skip beacon mute management if a dedicated TTS output is available
8001     if (mTtsOutputAvailable) {
8002         return 0;
8003     }
8004 
8005     switch(event) {
8006     case STARTING_OUTPUT:
8007         mBeaconMuteRefCount++;
8008         break;
8009     case STOPPING_OUTPUT:
8010         if (mBeaconMuteRefCount > 0) {
8011             mBeaconMuteRefCount--;
8012         }
8013         break;
8014     case STARTING_BEACON:
8015         mBeaconPlayingRefCount++;
8016         break;
8017     case STOPPING_BEACON:
8018         if (mBeaconPlayingRefCount > 0) {
8019             mBeaconPlayingRefCount--;
8020         }
8021         break;
8022     }
8023 
8024     if (mBeaconMuteRefCount > 0) {
8025         // any playback causes beacon to be muted
8026         return setBeaconMute(true);
8027     } else {
8028         // no other playback: unmute when beacon starts playing, mute when it stops
8029         return setBeaconMute(mBeaconPlayingRefCount == 0);
8030     }
8031 }
8032 
setBeaconMute(bool mute)8033 uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
8034     ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
8035             mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
8036     // keep track of muted state to avoid repeating mute/unmute operations
8037     if (mBeaconMuted != mute) {
8038         // mute/unmute AUDIO_STREAM_TTS on all outputs
8039         ALOGV("\t muting %d", mute);
8040         uint32_t maxLatency = 0;
8041         auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
8042         if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
8043             ALOGV("\t no tts volume source available");
8044             return 0;
8045         }
8046         for (size_t i = 0; i < mOutputs.size(); i++) {
8047             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
8048             setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
8049                                            DeviceTypeSet());
8050             const uint32_t latency = desc->latency() * 2;
8051             if (desc->isActive(latency * 2) && latency > maxLatency) {
8052                 maxLatency = latency;
8053             }
8054         }
8055         mBeaconMuted = mute;
8056         return maxLatency;
8057     }
8058     return 0;
8059 }
8060 
updateDevicesAndOutputs()8061 void AudioPolicyManager::updateDevicesAndOutputs()
8062 {
8063     mEngine->updateDeviceSelectionCache();
8064     mPreviousOutputs = mOutputs;
8065 }
8066 
checkDeviceMuteStrategies(const sp<AudioOutputDescriptor> & outputDesc,const DeviceVector & prevDevices,uint32_t delayMs)8067 uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
8068                                                        const DeviceVector &prevDevices,
8069                                                        uint32_t delayMs)
8070 {
8071     // mute/unmute strategies using an incompatible device combination
8072     // if muting, wait for the audio in pcm buffer to be drained before proceeding
8073     // if unmuting, unmute only after the specified delay
8074     if (outputDesc->isDuplicated()) {
8075         return 0;
8076     }
8077 
8078     uint32_t muteWaitMs = 0;
8079     DeviceVector devices = outputDesc->devices();
8080     bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
8081 
8082     auto productStrategies = mEngine->getOrderedProductStrategies();
8083     for (const auto &productStrategy : productStrategies) {
8084         auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
8085         DeviceVector curDevices =
8086                 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
8087         curDevices = curDevices.filter(outputDesc->supportedDevices());
8088         bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
8089         bool doMute = false;
8090 
8091         if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
8092             doMute = true;
8093             outputDesc->setStrategyMutedByDevice(productStrategy, true);
8094         } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
8095             doMute = true;
8096             outputDesc->setStrategyMutedByDevice(productStrategy, false);
8097         }
8098         if (doMute) {
8099             for (size_t j = 0; j < mOutputs.size(); j++) {
8100                 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
8101                 // skip output if it does not share any device with current output
8102                 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
8103                     continue;
8104                 }
8105                 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
8106                       mute ? "muting" : "unmuting", curDevices.toString().c_str());
8107                 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
8108                 if (desc->isStrategyActive(productStrategy)) {
8109                     if (mute) {
8110                         // FIXME: should not need to double latency if volume could be applied
8111                         // immediately by the audioflinger mixer. We must account for the delay
8112                         // between now and the next time the audioflinger thread for this output
8113                         // will process a buffer (which corresponds to one buffer size,
8114                         // usually 1/2 or 1/4 of the latency).
8115                         if (muteWaitMs < desc->latency() * 2) {
8116                             muteWaitMs = desc->latency() * 2;
8117                         }
8118                     }
8119                 }
8120             }
8121         }
8122     }
8123 
8124     // temporary mute output if device selection changes to avoid volume bursts due to
8125     // different per device volumes
8126     if (outputDesc->isActive() && (devices != prevDevices)) {
8127         uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
8128 
8129         if (muteWaitMs < tempMuteWaitMs) {
8130             muteWaitMs = tempMuteWaitMs;
8131         }
8132 
8133         // If recommended duration is defined, replace temporary mute duration to avoid
8134         // truncated notifications at beginning, which depends on duration of changing path in HAL.
8135         // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8136         uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8137         uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8138                 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8139 
8140         for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8141             // make sure that we do not start the temporary mute period too early in case of
8142             // delayed device change
8143             setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8144             setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8145                                            delayMs + tempMuteDurationMs,
8146                                            devices.types());
8147         }
8148     }
8149 
8150     // wait for the PCM output buffers to empty before proceeding with the rest of the command
8151     if (muteWaitMs > delayMs) {
8152         muteWaitMs -= delayMs;
8153         usleep(muteWaitMs * 1000);
8154         return muteWaitMs;
8155     }
8156     return 0;
8157 }
8158 
setOutputDevices(const char * caller,const sp<SwAudioOutputDescriptor> & outputDesc,const DeviceVector & devices,bool force,int delayMs,audio_patch_handle_t * patchHandle,bool requiresMuteCheck,bool requiresVolumeCheck,bool skipMuteDelay)8159 uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8160                                               const sp<SwAudioOutputDescriptor>& outputDesc,
8161                                               const DeviceVector &devices,
8162                                               bool force,
8163                                               int delayMs,
8164                                               audio_patch_handle_t *patchHandle,
8165                                               bool requiresMuteCheck, bool requiresVolumeCheck,
8166                                               bool skipMuteDelay)
8167 {
8168     // TODO(b/262404095): Consider if the output need to be reopened.
8169     std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8170     ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8171           devices.toString().c_str(), delayMs);
8172     uint32_t muteWaitMs;
8173 
8174     if (outputDesc->isDuplicated()) {
8175         muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
8176                 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
8177         muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
8178                 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
8179         return muteWaitMs;
8180     }
8181 
8182     // filter devices according to output selected
8183     DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
8184     DeviceVector prevDevices = outputDesc->devices();
8185     DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
8186 
8187     ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8188           prevDevices.toString().c_str());
8189 
8190     if (!filteredDevices.isEmpty()) {
8191         outputDesc->setDevices(filteredDevices);
8192     }
8193 
8194     // if the outputs are not materially active, there is no need to mute.
8195     if (requiresMuteCheck) {
8196         muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
8197     } else {
8198         ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8199               logPrefix.c_str());
8200         muteWaitMs = 0;
8201     }
8202 
8203     bool outputRouted = outputDesc->isRouted();
8204 
8205     // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8206     // output profile or if new device is not supported AND previous device(s) is(are) still
8207     // available (otherwise reset device must be done on the output)
8208     if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
8209         ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8210               devices.toString().c_str());
8211         // restore previous device after evaluating strategy mute state
8212         outputDesc->setDevices(prevDevices);
8213         applyStreamVolumes(outputDesc, prevDevices.types(), delayMs, true /*force*/);
8214         return muteWaitMs;
8215     }
8216 
8217     // Do not change the routing if:
8218     //      the requested device is AUDIO_DEVICE_NONE
8219     //      OR the requested device is the same as current device
8220     //  AND force is not specified
8221     //  AND the output is connected by a valid audio patch.
8222     // Doing this check here allows the caller to call setOutputDevices() without conditions
8223     if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
8224         ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8225               __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8226               outputDesc->getPatchHandle());
8227         if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
8228             ALOGV("%s %s setting same device on routed output, force apply volumes",
8229                   __func__, logPrefix.c_str());
8230             applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8231         }
8232         return muteWaitMs;
8233     }
8234 
8235     ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8236           filteredDevices.toString().c_str());
8237 
8238     // do the routing
8239     if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
8240         resetOutputDevice(outputDesc, delayMs, NULL);
8241     } else {
8242         PatchBuilder patchBuilder;
8243         patchBuilder.addSource(outputDesc);
8244         ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8245         for (const auto &filteredDevice : filteredDevices) {
8246             patchBuilder.addSink(filteredDevice);
8247         }
8248 
8249         // Add half reported latency to delayMs when muteWaitMs is null in order
8250         // to avoid disordered sequence of muting volume and changing devices.
8251         int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8252                 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8253         installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
8254     }
8255 
8256     // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8257     if (!skipMuteDelay) {
8258         // update stream volumes according to new device
8259         applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8260     }
8261 
8262     return muteWaitMs;
8263 }
8264 
resetOutputDevice(const sp<AudioOutputDescriptor> & outputDesc,int delayMs,audio_patch_handle_t * patchHandle)8265 status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
8266                                                int delayMs,
8267                                                audio_patch_handle_t *patchHandle)
8268 {
8269     ssize_t index;
8270     if (patchHandle == nullptr && !outputDesc->isRouted()) {
8271         return INVALID_OPERATION;
8272     }
8273     if (patchHandle) {
8274         index = mAudioPatches.indexOfKey(*patchHandle);
8275     } else {
8276         index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
8277     }
8278     if (index < 0) {
8279         return INVALID_OPERATION;
8280     }
8281     sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8282     status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
8283     ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
8284     outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
8285     removeAudioPatch(patchDesc->getHandle());
8286     nextAudioPortGeneration();
8287     mpClientInterface->onAudioPatchListUpdate();
8288     return status;
8289 }
8290 
setInputDevice(audio_io_handle_t input,const sp<DeviceDescriptor> & device,bool force,audio_patch_handle_t * patchHandle)8291 status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
8292                                             const sp<DeviceDescriptor> &device,
8293                                             bool force,
8294                                             audio_patch_handle_t *patchHandle)
8295 {
8296     status_t status = NO_ERROR;
8297 
8298     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
8299     if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8300         inputDesc->setDevice(device);
8301 
8302         if (mAvailableInputDevices.contains(device)) {
8303             PatchBuilder patchBuilder;
8304             patchBuilder.addSink(inputDesc,
8305             // AUDIO_SOURCE_HOTWORD is for internal use only:
8306             // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
8307                     [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8308                         auto result = usecase;
8309                         if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8310                             result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8311                         }
8312                         return result; });
8313             //only one input device for now
8314             if (audio_is_remote_submix_device(device->type())) {
8315                 // remote submix HAL does not support audio conversion, need source device
8316                 // audio config to match the sink input descriptor audio config, otherwise AIDL
8317                 // HAL patching will fail
8318                 audio_port_config srcDevicePortConfig = {};
8319                 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8320                 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8321                 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8322                 srcDevicePortConfig.format = inputDesc->getFormat();
8323                 patchBuilder.addSource(srcDevicePortConfig);
8324             } else {
8325                 patchBuilder.addSource(device);
8326             }
8327             status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
8328         }
8329     }
8330     return status;
8331 }
8332 
resetInputDevice(audio_io_handle_t input,audio_patch_handle_t * patchHandle)8333 status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8334                                               audio_patch_handle_t *patchHandle)
8335 {
8336     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
8337     ssize_t index;
8338     if (patchHandle) {
8339         index = mAudioPatches.indexOfKey(*patchHandle);
8340     } else {
8341         index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
8342     }
8343     if (index < 0) {
8344         return INVALID_OPERATION;
8345     }
8346     sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8347     status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
8348     ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
8349     inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
8350     removeAudioPatch(patchDesc->getHandle());
8351     nextAudioPortGeneration();
8352     mpClientInterface->onAudioPatchListUpdate();
8353     return status;
8354 }
8355 
getInputProfile(const sp<DeviceDescriptor> & device,uint32_t & samplingRate,audio_format_t & format,audio_channel_mask_t & channelMask,audio_input_flags_t flags)8356 sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
8357                                                   uint32_t& samplingRate,
8358                                                   audio_format_t& format,
8359                                                   audio_channel_mask_t& channelMask,
8360                                                   audio_input_flags_t flags)
8361 {
8362     // Choose an input profile based on the requested capture parameters: select the first available
8363     // profile supporting all requested parameters.
8364     // The flags can be ignored if it doesn't contain a much match flag.
8365 
8366     using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8367     const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8368                          AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8369 
8370     const underlying_input_flag_t oriFlags = flags;
8371 
8372     for (;;) {
8373         sp<IOProfile> inexact = nullptr;
8374         uint32_t inexactSamplingRate = 0;
8375         audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8376         audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
8377         uint32_t updatedSamplingRate = 0;
8378         audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8379         audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8380         auto bestCompatibleScore = IOProfile::NO_MATCH;
8381         for (const auto& hwModule : mHwModules) {
8382             for (const auto& profile : hwModule->getInputProfiles()) {
8383                 // profile->log();
8384                 //updatedFormat = format;
8385                 auto compatibleScore = profile->getCompatibilityScore(
8386                         DeviceVector(device),
8387                         samplingRate,
8388                         &updatedSamplingRate,
8389                         format,
8390                         &updatedFormat,
8391                         channelMask,
8392                         &updatedChannelMask,
8393                         // FIXME ugly cast
8394                         (audio_output_flags_t) flags);
8395                 if (compatibleScore == IOProfile::EXACT_MATCH) {
8396                     samplingRate = updatedSamplingRate;
8397                     format = updatedFormat;
8398                     channelMask = updatedChannelMask;
8399                     return profile;
8400                 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8401                         && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8402                     || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8403                     if (compatibleScore > bestCompatibleScore) {
8404                         inexact = profile;
8405                         inexactSamplingRate = updatedSamplingRate;
8406                         inexactFormat = updatedFormat;
8407                         inexactChannelMask = updatedChannelMask;
8408                         bestCompatibleScore = compatibleScore;
8409                     }
8410                 }
8411             }
8412         }
8413 
8414         if (inexact != nullptr) {
8415             samplingRate = inexactSamplingRate;
8416             format = inexactFormat;
8417             channelMask = inexactChannelMask;
8418             return inexact;
8419         } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8420             flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8421         } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8422                 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8423             flags = AUDIO_INPUT_FLAG_NONE;
8424         } else { // fail
8425             ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8426                   "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8427                   samplingRate, format, channelMask, oriFlags);
8428             break;
8429         }
8430     }
8431 
8432     return nullptr;
8433 }
8434 
adjustDeviceAttenuationForAbsVolume(IVolumeCurves & curves,VolumeSource volumeSource,int index,const DeviceTypeSet & deviceTypes)8435 float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8436                                                               VolumeSource volumeSource,
8437                                                               int index,
8438                                                               const DeviceTypeSet &deviceTypes)
8439 {
8440     audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8441     device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8442     float volumeDb = curves.volIndexToDb(deviceCategory, index);
8443 
8444     const auto it = mAbsoluteVolumeDrivingStreams.find(volumeDevice);
8445     if (it != mAbsoluteVolumeDrivingStreams.end()) {
8446         audio_attributes_t attributesToDriveAbs = it->second;
8447         auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8448         if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8449             ALOGD("%s: no group matching with %s", __FUNCTION__,
8450                   toString(attributesToDriveAbs).c_str());
8451             return volumeDb;
8452         }
8453 
8454         float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8455         VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8456         if (vsToDriveAbs == volumeSource) {
8457             // attenuation is applied by the abs volume controller
8458             // do not mute LE broadcast to allow the secondary device to continue playing
8459             return (index != 0 || volumeDevice == AUDIO_DEVICE_OUT_BLE_BROADCAST) ? volumeDbMax
8460                                                                                   : volumeDb;
8461         } else {
8462             IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8463             int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8464             float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8465             float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8466                                                           curvesAbs.getVolumeIndexMax());
8467             float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8468             ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8469                   "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8470                   volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8471             return newVolumeDb;
8472         }
8473     }
8474     return volumeDb;
8475 }
8476 
computeVolume(IVolumeCurves & curves,VolumeSource volumeSource,int index,const DeviceTypeSet & deviceTypes,bool adjustAttenuation,bool computeInternalInteraction)8477 float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8478                                         VolumeSource volumeSource,
8479                                         int index,
8480                                         const DeviceTypeSet& deviceTypes,
8481                                         bool adjustAttenuation,
8482                                         bool computeInternalInteraction)
8483 {
8484     float volumeDb;
8485     if (adjustAttenuation) {
8486         volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8487     } else {
8488         volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8489     }
8490     ALOGV("%s volume source %d, index %d,  devices %s, compute internal %b ", __func__,
8491           volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8492 
8493     if (!computeInternalInteraction) {
8494         return volumeDb;
8495     }
8496 
8497     // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8498     // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8499     // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8500     // the ringtone volume
8501     const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8502     const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8503     const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8504     const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8505     const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
8506     if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
8507             mOutputs.isActive(ringVolumeSrc, 0)) {
8508         auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
8509         const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8510                                                  adjustAttenuation,
8511                                                  /* computeInternalInteraction= */false);
8512         return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
8513     }
8514 
8515     // in-call: always cap volume by voice volume + some low headroom
8516     if ((volumeSource != callVolumeSrc && (isInCall() ||
8517                                            mOutputs.isActiveLocally(callVolumeSrc))) &&
8518             (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
8519              volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8520              volumeSource == alarmVolumeSrc ||
8521              volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8522              volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8523              volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
8524              volumeSource == a11yVolumeSrc)) {
8525         auto &voiceCurves = getVolumeCurves(callVolumeSrc);
8526         int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
8527         const float maxVoiceVolDb =
8528                 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8529                         adjustAttenuation, /* computeInternalInteraction= */false)
8530                 + IN_CALL_EARPIECE_HEADROOM_DB;
8531         // FIXME: Workaround for call screening applications until a proper audio mode is defined
8532         // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8533         // programmatically muted.
8534         // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8535         // 0. We don't want to cap volume when the system has programmatically muted the voice call
8536         // stream. See setVolumeCurveIndex() for more information.
8537         bool exemptFromCapping =
8538                 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8539                 && (voiceVolumeIndex == 0);
8540         ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8541                  volumeSource, volumeDb);
8542         if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
8543             ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8544                   volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8545             volumeDb = maxVoiceVolDb;
8546         }
8547     }
8548     // if a headset is connected, apply the following rules to ring tones and notifications
8549     // to avoid sound level bursts in user's ears:
8550     // - always attenuate notifications volume by 6dB
8551     // - attenuate ring tones volume by 6dB unless music is not playing and
8552     // speaker is part of the select devices
8553     // - if music is playing, always limit the volume to current music volume,
8554     // with a minimum threshold at -36dB so that notification is always perceived.
8555     if (!Intersection(deviceTypes,
8556             {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8557              AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
8558              AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8559              AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
8560             ((volumeSource == alarmVolumeSrc ||
8561               volumeSource == ringVolumeSrc) ||
8562              (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8563              (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8564              ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
8565               (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8566             curves.canBeMuted()) {
8567 
8568         // when the phone is ringing we must consider that music could have been paused just before
8569         // by the music application and behave as if music was active if the last music track was
8570         // just stopped
8571         if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8572                 || mLimitRingtoneVolume) {
8573             volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
8574             DeviceTypeSet musicDevice =
8575                     mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8576                                                            nullptr, true /*fromCache*/).types();
8577             auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
8578             float musicVolDb = computeVolume(musicCurves,
8579                                              musicVolumeSrc,
8580                                              musicCurves.getVolumeIndex(musicDevice),
8581                                              musicDevice,
8582                                               adjustAttenuation,
8583                                               /* computeInternalInteraction= */ false);
8584             float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8585                         musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8586             if (volumeDb > minVolDb) {
8587                 volumeDb = minVolDb;
8588                 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
8589             }
8590             if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8591                     &&  !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
8592                         AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8593                         AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8594                 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8595                 // when intended to be played.
8596                 if ((volumeDb > -96.0f) &&
8597                         (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
8598                     ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8599                           __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
8600                           musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8601                     volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
8602                 }
8603             }
8604         } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
8605                    (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
8606             volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
8607         }
8608     }
8609 
8610     return volumeDb;
8611 }
8612 
rescaleVolumeIndex(int srcIndex,VolumeSource fromVolumeSource,VolumeSource toVolumeSource)8613 int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
8614                                            VolumeSource fromVolumeSource,
8615                                            VolumeSource toVolumeSource)
8616 {
8617     if (fromVolumeSource == toVolumeSource) {
8618         return srcIndex;
8619     }
8620     auto &srcCurves = getVolumeCurves(fromVolumeSource);
8621     auto &dstCurves = getVolumeCurves(toVolumeSource);
8622     float minSrc = (float)srcCurves.getVolumeIndexMin();
8623     float maxSrc = (float)srcCurves.getVolumeIndexMax();
8624     float minDst = (float)dstCurves.getVolumeIndexMin();
8625     float maxDst = (float)dstCurves.getVolumeIndexMax();
8626 
8627     // preserve mute request or correct range
8628     if (srcIndex < minSrc) {
8629         if (srcIndex == 0) {
8630             return 0;
8631         }
8632         srcIndex = minSrc;
8633     } else if (srcIndex > maxSrc) {
8634         srcIndex = maxSrc;
8635     }
8636     return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8637 }
8638 
checkAndSetVolume(IVolumeCurves & curves,VolumeSource volumeSource,int index,const sp<AudioOutputDescriptor> & outputDesc,DeviceTypeSet deviceTypes,int delayMs,bool force)8639 status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8640                                                VolumeSource volumeSource,
8641                                                int index,
8642                                                const sp<AudioOutputDescriptor>& outputDesc,
8643                                                DeviceTypeSet deviceTypes,
8644                                                int delayMs,
8645                                                bool force)
8646 {
8647     // APM is single threaded, and single instance.
8648     static std::set<IVolumeCurves*> invalidCurvesReported;
8649 
8650     // do not change actual attributes volume if the attributes is muted
8651     if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
8652         ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8653                outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
8654         return NO_ERROR;
8655     }
8656 
8657     bool isVoiceVolSrc;
8658     bool isBtScoVolSrc;
8659     if (!isVolumeConsistentForCalls(
8660             volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
8661         // Do not return an error here as AudioService will always set both voice call
8662         // and Bluetooth SCO volumes due to stream aliasing.
8663         return NO_ERROR;
8664     }
8665 
8666     if (deviceTypes.empty()) {
8667         deviceTypes = outputDesc->devices().types();
8668         index = curves.getVolumeIndex(deviceTypes);
8669         ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
8670                 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
8671     }
8672 
8673     if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8674         if (!invalidCurvesReported.count(&curves)) {
8675             invalidCurvesReported.insert(&curves);
8676             String8 dump;
8677             curves.dump(&dump);
8678             ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8679         }
8680         return BAD_VALUE;
8681     }
8682 
8683     float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8684     const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
8685     if (outputDesc->isFixedVolume(deviceTypes) ||
8686             // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
8687             (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8688                         || (isInCall() && (dtmfVolSrc == volumeSource))) &&
8689                     (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8690                     || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
8691         volumeDb = 0.0f;
8692     }
8693 
8694     bool muted;
8695     if (!com_android_media_audio_ring_my_car()) {
8696         muted = (index == 0) && (volumeDb != 0.0f);
8697     } else {
8698         muted = curves.isMuted();
8699     }
8700     outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8701             deviceTypes, delayMs, force, isVoiceVolSrc);
8702 
8703     if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
8704         bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
8705                 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8706         setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
8707     }
8708     return NO_ERROR;
8709 }
8710 
setVoiceVolume(int index,IVolumeCurves & curves,bool voiceVolumeManagedByHost,int delayMs)8711 void AudioPolicyManager::setVoiceVolume(
8712         int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
8713     float voiceVolume;
8714 
8715     if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8716         index = 0;
8717     }
8718 
8719     // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
8720     // by the headset
8721     if (voiceVolumeManagedByHost) {
8722         voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8723     } else {
8724         voiceVolume = index == 0 ? 0.0 : 1.0;
8725     }
8726     if (voiceVolume != mLastVoiceVolume) {
8727         mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8728         mLastVoiceVolume = voiceVolume;
8729     }
8730 }
8731 
isVolumeConsistentForCalls(VolumeSource volumeSource,const DeviceTypeSet & deviceTypes,bool & isVoiceVolSrc,bool & isBtScoVolSrc,const char * caller)8732 bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8733                                                    const DeviceTypeSet& deviceTypes,
8734                                                    bool& isVoiceVolSrc,
8735                                                    bool& isBtScoVolSrc,
8736                                                    const char* caller) {
8737     const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8738     isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8739 
8740     const bool isScoRequested = isScoRequestedForComm();
8741     const bool isHAUsed = isHearingAidUsedForComm();
8742 
8743     if (com_android_media_audio_replace_stream_bt_sco()) {
8744         isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8745                         (isScoRequested || isHAUsed);
8746         return true;
8747     }
8748 
8749     const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8750     isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8751 
8752     if ((callVolSrc != btScoVolSrc) &&
8753             ((isVoiceVolSrc && isScoRequested) ||
8754              (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8755             !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8756         ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8757              volumeSource, isScoRequested ? " " : " not ");
8758         return false;
8759     }
8760     return true;
8761 }
8762 
applyStreamVolumes(const sp<AudioOutputDescriptor> & outputDesc,const DeviceTypeSet & deviceTypes,int delayMs,bool force)8763 void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
8764                                             const DeviceTypeSet& deviceTypes,
8765                                             int delayMs,
8766                                             bool force)
8767 {
8768     ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
8769     for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8770         auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8771         checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
8772                           outputDesc, deviceTypes, delayMs, force);
8773     }
8774 }
8775 
setStrategyMute(product_strategy_t strategy,bool on,const sp<AudioOutputDescriptor> & outputDesc,int delayMs,DeviceTypeSet deviceTypes)8776 void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8777                                          bool on,
8778                                          const sp<AudioOutputDescriptor>& outputDesc,
8779                                          int delayMs,
8780                                          DeviceTypeSet deviceTypes)
8781 {
8782     std::vector<VolumeSource> sourcesToMute;
8783     for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8784         ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8785                toString(attributes).c_str(), on, outputDesc->getId());
8786         VolumeSource source = toVolumeSource(attributes, false);
8787         if ((source != VOLUME_SOURCE_NONE) &&
8788                 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8789                         == end(sourcesToMute))) {
8790             sourcesToMute.push_back(source);
8791         }
8792     }
8793     for (auto source : sourcesToMute) {
8794         setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
8795     }
8796 
8797 }
8798 
setVolumeSourceMutedInternally(VolumeSource volumeSource,bool on,const sp<AudioOutputDescriptor> & outputDesc,int delayMs,DeviceTypeSet deviceTypes)8799 void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8800                                                         bool on,
8801                                                         const sp<AudioOutputDescriptor>& outputDesc,
8802                                                         int delayMs,
8803                                                         DeviceTypeSet deviceTypes)
8804 {
8805     if (deviceTypes.empty()) {
8806         deviceTypes = outputDesc->devices().types();
8807     }
8808     auto &curves = getVolumeCurves(volumeSource);
8809     if (on) {
8810         if (!outputDesc->isMutedInternally(volumeSource)) {
8811             if (curves.canBeMuted() &&
8812                     (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8813                      (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8814                       AUDIO_POLICY_FORCE_NONE))) {
8815                 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
8816             }
8817         }
8818         // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8819         // ignored
8820         outputDesc->incMuteCount(volumeSource);
8821     } else {
8822         if (!outputDesc->isMutedInternally(volumeSource)) {
8823             ALOGV("%s unmuting non muted attributes!", __func__);
8824             return;
8825         }
8826         if (outputDesc->decMuteCount(volumeSource) == 0) {
8827             checkAndSetVolume(curves, volumeSource,
8828                               curves.getVolumeIndex(deviceTypes),
8829                               outputDesc,
8830                               deviceTypes,
8831                               delayMs);
8832         }
8833     }
8834 }
8835 
isValidAttributes(const audio_attributes_t * paa)8836 bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8837 {
8838     if ((paa->flags & AUDIO_FLAG_SCO) != 0) {
8839         ALOGW("%s: deprecated use of AUDIO_FLAG_SCO in attributes flags %d", __func__, paa->flags);
8840     }
8841 
8842     // has flags that map to a stream type?
8843     if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_BEACON)) != 0) {
8844         return true;
8845     }
8846 
8847     // has known usage?
8848     switch (paa->usage) {
8849     case AUDIO_USAGE_UNKNOWN:
8850     case AUDIO_USAGE_MEDIA:
8851     case AUDIO_USAGE_VOICE_COMMUNICATION:
8852     case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8853     case AUDIO_USAGE_ALARM:
8854     case AUDIO_USAGE_NOTIFICATION:
8855     case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8856     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8857     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8858     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8859     case AUDIO_USAGE_NOTIFICATION_EVENT:
8860     case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8861     case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8862     case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8863     case AUDIO_USAGE_GAME:
8864     case AUDIO_USAGE_VIRTUAL_SOURCE:
8865     case AUDIO_USAGE_ASSISTANT:
8866     case AUDIO_USAGE_CALL_ASSISTANT:
8867     case AUDIO_USAGE_EMERGENCY:
8868     case AUDIO_USAGE_SAFETY:
8869     case AUDIO_USAGE_VEHICLE_STATUS:
8870     case AUDIO_USAGE_ANNOUNCEMENT:
8871     case AUDIO_USAGE_SPEAKER_CLEANUP:
8872         break;
8873     default:
8874         return false;
8875     }
8876     return true;
8877 }
8878 
getForceUse(audio_policy_force_use_t usage)8879 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8880 {
8881     return mEngine->getForceUse(usage);
8882 }
8883 
isInCall() const8884 bool AudioPolicyManager::isInCall() const {
8885     return isStateInCall(mEngine->getPhoneState());
8886 }
8887 
isStateInCall(int state) const8888 bool AudioPolicyManager::isStateInCall(int state) const {
8889     return is_state_in_call(state);
8890 }
8891 
isCallAudioAccessible() const8892 bool AudioPolicyManager::isCallAudioAccessible() const {
8893     audio_mode_t mode = mEngine->getPhoneState();
8894     return (mode == AUDIO_MODE_IN_CALL)
8895             || (mode == AUDIO_MODE_CALL_SCREEN)
8896             || (mode == AUDIO_MODE_CALL_REDIRECT);
8897 }
8898 
isInCallOrScreening() const8899 bool AudioPolicyManager::isInCallOrScreening() const {
8900     audio_mode_t mode = mEngine->getPhoneState();
8901     return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8902 }
8903 
cleanUpForDevice(const sp<DeviceDescriptor> & deviceDesc)8904 void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8905 {
8906     for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--)  {
8907         sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
8908         if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
8909                                           sourceDesc->sinkDevice()->equals(deviceDesc))
8910                 && !sourceDesc->isCallRx()) {
8911             disconnectAudioSource(sourceDesc);
8912         }
8913     }
8914 
8915     for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--)  {
8916         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8917         bool release = false;
8918         for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++)  {
8919             const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8920             if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8921                     source->ext.device.type == deviceDesc->type()) {
8922                 release = true;
8923             }
8924         }
8925         const char *address = deviceDesc->address().c_str();
8926         for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++)  {
8927             const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8928             if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
8929                     sink->ext.device.type == deviceDesc->type() &&
8930                     (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8931                      || strncmp(sink->ext.device.address, address,
8932                                  AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
8933                 release = true;
8934             }
8935         }
8936         if (release) {
8937             ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8938             releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
8939         }
8940     }
8941 
8942     mInputs.clearSessionRoutesForDevice(deviceDesc);
8943 
8944     mHwModules.cleanUpForDevice(deviceDesc);
8945 }
8946 
modifySurroundFormats(const sp<DeviceDescriptor> & devDesc,FormatVector * formatsPtr)8947 void AudioPolicyManager::modifySurroundFormats(
8948         const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
8949     std::unordered_set<audio_format_t> enforcedSurround(
8950             devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
8951     std::unordered_set<audio_format_t> allSurround;  // A flat set of all known surround formats
8952     for (const auto& pair : mConfig->getSurroundFormats()) {
8953         allSurround.insert(pair.first);
8954         for (const auto& subformat : pair.second) allSurround.insert(subformat);
8955     }
8956 
8957     audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8958             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8959     ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
8960     // This is the resulting set of formats depending on the surround mode:
8961     //   'all surround' = allSurround
8962     //   'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8963     //   'non-surround' = not in 'all surround' and not in 'enforced surround'
8964     //   'manual surround' = mManualSurroundFormats
8965     // AUTO:   formats v 'enforced surround'
8966     // ALWAYS: formats v 'all surround' v 'enforced surround'
8967     // NEVER:  formats ^ 'non-surround'
8968     // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
8969 
8970     std::unordered_set<audio_format_t> formatSet;
8971     if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8972             || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
8973         // formatSet is (formats ^ 'non-surround')
8974         for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
8975             if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
8976                 formatSet.insert(*formatIter);
8977             }
8978         }
8979     } else {
8980         formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8981     }
8982     formatsPtr->clear();  // Re-filled from the formatSet at the end.
8983 
8984     if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
8985         formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
8986         // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8987         if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8988             formatSet.insert(AUDIO_FORMAT_IEC61937);
8989         }
8990     } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8991         if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8992             formatSet.insert(allSurround.begin(), allSurround.end());
8993         }
8994         formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
8995     }
8996     for (const auto& format : formatSet) {
8997         formatsPtr->push_back(format);
8998     }
8999 }
9000 
modifySurroundChannelMasks(ChannelMaskSet * channelMasksPtr)9001 void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
9002     ChannelMaskSet &channelMasks = *channelMasksPtr;
9003     audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
9004             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
9005 
9006     // If NEVER, then remove support for channelMasks > stereo.
9007     if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
9008         for (auto it = channelMasks.begin(); it != channelMasks.end();) {
9009             audio_channel_mask_t channelMask = *it;
9010             if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
9011                 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
9012                 it = channelMasks.erase(it);
9013             } else {
9014                 ++it;
9015             }
9016         }
9017     // If ALWAYS or MANUAL, then make sure we at least support 5.1
9018     } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
9019             || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
9020         bool supports5dot1 = false;
9021         // Are there any channel masks that can be considered "surround"?
9022         for (audio_channel_mask_t channelMask : channelMasks) {
9023             if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
9024                 supports5dot1 = true;
9025                 break;
9026             }
9027         }
9028         // If not then add 5.1 support.
9029         if (!supports5dot1) {
9030             channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
9031             ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
9032         }
9033     }
9034 }
9035 
updateAudioProfiles(const sp<DeviceDescriptor> & devDesc,audio_io_handle_t ioHandle,const sp<IOProfile> & profile)9036 void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
9037                                              audio_io_handle_t ioHandle,
9038                                              const sp<IOProfile>& profile) {
9039     if (!profile->hasDynamicAudioProfile()) {
9040         return;
9041     }
9042 
9043     audio_port_v7 devicePort;
9044     devDesc->toAudioPort(&devicePort);
9045 
9046     audio_port_v7 mixPort;
9047     profile->toAudioPort(&mixPort);
9048     mixPort.ext.mix.handle = ioHandle;
9049 
9050     status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
9051     if (status != NO_ERROR) {
9052         ALOGE("%s failed to query the attributes of the mix port", __func__);
9053         return;
9054     }
9055 
9056     std::set<audio_format_t> supportedFormats;
9057     for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
9058         supportedFormats.insert(mixPort.audio_profiles[i].format);
9059     }
9060     FormatVector formats(supportedFormats.begin(), supportedFormats.end());
9061     mReportedFormatsMap[devDesc] = formats;
9062 
9063     if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
9064         devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
9065         devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
9066         isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
9067         modifySurroundFormats(devDesc, &formats);
9068         size_t modifiedNumProfiles = 0;
9069         for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
9070             if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
9071                 formats.end()) {
9072                 // Skip the format that is not present after modifying surround formats.
9073                 continue;
9074             }
9075             memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
9076                    sizeof(struct audio_profile));
9077             ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
9078                     mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
9079                             mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
9080             modifySurroundChannelMasks(&channels);
9081             std::copy(channels.begin(), channels.end(),
9082                       std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
9083             mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
9084         }
9085         mixPort.num_audio_profiles = modifiedNumProfiles;
9086     }
9087     profile->importAudioPort(mixPort);
9088 }
9089 
installPatch(const char * caller,audio_patch_handle_t * patchHandle,AudioIODescriptorInterface * ioDescriptor,const struct audio_patch * patch,int delayMs)9090 status_t AudioPolicyManager::installPatch(const char *caller,
9091                                           audio_patch_handle_t *patchHandle,
9092                                           AudioIODescriptorInterface *ioDescriptor,
9093                                           const struct audio_patch *patch,
9094                                           int delayMs)
9095 {
9096     ssize_t index = mAudioPatches.indexOfKey(
9097             patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
9098             *patchHandle : ioDescriptor->getPatchHandle());
9099     sp<AudioPatch> patchDesc;
9100     status_t status = installPatch(
9101             caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
9102     if (status == NO_ERROR) {
9103         ioDescriptor->setPatchHandle(patchDesc->getHandle());
9104     }
9105     return status;
9106 }
9107 
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)9108 status_t AudioPolicyManager::installPatch(const char *caller,
9109                                           ssize_t index,
9110                                           audio_patch_handle_t *patchHandle,
9111                                           const struct audio_patch *patch,
9112                                           int delayMs,
9113                                           uid_t uid,
9114                                           sp<AudioPatch> *patchDescPtr)
9115 {
9116     sp<AudioPatch> patchDesc;
9117     audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
9118     if (index >= 0) {
9119         patchDesc = mAudioPatches.valueAt(index);
9120         afPatchHandle = patchDesc->getAfHandle();
9121     }
9122 
9123     status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
9124     ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
9125             caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
9126     if (status == NO_ERROR) {
9127         if (index < 0) {
9128             patchDesc = new AudioPatch(patch, uid);
9129             addAudioPatch(patchDesc->getHandle(), patchDesc);
9130         } else {
9131             patchDesc->mPatch = *patch;
9132         }
9133         patchDesc->setAfHandle(afPatchHandle);
9134         if (patchHandle) {
9135             *patchHandle = patchDesc->getHandle();
9136         }
9137         nextAudioPortGeneration();
9138         mpClientInterface->onAudioPatchListUpdate();
9139     }
9140     if (patchDescPtr) *patchDescPtr = patchDesc;
9141     return status;
9142 }
9143 
areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor> & output)9144 bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9145 {
9146     const TrackClientVector activeClients = output->getActiveClients();
9147     if (activeClients.empty()) {
9148         return true;
9149     }
9150     ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9151     if (index < 0) {
9152         ALOGE("%s, no audio patch found while there are active clients on output %d",
9153                 __func__, output->getId());
9154         return false;
9155     }
9156     sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9157     DeviceVector routedDevices;
9158     for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9159         sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9160                 patchDesc->mPatch.sinks[i].id);
9161         if (device == nullptr) {
9162             ALOGE("%s, no audio device found with id(%d)",
9163                     __func__, patchDesc->mPatch.sinks[i].id);
9164             return false;
9165         }
9166         routedDevices.add(device);
9167     }
9168     for (const auto& client : activeClients) {
9169         if (client->isInvalid()) {
9170             // No need to take care about invalidated clients.
9171             continue;
9172         }
9173         sp<DeviceDescriptor> preferredDevice =
9174                 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9175         if (mEngine->getOutputDevicesForAttributes(
9176                 client->attributes(), preferredDevice, false) == routedDevices) {
9177             return false;
9178         }
9179     }
9180     return true;
9181 }
9182 
openOutputWithProfileAndDevice(const sp<IOProfile> & profile,const DeviceVector & devices,const audio_config_base_t * mixerConfig,const audio_config_t * halConfig,audio_output_flags_t flags)9183 sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
9184         const sp<IOProfile>& profile, const DeviceVector& devices,
9185         const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9186         audio_output_flags_t flags)
9187 {
9188     for (const auto& device : devices) {
9189         // TODO: This should be checking if the profile supports the device combo.
9190         if (!profile->supportsDevice(device)) {
9191             ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9192                   device->type());
9193             return nullptr;
9194         }
9195     }
9196     sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9197     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
9198     audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
9199     status_t status = desc->open(halConfig, mixerConfig, devices,
9200             AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
9201     if (status != NO_ERROR) {
9202         ALOGE("%s failed to open output %d", __func__, status);
9203         return nullptr;
9204     }
9205     if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9206         auto portConfig = desc->getConfig();
9207         for (const auto& device : devices) {
9208             device->setPreferredConfig(&portConfig);
9209         }
9210     }
9211 
9212     // Here is where the out_set_parameters() for card & device gets called
9213     sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9214     const audio_devices_t deviceType = device->type();
9215     const String8 &address = String8(device->address().c_str());
9216     if (!address.empty()) {
9217         char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9218         mpClientInterface->setParameters(output, String8(param));
9219         free(param);
9220     }
9221     updateAudioProfiles(device, output, profile);
9222     if (!profile->hasValidAudioProfile()) {
9223         ALOGW("%s() missing param", __func__);
9224         desc->close();
9225         return nullptr;
9226     } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9227         // Reopen the output with the best audio profile picked by APM when the profile supports
9228         // dynamic audio profile and the hal config is not specified.
9229         desc->close();
9230         output = AUDIO_IO_HANDLE_NONE;
9231         audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9232         profile->pickAudioProfile(
9233                 config.sample_rate, config.channel_mask, config.format);
9234         config.offload_info.sample_rate = config.sample_rate;
9235         config.offload_info.channel_mask = config.channel_mask;
9236         config.offload_info.format = config.format;
9237 
9238         status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
9239                             attributes);
9240         if (status != NO_ERROR) {
9241             return nullptr;
9242         }
9243     }
9244 
9245     addOutput(output, desc);
9246     // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9247     if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9248             hwModule->getHalVersionMajor() >= 3) {
9249         setOutputDevices(__func__, desc, devices, true, 0, NULL);
9250     }
9251     sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9252             AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9253 
9254     if (audio_is_remote_submix_device(deviceType) && address != "0") {
9255         sp<AudioPolicyMix> policyMix;
9256         if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9257             policyMix->setOutput(desc);
9258             desc->mPolicyMix = policyMix;
9259         } else {
9260             ALOGW("checkOutputsForDevice() cannot find policy for address %s",
9261                     address.c_str());
9262         }
9263 
9264     } else if (hasPrimaryOutput() && speaker != nullptr
9265             && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
9266             && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9267         // no duplicated output for:
9268         // - direct outputs
9269         // - outputs used by dynamic policy mixes
9270         // - outputs that supports SPEAKER while the primary output does not.
9271         audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9272 
9273         //TODO: configure audio effect output stage here
9274 
9275         // open a duplicating output thread for the new output and the primary output
9276         sp<SwAudioOutputDescriptor> dupOutputDesc =
9277                 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9278         status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9279         if (status == NO_ERROR) {
9280             // add duplicated output descriptor
9281             addOutput(duplicatedOutput, dupOutputDesc);
9282         } else {
9283             ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9284                   mPrimaryOutput->mIoHandle, output);
9285             desc->close();
9286             removeOutput(output);
9287             nextAudioPortGeneration();
9288             return nullptr;
9289         }
9290     }
9291     if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9292         ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9293         mPrimaryOutput = desc;
9294         mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
9295     }
9296     return desc;
9297 }
9298 
getDevicesForAttributes(const audio_attributes_t & attr,DeviceVector & devices,bool forVolume)9299 status_t AudioPolicyManager::getDevicesForAttributes(
9300         const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
9301     // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9302     // over any usage or content type also present in attr.
9303     if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9304         attr.source != AUDIO_SOURCE_INVALID) {
9305         return getInputDevicesForAttributes(attr, devices);
9306     }
9307 
9308     // Devices are determined in the following precedence:
9309     //
9310     // 1) Devices associated with a dynamic policy matching the attributes.  This is often
9311     //    a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9312     //
9313     // If no such dynamic policy then
9314     // 2) Devices containing an active client using setPreferredDevice
9315     //    with same strategy as the attributes.
9316     //    (from the default Engine::getOutputDevicesForAttributes() implementation).
9317     //
9318     // If no corresponding active client with setPreferredDevice then
9319     // 3) Devices associated with the strategy determined by the attributes
9320     //    (from the default Engine::getOutputDevicesForAttributes() implementation).
9321     //
9322     // See related getOutputForAttrInt().
9323 
9324     // check dynamic policies but only for primary descriptors (secondary not used for audible
9325     // audio routing, only used for duplication for playback capture)
9326     sp<AudioPolicyMix> policyMix;
9327     bool unneededUsePrimaryOutputFromPolicyMixes = false;
9328     status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
9329             0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9330             mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9331             nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
9332     if (status != OK) {
9333         return status;
9334     }
9335 
9336     if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9337             // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9338             // as they are unaffected by device/stream volume
9339             // (per SwAudioOutputDescriptor::isFixedVolume()).
9340             (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9341             ) {
9342         sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9343                 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9344         devices.add(deviceDesc);
9345     } else {
9346         // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9347         // which selects setPreferredDevice if active.  This means forVolume call
9348         // will take an active setPreferredDevice, if such exists.
9349 
9350         devices = mEngine->getOutputDevicesForAttributes(
9351                 attr, nullptr /* preferredDevice */, false /* fromCache */);
9352     }
9353 
9354     if (forVolume) {
9355         // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9356         // for single volume control in AudioService (such relationship should exist if
9357         // SPEAKER_SAFE is present).
9358         //
9359         // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9360         DeviceVector speakerSafeDevices =
9361                 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9362         if (!speakerSafeDevices.isEmpty()) {
9363             devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9364             devices.remove(speakerSafeDevices);
9365         }
9366     }
9367 
9368     return NO_ERROR;
9369 }
9370 
getInputDevicesForAttributes(const audio_attributes_t & attr,DeviceVector & devices)9371 status_t AudioPolicyManager::getInputDevicesForAttributes(
9372         const audio_attributes_t &attr, DeviceVector &devices) {
9373     devices = DeviceVector(mEngine->getInputDeviceForAttributes(attr));
9374     return NO_ERROR;
9375 }
9376 
getProfilesForDevices(const DeviceVector & devices,AudioProfileVector & audioProfiles,uint32_t flags,bool isInput)9377 status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9378                                                    AudioProfileVector& audioProfiles,
9379                                                    uint32_t flags,
9380                                                    bool isInput) {
9381     for (const auto& hwModule : mHwModules) {
9382         // the MSD module checks for different conditions
9383         if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9384             continue;
9385         }
9386         IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9387                                                  : hwModule->getOutputProfiles();
9388         for (const auto& profile : ioProfiles) {
9389             if (!profile->areAllDevicesSupported(devices) ||
9390                     !profile->isCompatibleProfileForFlags(flags)) {
9391                 continue;
9392             }
9393             audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9394         }
9395     }
9396 
9397     if (!isInput) {
9398         // add the direct profiles from MSD if present and has audio patches to all the output(s)
9399         const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9400         if (msdModule != nullptr) {
9401             if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9402                 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9403                 for (const auto &profile: msdModule->getOutputProfiles()) {
9404                     if (!profile->asAudioPort()->isDirectOutput()) {
9405                         continue;
9406                     }
9407                     audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9408                 }
9409             } else {
9410                 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9411             }
9412         }
9413     }
9414 
9415     return NO_ERROR;
9416 }
9417 
reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,const audio_config_t * config,audio_output_flags_t flags,const char * caller)9418 sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9419                                                              const audio_config_t *config,
9420                                                              audio_output_flags_t flags,
9421                                                              const char* caller) {
9422     closeOutput(outputDesc->mIoHandle);
9423     sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9424             outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9425     if (preferredOutput == nullptr) {
9426         ALOGE("%s failed to reopen output device=%d, caller=%s",
9427               __func__, outputDesc->devices()[0]->getId(), caller);
9428     }
9429     return preferredOutput;
9430 }
9431 
reopenOutputsWithDevices(const std::map<audio_io_handle_t,DeviceVector> & outputsToReopen)9432 void AudioPolicyManager::reopenOutputsWithDevices(
9433         const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9434     for (const auto& [output, devices] : outputsToReopen) {
9435         sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9436         closeOutput(output);
9437         openOutputWithProfileAndDevice(desc->mProfile, devices);
9438     }
9439 }
9440 
getClientsForStream(audio_stream_type_t streamType) const9441 PortHandleVector AudioPolicyManager::getClientsForStream(
9442         audio_stream_type_t streamType) const {
9443     PortHandleVector clients;
9444     for (size_t i = 0; i < mOutputs.size(); ++i) {
9445         PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9446         clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9447     }
9448     return clients;
9449 }
9450 
invalidateStreams(StreamTypeVector streams) const9451 void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9452     PortHandleVector clients;
9453     for (auto stream : streams) {
9454         PortHandleVector clientsForStream = getClientsForStream(stream);
9455         clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9456     }
9457     mpClientInterface->invalidateTracks(clients);
9458 }
9459 
updateClientsInternalMute(const sp<android::SwAudioOutputDescriptor> & desc)9460 void AudioPolicyManager::updateClientsInternalMute(
9461         const sp<android::SwAudioOutputDescriptor> &desc) {
9462     if (!desc->isBitPerfect() ||
9463         !com::android::media::audioserver::
9464                 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9465         // This is only used for bit perfect output now.
9466         return;
9467     }
9468     sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9469     bool bitPerfectClientInternalMute = false;
9470     std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9471     for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9472         if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9473             bitPerfectClient = client;
9474             continue;
9475         }
9476         bool muted = false;
9477         if (client->stream() == AUDIO_STREAM_SYSTEM) {
9478             // System sound is muted.
9479             muted = true;
9480         } else {
9481             bitPerfectClientInternalMute = true;
9482         }
9483         if (client->setInternalMute(muted)) {
9484             auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9485             if (!result.ok()) {
9486                 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9487                 continue;
9488             }
9489             media::TrackInternalMuteInfo info;
9490             info.portId = result.value();
9491             info.muted = client->getInternalMute();
9492             clientsInternalMute.push_back(std::move(info));
9493         }
9494     }
9495     if (bitPerfectClient != nullptr &&
9496         bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9497         auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9498         if (result.ok()) {
9499             media::TrackInternalMuteInfo info;
9500             info.portId = result.value();
9501             info.muted = bitPerfectClient->getInternalMute();
9502             clientsInternalMute.push_back(std::move(info));
9503         } else {
9504             ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9505                   __func__, bitPerfectClient->portId());
9506         }
9507     }
9508     if (!clientsInternalMute.empty()) {
9509         if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9510                 status != NO_ERROR) {
9511             ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9512         }
9513     }
9514 }
9515 
getMmapPolicyInfos(AudioMMapPolicyType policyType,std::vector<AudioMMapPolicyInfo> * policyInfos)9516 status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9517                                                 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9518     if (policyType != AudioMMapPolicyType::DEFAULT &&
9519         policyType != AudioMMapPolicyType::EXCLUSIVE) {
9520         return BAD_VALUE;
9521     }
9522     if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9523         if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9524             return status;
9525         }
9526     }
9527     *policyInfos = mMmapPolicyInfos[policyType];
9528     return NO_ERROR;
9529 }
9530 
getMmapPolicyForDevice(AudioMMapPolicyType policyType,AudioMMapPolicyInfo * policyInfo)9531 status_t AudioPolicyManager::getMmapPolicyForDevice(
9532         AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9533     if (policyType != AudioMMapPolicyType::DEFAULT &&
9534         policyType != AudioMMapPolicyType::EXCLUSIVE) {
9535         return BAD_VALUE;
9536     }
9537     if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9538         if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9539             return status;
9540         }
9541     }
9542     auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9543     policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9544             ? AudioMMapPolicy::NEVER : it->second;
9545     return NO_ERROR;
9546 }
9547 
updateMmapPolicyInfos(AudioMMapPolicyType policyType)9548 status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9549     std::vector<AudioMMapPolicyInfo> policyInfos;
9550     if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9551         status != NO_ERROR) {
9552         ALOGE("%s, failed, error = %d", __func__, status);
9553         return status;
9554     }
9555     std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9556     if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9557         // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9558         // it indicates the mmap policy is reported via system property. In that case, use the
9559         // routing information to fill details for how mmap is supported for a particular device.
9560         for (const auto &hwModule: mHwModules) {
9561             for (const auto &profile: hwModule->getInputProfiles()) {
9562                 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9563                     != AUDIO_INPUT_FLAG_MMAP_NOIRQ) {
9564                     continue;
9565                 }
9566                 for (const auto &device: profile->getSupportedDevices()) {
9567                     auto deviceDesc =
9568                             legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9569                     if (deviceDesc.ok()) {
9570                         mmapPolicyByDeviceType.emplace(
9571                                 deviceDesc.value(), policyInfos[0].mmapPolicy);
9572                     }
9573                 }
9574             }
9575             for (const auto &profile: hwModule->getOutputProfiles()) {
9576                 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9577                     != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9578                     continue;
9579                 }
9580                 for (const auto &device: profile->getSupportedDevices()) {
9581                     auto deviceDesc =
9582                             legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9583                     if (deviceDesc.ok()) {
9584                         mmapPolicyByDeviceType.emplace(
9585                                 deviceDesc.value(), policyInfos[0].mmapPolicy);
9586                     }
9587                 }
9588             }
9589         }
9590     } else {
9591         for (const auto &info: policyInfos) {
9592             mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9593         }
9594     }
9595     mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9596     mMmapPolicyInfos.emplace(policyType, policyInfos);
9597     return NO_ERROR;
9598 }
9599 
9600 } // namespace android
9601