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