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