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