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