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 "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 // A device mask for all audio input devices that are considered "virtual" when evaluating
28 // active inputs in getActiveInput()
29 #define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL  (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
30 // A device mask for all audio output devices that are considered "remote" when evaluating
31 // active output devices in isStreamActiveRemotely()
32 #define APM_AUDIO_OUT_DEVICE_REMOTE_ALL  AUDIO_DEVICE_OUT_REMOTE_SUBMIX
33 // A device mask for all audio input and output devices where matching inputs/outputs on device
34 // type alone is not enough: the address must match too
35 #define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36                                             AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
37 
38 #include <inttypes.h>
39 #include <math.h>
40 
41 #include <cutils/properties.h>
42 #include <utils/Log.h>
43 #include <hardware/audio.h>
44 #include <hardware/audio_effect.h>
45 #include <media/AudioParameter.h>
46 #include <media/AudioPolicyHelper.h>
47 #include <soundtrigger/SoundTrigger.h>
48 #include "AudioPolicyManager.h"
49 #include "audio_policy_conf.h"
50 
51 namespace android {
52 
53 // ----------------------------------------------------------------------------
54 // Definitions for audio_policy.conf file parsing
55 // ----------------------------------------------------------------------------
56 
57 struct StringToEnum {
58     const char *name;
59     uint32_t value;
60 };
61 
62 #define STRING_TO_ENUM(string) { #string, string }
63 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64 
65 const StringToEnum sDeviceNameToEnumTable[] = {
66     STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67     STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
68     STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
69     STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70     STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71     STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72     STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73     STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75     STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76     STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77     STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79     STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
80     STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
81     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82     STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83     STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84     STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86     STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
87     STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88     STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89     STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90     STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91     STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
92     STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
93     STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
94     STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95     STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96     STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97     STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98     STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
99     STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
100     STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
101     STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
102     STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103     STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104     STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105     STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106     STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
107     STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
108     STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109     STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110     STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111     STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
112     STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
113     STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
114 };
115 
116 const StringToEnum sOutputFlagNameToEnumTable[] = {
117     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
123     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
124 };
125 
126 const StringToEnum sInputFlagNameToEnumTable[] = {
127     STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128     STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129 };
130 
131 const StringToEnum sFormatNameToEnumTable[] = {
132     STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133     STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134     STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135     STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136     STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137     STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138     STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139     STRING_TO_ENUM(AUDIO_FORMAT_AAC),
140     STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141     STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142     STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143     STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144     STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145     STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146     STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147     STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148     STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149     STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
150     STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
151     STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152     STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153     STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154     STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155     STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
156 };
157 
158 const StringToEnum sOutChannelsNameToEnumTable[] = {
159     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
161     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
162     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164 };
165 
166 const StringToEnum sInChannelsNameToEnumTable[] = {
167     STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168     STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169     STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170 };
171 
172 const StringToEnum sGainModeNameToEnumTable[] = {
173     STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174     STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175     STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176 };
177 
178 
stringToEnum(const struct StringToEnum * table,size_t size,const char * name)179 uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180                                               size_t size,
181                                               const char *name)
182 {
183     for (size_t i = 0; i < size; i++) {
184         if (strcmp(table[i].name, name) == 0) {
185             ALOGV("stringToEnum() found %s", table[i].name);
186             return table[i].value;
187         }
188     }
189     return 0;
190 }
191 
enumToString(const struct StringToEnum * table,size_t size,uint32_t value)192 const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193                                               size_t size,
194                                               uint32_t value)
195 {
196     for (size_t i = 0; i < size; i++) {
197         if (table[i].value == value) {
198             return table[i].name;
199         }
200     }
201     return "";
202 }
203 
stringToBool(const char * value)204 bool AudioPolicyManager::stringToBool(const char *value)
205 {
206     return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207 }
208 
209 
210 // ----------------------------------------------------------------------------
211 // AudioPolicyInterface implementation
212 // ----------------------------------------------------------------------------
213 
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address)214 status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
215                                                           audio_policy_dev_state_t state,
216                                                   const char *device_address)
217 {
218     return setDeviceConnectionStateInt(device, state, device_address);
219 }
220 
setDeviceConnectionStateInt(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address)221 status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
222                                                          audio_policy_dev_state_t state,
223                                                          const char *device_address)
224 {
225     ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
226             device, state, device_address != NULL ? device_address : "");
227 
228     // connect/disconnect only 1 device at a time
229     if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
230 
231     sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address);
232 
233     // handle output devices
234     if (audio_is_output_device(device)) {
235         SortedVector <audio_io_handle_t> outputs;
236 
237         ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
238 
239         // save a copy of the opened output descriptors before any output is opened or closed
240         // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
241         mPreviousOutputs = mOutputs;
242         switch (state)
243         {
244         // handle output device connection
245         case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
246             if (index >= 0) {
247                 ALOGW("setDeviceConnectionState() device already connected: %x", device);
248                 return INVALID_OPERATION;
249             }
250             ALOGV("setDeviceConnectionState() connecting device %x", device);
251 
252             // register new device as available
253             index = mAvailableOutputDevices.add(devDesc);
254             if (index >= 0) {
255                 sp<HwModule> module = getModuleForDevice(device);
256                 if (module == 0) {
257                     ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
258                           device);
259                     mAvailableOutputDevices.remove(devDesc);
260                     return INVALID_OPERATION;
261                 }
262                 mAvailableOutputDevices[index]->mId = nextUniqueId();
263                 mAvailableOutputDevices[index]->mModule = module;
264             } else {
265                 return NO_MEMORY;
266             }
267 
268             if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
269                 mAvailableOutputDevices.remove(devDesc);
270                 return INVALID_OPERATION;
271             }
272             // outputs should never be empty here
273             ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
274                     "checkOutputsForDevice() returned no outputs but status OK");
275             ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
276                   outputs.size());
277 
278 
279             // Set connect to HALs
280             AudioParameter param = AudioParameter(devDesc->mAddress);
281             param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
282             mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
283 
284             } break;
285         // handle output device disconnection
286         case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
287             if (index < 0) {
288                 ALOGW("setDeviceConnectionState() device not connected: %x", device);
289                 return INVALID_OPERATION;
290             }
291 
292             ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
293 
294             // Set Disconnect to HALs
295             AudioParameter param = AudioParameter(devDesc->mAddress);
296             param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
297             mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
298 
299             // remove device from available output devices
300             mAvailableOutputDevices.remove(devDesc);
301 
302             checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
303             } break;
304 
305         default:
306             ALOGE("setDeviceConnectionState() invalid state: %x", state);
307             return BAD_VALUE;
308         }
309 
310         // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
311         // output is suspended before any tracks are moved to it
312         checkA2dpSuspend();
313         checkOutputForAllStrategies();
314         // outputs must be closed after checkOutputForAllStrategies() is executed
315         if (!outputs.isEmpty()) {
316             for (size_t i = 0; i < outputs.size(); i++) {
317                 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
318                 // close unused outputs after device disconnection or direct outputs that have been
319                 // opened by checkOutputsForDevice() to query dynamic parameters
320                 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
321                         (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
322                          (desc->mDirectOpenCount == 0))) {
323                     closeOutput(outputs[i]);
324                 }
325             }
326             // check again after closing A2DP output to reset mA2dpSuspended if needed
327             checkA2dpSuspend();
328         }
329 
330         updateDevicesAndOutputs();
331         if (mPhoneState == AUDIO_MODE_IN_CALL) {
332             audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
333             updateCallRouting(newDevice);
334         }
335         for (size_t i = 0; i < mOutputs.size(); i++) {
336             audio_io_handle_t output = mOutputs.keyAt(i);
337             if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
338                 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
339                                                                true /*fromCache*/);
340                 // do not force device change on duplicated output because if device is 0, it will
341                 // also force a device 0 for the two outputs it is duplicated to which may override
342                 // a valid device selection on those outputs.
343                 bool force = !mOutputs.valueAt(i)->isDuplicated()
344                         && (!deviceDistinguishesOnAddress(device)
345                                 // always force when disconnecting (a non-duplicated device)
346                                 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
347                 setOutputDevice(output, newDevice, force, 0);
348             }
349         }
350 
351         mpClientInterface->onAudioPortListUpdate();
352         return NO_ERROR;
353     }  // end if is output device
354 
355     // handle input devices
356     if (audio_is_input_device(device)) {
357         SortedVector <audio_io_handle_t> inputs;
358 
359         ssize_t index = mAvailableInputDevices.indexOf(devDesc);
360         switch (state)
361         {
362         // handle input device connection
363         case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
364             if (index >= 0) {
365                 ALOGW("setDeviceConnectionState() device already connected: %d", device);
366                 return INVALID_OPERATION;
367             }
368             sp<HwModule> module = getModuleForDevice(device);
369             if (module == NULL) {
370                 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
371                       device);
372                 return INVALID_OPERATION;
373             }
374             if (checkInputsForDevice(device, state, inputs, devDesc->mAddress) != NO_ERROR) {
375                 return INVALID_OPERATION;
376             }
377 
378             index = mAvailableInputDevices.add(devDesc);
379             if (index >= 0) {
380                 mAvailableInputDevices[index]->mId = nextUniqueId();
381                 mAvailableInputDevices[index]->mModule = module;
382             } else {
383                 return NO_MEMORY;
384             }
385 
386             // Set connect to HALs
387             AudioParameter param = AudioParameter(devDesc->mAddress);
388             param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
389             mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
390 
391         } break;
392 
393         // handle input device disconnection
394         case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
395             if (index < 0) {
396                 ALOGW("setDeviceConnectionState() device not connected: %d", device);
397                 return INVALID_OPERATION;
398             }
399 
400             ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
401 
402             // Set Disconnect to HALs
403             AudioParameter param = AudioParameter(devDesc->mAddress);
404             param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
405             mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
406 
407             checkInputsForDevice(device, state, inputs, devDesc->mAddress);
408             mAvailableInputDevices.remove(devDesc);
409 
410         } break;
411 
412         default:
413             ALOGE("setDeviceConnectionState() invalid state: %x", state);
414             return BAD_VALUE;
415         }
416 
417         closeAllInputs();
418 
419         if (mPhoneState == AUDIO_MODE_IN_CALL) {
420             audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
421             updateCallRouting(newDevice);
422         }
423 
424         mpClientInterface->onAudioPortListUpdate();
425         return NO_ERROR;
426     } // end if is input device
427 
428     ALOGW("setDeviceConnectionState() invalid device: %x", device);
429     return BAD_VALUE;
430 }
431 
getDeviceConnectionState(audio_devices_t device,const char * device_address)432 audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
433                                                   const char *device_address)
434 {
435     sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address);
436     DeviceVector *deviceVector;
437 
438     if (audio_is_output_device(device)) {
439         deviceVector = &mAvailableOutputDevices;
440     } else if (audio_is_input_device(device)) {
441         deviceVector = &mAvailableInputDevices;
442     } else {
443         ALOGW("getDeviceConnectionState() invalid device type %08x", device);
444         return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
445     }
446 
447     ssize_t index = deviceVector->indexOf(devDesc);
448     if (index >= 0) {
449         return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
450     } else {
451         return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
452     }
453 }
454 
getDeviceDescriptor(const audio_devices_t device,const char * device_address)455 sp<AudioPolicyManager::DeviceDescriptor>  AudioPolicyManager::getDeviceDescriptor(
456                                                                     const audio_devices_t device,
457                                                                     const char *device_address)
458 {
459     String8 address = (device_address == NULL) ? String8("") : String8(device_address);
460     // handle legacy remote submix case where the address was not always specified
461     if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
462         address = String8("0");
463     }
464 
465     for (size_t i = 0; i < mHwModules.size(); i++) {
466         if (mHwModules[i]->mHandle == 0) {
467             continue;
468         }
469         DeviceVector deviceList =
470                 mHwModules[i]->mDeclaredDevices.getDevicesFromTypeAddr(device, address);
471         if (!deviceList.isEmpty()) {
472             return deviceList.itemAt(0);
473         }
474         deviceList = mHwModules[i]->mDeclaredDevices.getDevicesFromType(device);
475         if (!deviceList.isEmpty()) {
476             return deviceList.itemAt(0);
477         }
478     }
479 
480     sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
481     devDesc->mAddress = address;
482     return devDesc;
483 }
484 
updateCallRouting(audio_devices_t rxDevice,int delayMs)485 void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
486 {
487     bool createTxPatch = false;
488     struct audio_patch patch;
489     patch.num_sources = 1;
490     patch.num_sinks = 1;
491     status_t status;
492     audio_patch_handle_t afPatchHandle;
493     DeviceVector deviceList;
494 
495     audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
496     ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
497 
498     // release existing RX patch if any
499     if (mCallRxPatch != 0) {
500         mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
501         mCallRxPatch.clear();
502     }
503     // release TX patch if any
504     if (mCallTxPatch != 0) {
505         mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
506         mCallTxPatch.clear();
507     }
508 
509     // If the RX device is on the primary HW module, then use legacy routing method for voice calls
510     // via setOutputDevice() on primary output.
511     // Otherwise, create two audio patches for TX and RX path.
512     if (availablePrimaryOutputDevices() & rxDevice) {
513         setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
514         // If the TX device is also on the primary HW module, setOutputDevice() will take care
515         // of it due to legacy implementation. If not, create a patch.
516         if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
517                 == AUDIO_DEVICE_NONE) {
518             createTxPatch = true;
519         }
520     } else {
521         // create RX path audio patch
522         deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
523         ALOG_ASSERT(!deviceList.isEmpty(),
524                     "updateCallRouting() selected device not in output device list");
525         sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
526         deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
527         ALOG_ASSERT(!deviceList.isEmpty(),
528                     "updateCallRouting() no telephony RX device");
529         sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
530 
531         rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
532         rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
533 
534         // request to reuse existing output stream if one is already opened to reach the RX device
535         SortedVector<audio_io_handle_t> outputs =
536                                 getOutputsForDevice(rxDevice, mOutputs);
537         audio_io_handle_t output = selectOutput(outputs,
538                                                 AUDIO_OUTPUT_FLAG_NONE,
539                                                 AUDIO_FORMAT_INVALID);
540         if (output != AUDIO_IO_HANDLE_NONE) {
541             sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
542             ALOG_ASSERT(!outputDesc->isDuplicated(),
543                         "updateCallRouting() RX device output is duplicated");
544             outputDesc->toAudioPortConfig(&patch.sources[1]);
545             patch.num_sources = 2;
546         }
547 
548         afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
549         status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
550         ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
551                                                status);
552         if (status == NO_ERROR) {
553             mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
554                                        &patch, mUidCached);
555             mCallRxPatch->mAfPatchHandle = afPatchHandle;
556             mCallRxPatch->mUid = mUidCached;
557         }
558         createTxPatch = true;
559     }
560     if (createTxPatch) {
561 
562         struct audio_patch patch;
563         patch.num_sources = 1;
564         patch.num_sinks = 1;
565         deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
566         ALOG_ASSERT(!deviceList.isEmpty(),
567                     "updateCallRouting() selected device not in input device list");
568         sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
569         txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
570         deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
571         ALOG_ASSERT(!deviceList.isEmpty(),
572                     "updateCallRouting() no telephony TX device");
573         sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
574         txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
575 
576         SortedVector<audio_io_handle_t> outputs =
577                                 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
578         audio_io_handle_t output = selectOutput(outputs,
579                                                 AUDIO_OUTPUT_FLAG_NONE,
580                                                 AUDIO_FORMAT_INVALID);
581         // request to reuse existing output stream if one is already opened to reach the TX
582         // path output device
583         if (output != AUDIO_IO_HANDLE_NONE) {
584             sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
585             ALOG_ASSERT(!outputDesc->isDuplicated(),
586                         "updateCallRouting() RX device output is duplicated");
587             outputDesc->toAudioPortConfig(&patch.sources[1]);
588             patch.num_sources = 2;
589         }
590 
591         afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
592         status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
593         ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
594                                                status);
595         if (status == NO_ERROR) {
596             mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
597                                        &patch, mUidCached);
598             mCallTxPatch->mAfPatchHandle = afPatchHandle;
599             mCallTxPatch->mUid = mUidCached;
600         }
601     }
602 }
603 
setPhoneState(audio_mode_t state)604 void AudioPolicyManager::setPhoneState(audio_mode_t state)
605 {
606     ALOGV("setPhoneState() state %d", state);
607     if (state < 0 || state >= AUDIO_MODE_CNT) {
608         ALOGW("setPhoneState() invalid state %d", state);
609         return;
610     }
611 
612     if (state == mPhoneState ) {
613         ALOGW("setPhoneState() setting same state %d", state);
614         return;
615     }
616 
617     // if leaving call state, handle special case of active streams
618     // pertaining to sonification strategy see handleIncallSonification()
619     if (isInCall()) {
620         ALOGV("setPhoneState() in call state management: new state is %d", state);
621         for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
622             if (stream == AUDIO_STREAM_PATCH) {
623                 continue;
624             }
625             handleIncallSonification((audio_stream_type_t)stream, false, true);
626         }
627 
628         // force reevaluating accessibility routing when call starts
629         mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
630     }
631 
632     // store previous phone state for management of sonification strategy below
633     int oldState = mPhoneState;
634     mPhoneState = state;
635     bool force = false;
636 
637     // are we entering or starting a call
638     if (!isStateInCall(oldState) && isStateInCall(state)) {
639         ALOGV("  Entering call in setPhoneState()");
640         // force routing command to audio hardware when starting a call
641         // even if no device change is needed
642         force = true;
643         for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
644             mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
645                     sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
646         }
647     } else if (isStateInCall(oldState) && !isStateInCall(state)) {
648         ALOGV("  Exiting call in setPhoneState()");
649         // force routing command to audio hardware when exiting a call
650         // even if no device change is needed
651         force = true;
652         for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
653             mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
654                     sVolumeProfiles[AUDIO_STREAM_DTMF][j];
655         }
656     } else if (isStateInCall(state) && (state != oldState)) {
657         ALOGV("  Switching between telephony and VoIP in setPhoneState()");
658         // force routing command to audio hardware when switching between telephony and VoIP
659         // even if no device change is needed
660         force = true;
661     }
662 
663     // check for device and output changes triggered by new phone state
664     checkA2dpSuspend();
665     checkOutputForAllStrategies();
666     updateDevicesAndOutputs();
667 
668     sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
669 
670     int delayMs = 0;
671     if (isStateInCall(state)) {
672         nsecs_t sysTime = systemTime();
673         for (size_t i = 0; i < mOutputs.size(); i++) {
674             sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
675             // mute media and sonification strategies and delay device switch by the largest
676             // latency of any output where either strategy is active.
677             // This avoid sending the ring tone or music tail into the earpiece or headset.
678             if ((desc->isStrategyActive(STRATEGY_MEDIA,
679                                      SONIFICATION_HEADSET_MUSIC_DELAY,
680                                      sysTime) ||
681                     desc->isStrategyActive(STRATEGY_SONIFICATION,
682                                          SONIFICATION_HEADSET_MUSIC_DELAY,
683                                          sysTime)) &&
684                     (delayMs < (int)desc->mLatency*2)) {
685                 delayMs = desc->mLatency*2;
686             }
687             setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
688             setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
689                 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
690             setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
691             setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
692                 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
693         }
694     }
695 
696     // Note that despite the fact that getNewOutputDevice() is called on the primary output,
697     // the device returned is not necessarily reachable via this output
698     audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
699     // force routing command to audio hardware when ending call
700     // even if no device change is needed
701     if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
702         rxDevice = hwOutputDesc->device();
703     }
704 
705     if (state == AUDIO_MODE_IN_CALL) {
706         updateCallRouting(rxDevice, delayMs);
707     } else if (oldState == AUDIO_MODE_IN_CALL) {
708         if (mCallRxPatch != 0) {
709             mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
710             mCallRxPatch.clear();
711         }
712         if (mCallTxPatch != 0) {
713             mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
714             mCallTxPatch.clear();
715         }
716         setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
717     } else {
718         setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
719     }
720     // if entering in call state, handle special case of active streams
721     // pertaining to sonification strategy see handleIncallSonification()
722     if (isStateInCall(state)) {
723         ALOGV("setPhoneState() in call state management: new state is %d", state);
724         for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
725             if (stream == AUDIO_STREAM_PATCH) {
726                 continue;
727             }
728             handleIncallSonification((audio_stream_type_t)stream, true, true);
729         }
730     }
731 
732     // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
733     if (state == AUDIO_MODE_RINGTONE &&
734         isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
735         mLimitRingtoneVolume = true;
736     } else {
737         mLimitRingtoneVolume = false;
738     }
739 }
740 
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)741 void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
742                                          audio_policy_forced_cfg_t config)
743 {
744     ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
745 
746     bool forceVolumeReeval = false;
747     switch(usage) {
748     case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
749         if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
750             config != AUDIO_POLICY_FORCE_NONE) {
751             ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
752             return;
753         }
754         forceVolumeReeval = true;
755         mForceUse[usage] = config;
756         break;
757     case AUDIO_POLICY_FORCE_FOR_MEDIA:
758         if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
759             config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
760             config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
761             config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
762             config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
763             ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
764             return;
765         }
766         mForceUse[usage] = config;
767         break;
768     case AUDIO_POLICY_FORCE_FOR_RECORD:
769         if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
770             config != AUDIO_POLICY_FORCE_NONE) {
771             ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
772             return;
773         }
774         mForceUse[usage] = config;
775         break;
776     case AUDIO_POLICY_FORCE_FOR_DOCK:
777         if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
778             config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
779             config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
780             config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
781             config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
782             ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
783         }
784         forceVolumeReeval = true;
785         mForceUse[usage] = config;
786         break;
787     case AUDIO_POLICY_FORCE_FOR_SYSTEM:
788         if (config != AUDIO_POLICY_FORCE_NONE &&
789             config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
790             ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
791         }
792         forceVolumeReeval = true;
793         mForceUse[usage] = config;
794         break;
795     case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
796         if (config != AUDIO_POLICY_FORCE_NONE &&
797             config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
798             ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
799         }
800         mForceUse[usage] = config;
801         break;
802     default:
803         ALOGW("setForceUse() invalid usage %d", usage);
804         break;
805     }
806 
807     // check for device and output changes triggered by new force usage
808     checkA2dpSuspend();
809     checkOutputForAllStrategies();
810     updateDevicesAndOutputs();
811     if (mPhoneState == AUDIO_MODE_IN_CALL) {
812         audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
813         updateCallRouting(newDevice);
814     }
815     for (size_t i = 0; i < mOutputs.size(); i++) {
816         audio_io_handle_t output = mOutputs.keyAt(i);
817         audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
818         if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
819             setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
820         }
821         if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
822             applyStreamVolumes(output, newDevice, 0, true);
823         }
824     }
825 
826     audio_io_handle_t activeInput = getActiveInput();
827     if (activeInput != 0) {
828         setInputDevice(activeInput, getNewInputDevice(activeInput));
829     }
830 
831 }
832 
getForceUse(audio_policy_force_use_t usage)833 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
834 {
835     return mForceUse[usage];
836 }
837 
setSystemProperty(const char * property,const char * value)838 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
839 {
840     ALOGV("setSystemProperty() property %s, value %s", property, value);
841 }
842 
843 // Find a direct output profile compatible with the parameters passed, even if the input flags do
844 // 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)845 sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
846                                                                audio_devices_t device,
847                                                                uint32_t samplingRate,
848                                                                audio_format_t format,
849                                                                audio_channel_mask_t channelMask,
850                                                                audio_output_flags_t flags)
851 {
852     for (size_t i = 0; i < mHwModules.size(); i++) {
853         if (mHwModules[i]->mHandle == 0) {
854             continue;
855         }
856         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
857             sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
858             bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
859                     NULL /*updatedSamplingRate*/, format, channelMask,
860                     flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
861                         AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
862             if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
863                 return profile;
864             }
865         }
866     }
867     return 0;
868 }
869 
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)870 audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
871                                     uint32_t samplingRate,
872                                     audio_format_t format,
873                                     audio_channel_mask_t channelMask,
874                                     audio_output_flags_t flags,
875                                     const audio_offload_info_t *offloadInfo)
876 {
877     routing_strategy strategy = getStrategy(stream);
878     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
879     ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
880           device, stream, samplingRate, format, channelMask, flags);
881 
882     return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
883                               stream, samplingRate,format, channelMask,
884                               flags, offloadInfo);
885 }
886 
getOutputForAttr(const audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,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)887 status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
888                                               audio_io_handle_t *output,
889                                               audio_session_t session,
890                                               audio_stream_type_t *stream,
891                                               uint32_t samplingRate,
892                                               audio_format_t format,
893                                               audio_channel_mask_t channelMask,
894                                               audio_output_flags_t flags,
895                                               const audio_offload_info_t *offloadInfo)
896 {
897     audio_attributes_t attributes;
898     if (attr != NULL) {
899         if (!isValidAttributes(attr)) {
900             ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
901                   attr->usage, attr->content_type, attr->flags,
902                   attr->tags);
903             return BAD_VALUE;
904         }
905         attributes = *attr;
906     } else {
907         if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
908             ALOGE("getOutputForAttr():  invalid stream type");
909             return BAD_VALUE;
910         }
911         stream_type_to_audio_attributes(*stream, &attributes);
912     }
913 
914     for (size_t i = 0; i < mPolicyMixes.size(); i++) {
915         sp<AudioOutputDescriptor> desc;
916         if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
917             for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
918                 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
919                         mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
920                     (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
921                         mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
922                     desc = mPolicyMixes[i]->mOutput;
923                     break;
924                 }
925                 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
926                         strncmp(attributes.tags + strlen("addr="),
927                                 mPolicyMixes[i]->mMix.mRegistrationId.string(),
928                                 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
929                     desc = mPolicyMixes[i]->mOutput;
930                     break;
931                 }
932             }
933         } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
934             if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
935                     strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
936                     strncmp(attributes.tags + strlen("addr="),
937                             mPolicyMixes[i]->mMix.mRegistrationId.string(),
938                             AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
939                 desc = mPolicyMixes[i]->mOutput;
940             }
941         }
942         if (desc != 0) {
943             if (!audio_is_linear_pcm(format)) {
944                 return BAD_VALUE;
945             }
946             desc->mPolicyMix = &mPolicyMixes[i]->mMix;
947             *stream = streamTypefromAttributesInt(&attributes);
948             *output = desc->mIoHandle;
949             ALOGV("getOutputForAttr() returns output %d", *output);
950             return NO_ERROR;
951         }
952     }
953     if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
954         ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
955         return BAD_VALUE;
956     }
957 
958     ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
959             attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
960 
961     routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
962     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
963 
964     if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
965         flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
966     }
967 
968     ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
969           device, samplingRate, format, channelMask, flags);
970 
971     *stream = streamTypefromAttributesInt(&attributes);
972     *output = getOutputForDevice(device, session, *stream,
973                                  samplingRate, format, channelMask,
974                                  flags, offloadInfo);
975     if (*output == AUDIO_IO_HANDLE_NONE) {
976         return INVALID_OPERATION;
977     }
978     return NO_ERROR;
979 }
980 
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)981 audio_io_handle_t AudioPolicyManager::getOutputForDevice(
982         audio_devices_t device,
983         audio_session_t session __unused,
984         audio_stream_type_t stream,
985         uint32_t samplingRate,
986         audio_format_t format,
987         audio_channel_mask_t channelMask,
988         audio_output_flags_t flags,
989         const audio_offload_info_t *offloadInfo)
990 {
991     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
992     uint32_t latency = 0;
993     status_t status;
994 
995 #ifdef AUDIO_POLICY_TEST
996     if (mCurOutput != 0) {
997         ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
998                 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
999 
1000         if (mTestOutputs[mCurOutput] == 0) {
1001             ALOGV("getOutput() opening test output");
1002             sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
1003             outputDesc->mDevice = mTestDevice;
1004             outputDesc->mLatency = mTestLatencyMs;
1005             outputDesc->mFlags =
1006                     (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
1007             outputDesc->mRefCount[stream] = 0;
1008             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1009             config.sample_rate = mTestSamplingRate;
1010             config.channel_mask = mTestChannels;
1011             config.format = mTestFormat;
1012             if (offloadInfo != NULL) {
1013                 config.offload_info = *offloadInfo;
1014             }
1015             status = mpClientInterface->openOutput(0,
1016                                                   &mTestOutputs[mCurOutput],
1017                                                   &config,
1018                                                   &outputDesc->mDevice,
1019                                                   String8(""),
1020                                                   &outputDesc->mLatency,
1021                                                   outputDesc->mFlags);
1022             if (status == NO_ERROR) {
1023                 outputDesc->mSamplingRate = config.sample_rate;
1024                 outputDesc->mFormat = config.format;
1025                 outputDesc->mChannelMask = config.channel_mask;
1026                 AudioParameter outputCmd = AudioParameter();
1027                 outputCmd.addInt(String8("set_id"),mCurOutput);
1028                 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
1029                 addOutput(mTestOutputs[mCurOutput], outputDesc);
1030             }
1031         }
1032         return mTestOutputs[mCurOutput];
1033     }
1034 #endif //AUDIO_POLICY_TEST
1035 
1036     // open a direct output if required by specified parameters
1037     //force direct flag if offload flag is set: offloading implies a direct output stream
1038     // and all common behaviors are driven by checking only the direct flag
1039     // this should normally be set appropriately in the policy configuration file
1040     if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1041         flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1042     }
1043     if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1044         flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1045     }
1046     // only allow deep buffering for music stream type
1047     if (stream != AUDIO_STREAM_MUSIC) {
1048         flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1049     }
1050 
1051     sp<IOProfile> profile;
1052 
1053     // skip direct output selection if the request can obviously be attached to a mixed output
1054     // and not explicitly requested
1055     if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1056             audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
1057             audio_channel_count_from_out_mask(channelMask) <= 2) {
1058         goto non_direct_output;
1059     }
1060 
1061     // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1062     // creating an offloaded track and tearing it down immediately after start when audioflinger
1063     // detects there is an active non offloadable effect.
1064     // FIXME: We should check the audio session here but we do not have it in this context.
1065     // This may prevent offloading in rare situations where effects are left active by apps
1066     // in the background.
1067 
1068     if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1069             !isNonOffloadableEffectEnabled()) {
1070         profile = getProfileForDirectOutput(device,
1071                                            samplingRate,
1072                                            format,
1073                                            channelMask,
1074                                            (audio_output_flags_t)flags);
1075     }
1076 
1077     if (profile != 0) {
1078         sp<AudioOutputDescriptor> outputDesc = NULL;
1079 
1080         for (size_t i = 0; i < mOutputs.size(); i++) {
1081             sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1082             if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1083                 outputDesc = desc;
1084                 // reuse direct output if currently open and configured with same parameters
1085                 if ((samplingRate == outputDesc->mSamplingRate) &&
1086                         (format == outputDesc->mFormat) &&
1087                         (channelMask == outputDesc->mChannelMask)) {
1088                     outputDesc->mDirectOpenCount++;
1089                     ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1090                     return mOutputs.keyAt(i);
1091                 }
1092             }
1093         }
1094         // close direct output if currently open and configured with different parameters
1095         if (outputDesc != NULL) {
1096             closeOutput(outputDesc->mIoHandle);
1097         }
1098         outputDesc = new AudioOutputDescriptor(profile);
1099         outputDesc->mDevice = device;
1100         outputDesc->mLatency = 0;
1101         outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
1102         audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1103         config.sample_rate = samplingRate;
1104         config.channel_mask = channelMask;
1105         config.format = format;
1106         if (offloadInfo != NULL) {
1107             config.offload_info = *offloadInfo;
1108         }
1109         status = mpClientInterface->openOutput(profile->mModule->mHandle,
1110                                                &output,
1111                                                &config,
1112                                                &outputDesc->mDevice,
1113                                                String8(""),
1114                                                &outputDesc->mLatency,
1115                                                outputDesc->mFlags);
1116 
1117         // only accept an output with the requested parameters
1118         if (status != NO_ERROR ||
1119             (samplingRate != 0 && samplingRate != config.sample_rate) ||
1120             (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1121             (channelMask != 0 && channelMask != config.channel_mask)) {
1122             ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1123                     "format %d %d, channelMask %04x %04x", output, samplingRate,
1124                     outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1125                     outputDesc->mChannelMask);
1126             if (output != AUDIO_IO_HANDLE_NONE) {
1127                 mpClientInterface->closeOutput(output);
1128             }
1129             // fall back to mixer output if possible when the direct output could not be open
1130             if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
1131                 goto non_direct_output;
1132             }
1133             return AUDIO_IO_HANDLE_NONE;
1134         }
1135         outputDesc->mSamplingRate = config.sample_rate;
1136         outputDesc->mChannelMask = config.channel_mask;
1137         outputDesc->mFormat = config.format;
1138         outputDesc->mRefCount[stream] = 0;
1139         outputDesc->mStopTime[stream] = 0;
1140         outputDesc->mDirectOpenCount = 1;
1141 
1142         audio_io_handle_t srcOutput = getOutputForEffect();
1143         addOutput(output, outputDesc);
1144         audio_io_handle_t dstOutput = getOutputForEffect();
1145         if (dstOutput == output) {
1146             mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1147         }
1148         mPreviousOutputs = mOutputs;
1149         ALOGV("getOutput() returns new direct output %d", output);
1150         mpClientInterface->onAudioPortListUpdate();
1151         return output;
1152     }
1153 
1154 non_direct_output:
1155 
1156     // ignoring channel mask due to downmix capability in mixer
1157 
1158     // open a non direct output
1159 
1160     // for non direct outputs, only PCM is supported
1161     if (audio_is_linear_pcm(format)) {
1162         // get which output is suitable for the specified stream. The actual
1163         // routing change will happen when startOutput() will be called
1164         SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1165 
1166         // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1167         flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1168         output = selectOutput(outputs, flags, format);
1169     }
1170     ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1171             "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1172 
1173     ALOGV("getOutput() returns output %d", output);
1174 
1175     return output;
1176 }
1177 
selectOutput(const SortedVector<audio_io_handle_t> & outputs,audio_output_flags_t flags,audio_format_t format)1178 audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
1179                                                        audio_output_flags_t flags,
1180                                                        audio_format_t format)
1181 {
1182     // select one output among several that provide a path to a particular device or set of
1183     // devices (the list was previously build by getOutputsForDevice()).
1184     // The priority is as follows:
1185     // 1: the output with the highest number of requested policy flags
1186     // 2: the primary output
1187     // 3: the first output in the list
1188 
1189     if (outputs.size() == 0) {
1190         return 0;
1191     }
1192     if (outputs.size() == 1) {
1193         return outputs[0];
1194     }
1195 
1196     int maxCommonFlags = 0;
1197     audio_io_handle_t outputFlags = 0;
1198     audio_io_handle_t outputPrimary = 0;
1199 
1200     for (size_t i = 0; i < outputs.size(); i++) {
1201         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
1202         if (!outputDesc->isDuplicated()) {
1203             // if a valid format is specified, skip output if not compatible
1204             if (format != AUDIO_FORMAT_INVALID) {
1205                 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1206                     if (format != outputDesc->mFormat) {
1207                         continue;
1208                     }
1209                 } else if (!audio_is_linear_pcm(format)) {
1210                     continue;
1211                 }
1212             }
1213 
1214             int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
1215             if (commonFlags > maxCommonFlags) {
1216                 outputFlags = outputs[i];
1217                 maxCommonFlags = commonFlags;
1218                 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1219             }
1220             if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1221                 outputPrimary = outputs[i];
1222             }
1223         }
1224     }
1225 
1226     if (outputFlags != 0) {
1227         return outputFlags;
1228     }
1229     if (outputPrimary != 0) {
1230         return outputPrimary;
1231     }
1232 
1233     return outputs[0];
1234 }
1235 
startOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)1236 status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
1237                                              audio_stream_type_t stream,
1238                                              audio_session_t session)
1239 {
1240     ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1241     ssize_t index = mOutputs.indexOfKey(output);
1242     if (index < 0) {
1243         ALOGW("startOutput() unknown output %d", output);
1244         return BAD_VALUE;
1245     }
1246 
1247     // cannot start playback of STREAM_TTS if any other output is being used
1248     uint32_t beaconMuteLatency = 0;
1249     if (stream == AUDIO_STREAM_TTS) {
1250         ALOGV("\t found BEACON stream");
1251         if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1252             return INVALID_OPERATION;
1253         } else {
1254             beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1255         }
1256     } else {
1257         // some playback other than beacon starts
1258         beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1259     }
1260 
1261     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1262 
1263     // increment usage count for this stream on the requested output:
1264     // NOTE that the usage count is the same for duplicated output and hardware output which is
1265     // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1266     outputDesc->changeRefCount(stream, 1);
1267 
1268     if (outputDesc->mRefCount[stream] == 1) {
1269         // starting an output being rerouted?
1270         audio_devices_t newDevice;
1271         if (outputDesc->mPolicyMix != NULL) {
1272             newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1273         } else {
1274             newDevice = getNewOutputDevice(output, false /*fromCache*/);
1275         }
1276         routing_strategy strategy = getStrategy(stream);
1277         bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1278                             (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1279                             (beaconMuteLatency > 0);
1280         uint32_t waitMs = beaconMuteLatency;
1281         bool force = false;
1282         for (size_t i = 0; i < mOutputs.size(); i++) {
1283             sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1284             if (desc != outputDesc) {
1285                 // force a device change if any other output is managed by the same hw
1286                 // module and has a current device selection that differs from selected device.
1287                 // In this case, the audio HAL must receive the new device selection so that it can
1288                 // change the device currently selected by the other active output.
1289                 if (outputDesc->sharesHwModuleWith(desc) &&
1290                     desc->device() != newDevice) {
1291                     force = true;
1292                 }
1293                 // wait for audio on other active outputs to be presented when starting
1294                 // a notification so that audio focus effect can propagate, or that a mute/unmute
1295                 // event occurred for beacon
1296                 uint32_t latency = desc->latency();
1297                 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1298                     waitMs = latency;
1299                 }
1300             }
1301         }
1302         uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1303 
1304         // handle special case for sonification while in call
1305         if (isInCall()) {
1306             handleIncallSonification(stream, true, false);
1307         }
1308 
1309         // apply volume rules for current stream and device if necessary
1310         checkAndSetVolume(stream,
1311                           mStreams[stream].getVolumeIndex(newDevice),
1312                           output,
1313                           newDevice);
1314 
1315         // update the outputs if starting an output with a stream that can affect notification
1316         // routing
1317         handleNotificationRoutingForStream(stream);
1318 
1319         // Automatically enable the remote submix input when output is started on a re routing mix
1320         // of type MIX_TYPE_RECORDERS
1321         if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1322                 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1323                 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1324                         AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1325                         outputDesc->mPolicyMix->mRegistrationId);
1326         }
1327 
1328         // force reevaluating accessibility routing when ringtone or alarm starts
1329         if (strategy == STRATEGY_SONIFICATION) {
1330             mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1331         }
1332 
1333         if (waitMs > muteWaitMs) {
1334             usleep((waitMs - muteWaitMs) * 2 * 1000);
1335         }
1336     }
1337     return NO_ERROR;
1338 }
1339 
1340 
stopOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)1341 status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
1342                                             audio_stream_type_t stream,
1343                                             audio_session_t session)
1344 {
1345     ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1346     ssize_t index = mOutputs.indexOfKey(output);
1347     if (index < 0) {
1348         ALOGW("stopOutput() unknown output %d", output);
1349         return BAD_VALUE;
1350     }
1351 
1352     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1353 
1354     // always handle stream stop, check which stream type is stopping
1355     handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1356 
1357     // handle special case for sonification while in call
1358     if (isInCall()) {
1359         handleIncallSonification(stream, false, false);
1360     }
1361 
1362     if (outputDesc->mRefCount[stream] > 0) {
1363         // decrement usage count of this stream on the output
1364         outputDesc->changeRefCount(stream, -1);
1365         // store time at which the stream was stopped - see isStreamActive()
1366         if (outputDesc->mRefCount[stream] == 0) {
1367             // Automatically disable the remote submix input when output is stopped on a
1368             // re routing mix of type MIX_TYPE_RECORDERS
1369             if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1370                     outputDesc->mPolicyMix != NULL &&
1371                     outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1372                 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1373                         AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1374                         outputDesc->mPolicyMix->mRegistrationId);
1375             }
1376 
1377             outputDesc->mStopTime[stream] = systemTime();
1378             audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
1379             // delay the device switch by twice the latency because stopOutput() is executed when
1380             // the track stop() command is received and at that time the audio track buffer can
1381             // still contain data that needs to be drained. The latency only covers the audio HAL
1382             // and kernel buffers. Also the latency does not always include additional delay in the
1383             // audio path (audio DSP, CODEC ...)
1384             setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1385 
1386             // force restoring the device selection on other active outputs if it differs from the
1387             // one being selected for this output
1388             for (size_t i = 0; i < mOutputs.size(); i++) {
1389                 audio_io_handle_t curOutput = mOutputs.keyAt(i);
1390                 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1391                 if (curOutput != output &&
1392                         desc->isActive() &&
1393                         outputDesc->sharesHwModuleWith(desc) &&
1394                         (newDevice != desc->device())) {
1395                     setOutputDevice(curOutput,
1396                                     getNewOutputDevice(curOutput, false /*fromCache*/),
1397                                     true,
1398                                     outputDesc->mLatency*2);
1399                 }
1400             }
1401             // update the outputs if stopping one with a stream that can affect notification routing
1402             handleNotificationRoutingForStream(stream);
1403         }
1404         return NO_ERROR;
1405     } else {
1406         ALOGW("stopOutput() refcount is already 0 for output %d", output);
1407         return INVALID_OPERATION;
1408     }
1409 }
1410 
releaseOutput(audio_io_handle_t output,audio_stream_type_t stream __unused,audio_session_t session __unused)1411 void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
1412                                        audio_stream_type_t stream __unused,
1413                                        audio_session_t session __unused)
1414 {
1415     ALOGV("releaseOutput() %d", output);
1416     ssize_t index = mOutputs.indexOfKey(output);
1417     if (index < 0) {
1418         ALOGW("releaseOutput() releasing unknown output %d", output);
1419         return;
1420     }
1421 
1422 #ifdef AUDIO_POLICY_TEST
1423     int testIndex = testOutputIndex(output);
1424     if (testIndex != 0) {
1425         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1426         if (outputDesc->isActive()) {
1427             mpClientInterface->closeOutput(output);
1428             mOutputs.removeItem(output);
1429             mTestOutputs[testIndex] = 0;
1430         }
1431         return;
1432     }
1433 #endif //AUDIO_POLICY_TEST
1434 
1435     sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
1436     if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1437         if (desc->mDirectOpenCount <= 0) {
1438             ALOGW("releaseOutput() invalid open count %d for output %d",
1439                                                               desc->mDirectOpenCount, output);
1440             return;
1441         }
1442         if (--desc->mDirectOpenCount == 0) {
1443             closeOutput(output);
1444             // If effects where present on the output, audioflinger moved them to the primary
1445             // output by default: move them back to the appropriate output.
1446             audio_io_handle_t dstOutput = getOutputForEffect();
1447             if (dstOutput != mPrimaryOutput) {
1448                 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1449             }
1450             mpClientInterface->onAudioPortListUpdate();
1451         }
1452     }
1453 }
1454 
1455 
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_session_t session,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_input_flags_t flags,input_type_t * inputType)1456 status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1457                                              audio_io_handle_t *input,
1458                                              audio_session_t session,
1459                                              uint32_t samplingRate,
1460                                              audio_format_t format,
1461                                              audio_channel_mask_t channelMask,
1462                                              audio_input_flags_t flags,
1463                                              input_type_t *inputType)
1464 {
1465     ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1466             "session %d, flags %#x",
1467           attr->source, samplingRate, format, channelMask, session, flags);
1468 
1469     *input = AUDIO_IO_HANDLE_NONE;
1470     *inputType = API_INPUT_INVALID;
1471     audio_devices_t device;
1472     // handle legacy remote submix case where the address was not always specified
1473     String8 address = String8("");
1474     bool isSoundTrigger = false;
1475     audio_source_t inputSource = attr->source;
1476     audio_source_t halInputSource;
1477     AudioMix *policyMix = NULL;
1478 
1479     if (inputSource == AUDIO_SOURCE_DEFAULT) {
1480         inputSource = AUDIO_SOURCE_MIC;
1481     }
1482     halInputSource = inputSource;
1483 
1484     if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
1485             strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1486         device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1487         address = String8(attr->tags + strlen("addr="));
1488         ssize_t index = mPolicyMixes.indexOfKey(address);
1489         if (index < 0) {
1490             ALOGW("getInputForAttr() no policy for address %s", address.string());
1491             return BAD_VALUE;
1492         }
1493         if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1494             ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1495             return BAD_VALUE;
1496         }
1497         policyMix = &mPolicyMixes[index]->mMix;
1498         *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1499     } else {
1500         device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1501         if (device == AUDIO_DEVICE_NONE) {
1502             ALOGW("getInputForAttr() could not find device for source %d", inputSource);
1503             return BAD_VALUE;
1504         }
1505         if (policyMix != NULL) {
1506             address = policyMix->mRegistrationId;
1507             if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1508                 // there is an external policy, but this input is attached to a mix of recorders,
1509                 // meaning it receives audio injected into the framework, so the recorder doesn't
1510                 // know about it and is therefore considered "legacy"
1511                 *inputType = API_INPUT_LEGACY;
1512             } else {
1513                 // recording a mix of players defined by an external policy, we're rerouting for
1514                 // an external policy
1515                 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1516             }
1517         } else if (audio_is_remote_submix_device(device)) {
1518             address = String8("0");
1519             *inputType = API_INPUT_MIX_CAPTURE;
1520         } else {
1521             *inputType = API_INPUT_LEGACY;
1522         }
1523         // adapt channel selection to input source
1524         switch (inputSource) {
1525         case AUDIO_SOURCE_VOICE_UPLINK:
1526             channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1527             break;
1528         case AUDIO_SOURCE_VOICE_DOWNLINK:
1529             channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1530             break;
1531         case AUDIO_SOURCE_VOICE_CALL:
1532             channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1533             break;
1534         default:
1535             break;
1536         }
1537         if (inputSource == AUDIO_SOURCE_HOTWORD) {
1538             ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1539             if (index >= 0) {
1540                 *input = mSoundTriggerSessions.valueFor(session);
1541                 isSoundTrigger = true;
1542                 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1543                 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1544             } else {
1545                 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1546             }
1547         }
1548     }
1549 
1550     sp<IOProfile> profile = getInputProfile(device, address,
1551                                             samplingRate, format, channelMask,
1552                                             flags);
1553     if (profile == 0) {
1554         //retry without flags
1555         audio_input_flags_t log_flags = flags;
1556         flags = AUDIO_INPUT_FLAG_NONE;
1557         profile = getInputProfile(device, address,
1558                                   samplingRate, format, channelMask,
1559                                   flags);
1560         if (profile == 0) {
1561             ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1562                     "format %#x, channelMask 0x%X, flags %#x",
1563                     device, samplingRate, format, channelMask, log_flags);
1564             return BAD_VALUE;
1565         }
1566     }
1567 
1568     if (profile->mModule->mHandle == 0) {
1569         ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1570         return NO_INIT;
1571     }
1572 
1573     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1574     config.sample_rate = samplingRate;
1575     config.channel_mask = channelMask;
1576     config.format = format;
1577 
1578     status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1579                                                    input,
1580                                                    &config,
1581                                                    &device,
1582                                                    address,
1583                                                    halInputSource,
1584                                                    flags);
1585 
1586     // only accept input with the exact requested set of parameters
1587     if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
1588         (samplingRate != config.sample_rate) ||
1589         (format != config.format) ||
1590         (channelMask != config.channel_mask)) {
1591         ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
1592                 samplingRate, format, channelMask);
1593         if (*input != AUDIO_IO_HANDLE_NONE) {
1594             mpClientInterface->closeInput(*input);
1595         }
1596         return BAD_VALUE;
1597     }
1598 
1599     sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
1600     inputDesc->mInputSource = inputSource;
1601     inputDesc->mRefCount = 0;
1602     inputDesc->mOpenRefCount = 1;
1603     inputDesc->mSamplingRate = samplingRate;
1604     inputDesc->mFormat = format;
1605     inputDesc->mChannelMask = channelMask;
1606     inputDesc->mDevice = device;
1607     inputDesc->mSessions.add(session);
1608     inputDesc->mIsSoundTrigger = isSoundTrigger;
1609     inputDesc->mPolicyMix = policyMix;
1610 
1611     ALOGV("getInputForAttr() returns input type = %d", inputType);
1612 
1613     addInput(*input, inputDesc);
1614     mpClientInterface->onAudioPortListUpdate();
1615     return NO_ERROR;
1616 }
1617 
startInput(audio_io_handle_t input,audio_session_t session)1618 status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1619                                         audio_session_t session)
1620 {
1621     ALOGV("startInput() input %d", input);
1622     ssize_t index = mInputs.indexOfKey(input);
1623     if (index < 0) {
1624         ALOGW("startInput() unknown input %d", input);
1625         return BAD_VALUE;
1626     }
1627     sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1628 
1629     index = inputDesc->mSessions.indexOf(session);
1630     if (index < 0) {
1631         ALOGW("startInput() unknown session %d on input %d", session, input);
1632         return BAD_VALUE;
1633     }
1634 
1635     // virtual input devices are compatible with other input devices
1636     if (!isVirtualInputDevice(inputDesc->mDevice)) {
1637 
1638         // for a non-virtual input device, check if there is another (non-virtual) active input
1639         audio_io_handle_t activeInput = getActiveInput();
1640         if (activeInput != 0 && activeInput != input) {
1641 
1642             // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1643             // otherwise the active input continues and the new input cannot be started.
1644             sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1645             if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1646                 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1647                 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1648                 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
1649             } else {
1650                 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1651                 return INVALID_OPERATION;
1652             }
1653         }
1654     }
1655 
1656     if (inputDesc->mRefCount == 0) {
1657         if (activeInputsCount() == 0) {
1658             SoundTrigger::setCaptureState(true);
1659         }
1660         setInputDevice(input, getNewInputDevice(input), true /* force */);
1661 
1662         // automatically enable the remote submix output when input is started if not
1663         // used by a policy mix of type MIX_TYPE_RECORDERS
1664         // For remote submix (a virtual device), we open only one input per capture request.
1665         if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1666             String8 address = String8("");
1667             if (inputDesc->mPolicyMix == NULL) {
1668                 address = String8("0");
1669             } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1670                 address = inputDesc->mPolicyMix->mRegistrationId;
1671             }
1672             if (address != "") {
1673                 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1674                         AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1675                         address);
1676             }
1677         }
1678     }
1679 
1680     ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1681 
1682     inputDesc->mRefCount++;
1683     return NO_ERROR;
1684 }
1685 
stopInput(audio_io_handle_t input,audio_session_t session)1686 status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1687                                        audio_session_t session)
1688 {
1689     ALOGV("stopInput() input %d", input);
1690     ssize_t index = mInputs.indexOfKey(input);
1691     if (index < 0) {
1692         ALOGW("stopInput() unknown input %d", input);
1693         return BAD_VALUE;
1694     }
1695     sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1696 
1697     index = inputDesc->mSessions.indexOf(session);
1698     if (index < 0) {
1699         ALOGW("stopInput() unknown session %d on input %d", session, input);
1700         return BAD_VALUE;
1701     }
1702 
1703     if (inputDesc->mRefCount == 0) {
1704         ALOGW("stopInput() input %d already stopped", input);
1705         return INVALID_OPERATION;
1706     }
1707 
1708     inputDesc->mRefCount--;
1709     if (inputDesc->mRefCount == 0) {
1710 
1711         // automatically disable the remote submix output when input is stopped if not
1712         // used by a policy mix of type MIX_TYPE_RECORDERS
1713         if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1714             String8 address = String8("");
1715             if (inputDesc->mPolicyMix == NULL) {
1716                 address = String8("0");
1717             } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1718                 address = inputDesc->mPolicyMix->mRegistrationId;
1719             }
1720             if (address != "") {
1721                 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1722                                          AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1723                                          address);
1724             }
1725         }
1726 
1727         resetInputDevice(input);
1728 
1729         if (activeInputsCount() == 0) {
1730             SoundTrigger::setCaptureState(false);
1731         }
1732     }
1733     return NO_ERROR;
1734 }
1735 
releaseInput(audio_io_handle_t input,audio_session_t session)1736 void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1737                                       audio_session_t session)
1738 {
1739     ALOGV("releaseInput() %d", input);
1740     ssize_t index = mInputs.indexOfKey(input);
1741     if (index < 0) {
1742         ALOGW("releaseInput() releasing unknown input %d", input);
1743         return;
1744     }
1745     sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1746     ALOG_ASSERT(inputDesc != 0);
1747 
1748     index = inputDesc->mSessions.indexOf(session);
1749     if (index < 0) {
1750         ALOGW("releaseInput() unknown session %d on input %d", session, input);
1751         return;
1752     }
1753     inputDesc->mSessions.remove(session);
1754     if (inputDesc->mOpenRefCount == 0) {
1755         ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1756         return;
1757     }
1758     inputDesc->mOpenRefCount--;
1759     if (inputDesc->mOpenRefCount > 0) {
1760         ALOGV("releaseInput() exit > 0");
1761         return;
1762     }
1763 
1764     closeInput(input);
1765     mpClientInterface->onAudioPortListUpdate();
1766     ALOGV("releaseInput() exit");
1767 }
1768 
closeAllInputs()1769 void AudioPolicyManager::closeAllInputs() {
1770     bool patchRemoved = false;
1771 
1772     for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1773         sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1774         ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1775         if (patch_index >= 0) {
1776             sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1777             status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1778             mAudioPatches.removeItemsAt(patch_index);
1779             patchRemoved = true;
1780         }
1781         mpClientInterface->closeInput(mInputs.keyAt(input_index));
1782     }
1783     mInputs.clear();
1784     nextAudioPortGeneration();
1785 
1786     if (patchRemoved) {
1787         mpClientInterface->onAudioPatchListUpdate();
1788     }
1789 }
1790 
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)1791 void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
1792                                             int indexMin,
1793                                             int indexMax)
1794 {
1795     ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1796     if (indexMin < 0 || indexMin >= indexMax) {
1797         ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1798         return;
1799     }
1800     mStreams[stream].mIndexMin = indexMin;
1801     mStreams[stream].mIndexMax = indexMax;
1802     //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1803     if (stream == AUDIO_STREAM_MUSIC) {
1804         mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1805         mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1806     }
1807 }
1808 
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)1809 status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
1810                                                       int index,
1811                                                       audio_devices_t device)
1812 {
1813 
1814     if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1815         return BAD_VALUE;
1816     }
1817     if (!audio_is_output_device(device)) {
1818         return BAD_VALUE;
1819     }
1820 
1821     // Force max volume if stream cannot be muted
1822     if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1823 
1824     ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1825           stream, device, index);
1826 
1827     // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1828     // clear all device specific values
1829     if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1830         mStreams[stream].mIndexCur.clear();
1831     }
1832     mStreams[stream].mIndexCur.add(device, index);
1833 
1834     // update volume on all outputs whose current device is also selected by the same
1835     // strategy as the device specified by the caller
1836     audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1837 
1838 
1839     //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1840     audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1841     if (stream == AUDIO_STREAM_MUSIC) {
1842         mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1843         accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1844     }
1845     if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1846             (device & (strategyDevice | accessibilityDevice)) == 0) {
1847         return NO_ERROR;
1848     }
1849     status_t status = NO_ERROR;
1850     for (size_t i = 0; i < mOutputs.size(); i++) {
1851         audio_devices_t curDevice =
1852                 getDeviceForVolume(mOutputs.valueAt(i)->device());
1853         if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
1854             status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1855             if (volStatus != NO_ERROR) {
1856                 status = volStatus;
1857             }
1858         }
1859         if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1860             status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1861                                                    index, mOutputs.keyAt(i), curDevice);
1862         }
1863     }
1864     return status;
1865 }
1866 
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)1867 status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
1868                                                       int *index,
1869                                                       audio_devices_t device)
1870 {
1871     if (index == NULL) {
1872         return BAD_VALUE;
1873     }
1874     if (!audio_is_output_device(device)) {
1875         return BAD_VALUE;
1876     }
1877     // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1878     // the strategy the stream belongs to.
1879     if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1880         device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1881     }
1882     device = getDeviceForVolume(device);
1883 
1884     *index =  mStreams[stream].getVolumeIndex(device);
1885     ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1886     return NO_ERROR;
1887 }
1888 
selectOutputForEffects(const SortedVector<audio_io_handle_t> & outputs)1889 audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
1890                                             const SortedVector<audio_io_handle_t>& outputs)
1891 {
1892     // select one output among several suitable for global effects.
1893     // The priority is as follows:
1894     // 1: An offloaded output. If the effect ends up not being offloadable,
1895     //    AudioFlinger will invalidate the track and the offloaded output
1896     //    will be closed causing the effect to be moved to a PCM output.
1897     // 2: A deep buffer output
1898     // 3: the first output in the list
1899 
1900     if (outputs.size() == 0) {
1901         return 0;
1902     }
1903 
1904     audio_io_handle_t outputOffloaded = 0;
1905     audio_io_handle_t outputDeepBuffer = 0;
1906 
1907     for (size_t i = 0; i < outputs.size(); i++) {
1908         sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
1909         ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1910         if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1911             outputOffloaded = outputs[i];
1912         }
1913         if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1914             outputDeepBuffer = outputs[i];
1915         }
1916     }
1917 
1918     ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1919           outputOffloaded, outputDeepBuffer);
1920     if (outputOffloaded != 0) {
1921         return outputOffloaded;
1922     }
1923     if (outputDeepBuffer != 0) {
1924         return outputDeepBuffer;
1925     }
1926 
1927     return outputs[0];
1928 }
1929 
getOutputForEffect(const effect_descriptor_t * desc)1930 audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
1931 {
1932     // apply simple rule where global effects are attached to the same output as MUSIC streams
1933 
1934     routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
1935     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1936     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1937 
1938     audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1939     ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1940           output, (desc == NULL) ? "unspecified" : desc->name,  (desc == NULL) ? 0 : desc->flags);
1941 
1942     return output;
1943 }
1944 
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,uint32_t strategy,int session,int id)1945 status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
1946                                 audio_io_handle_t io,
1947                                 uint32_t strategy,
1948                                 int session,
1949                                 int id)
1950 {
1951     ssize_t index = mOutputs.indexOfKey(io);
1952     if (index < 0) {
1953         index = mInputs.indexOfKey(io);
1954         if (index < 0) {
1955             ALOGW("registerEffect() unknown io %d", io);
1956             return INVALID_OPERATION;
1957         }
1958     }
1959 
1960     if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1961         ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1962                 desc->name, desc->memoryUsage);
1963         return INVALID_OPERATION;
1964     }
1965     mTotalEffectsMemory += desc->memoryUsage;
1966     ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1967             desc->name, io, strategy, session, id);
1968     ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1969 
1970     sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1971     memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1972     effectDesc->mIo = io;
1973     effectDesc->mStrategy = (routing_strategy)strategy;
1974     effectDesc->mSession = session;
1975     effectDesc->mEnabled = false;
1976 
1977     mEffects.add(id, effectDesc);
1978 
1979     return NO_ERROR;
1980 }
1981 
unregisterEffect(int id)1982 status_t AudioPolicyManager::unregisterEffect(int id)
1983 {
1984     ssize_t index = mEffects.indexOfKey(id);
1985     if (index < 0) {
1986         ALOGW("unregisterEffect() unknown effect ID %d", id);
1987         return INVALID_OPERATION;
1988     }
1989 
1990     sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
1991 
1992     setEffectEnabled(effectDesc, false);
1993 
1994     if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
1995         ALOGW("unregisterEffect() memory %d too big for total %d",
1996                 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1997         effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1998     }
1999     mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
2000     ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
2001             effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
2002 
2003     mEffects.removeItem(id);
2004 
2005     return NO_ERROR;
2006 }
2007 
setEffectEnabled(int id,bool enabled)2008 status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2009 {
2010     ssize_t index = mEffects.indexOfKey(id);
2011     if (index < 0) {
2012         ALOGW("unregisterEffect() unknown effect ID %d", id);
2013         return INVALID_OPERATION;
2014     }
2015 
2016     return setEffectEnabled(mEffects.valueAt(index), enabled);
2017 }
2018 
setEffectEnabled(const sp<EffectDescriptor> & effectDesc,bool enabled)2019 status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
2020 {
2021     if (enabled == effectDesc->mEnabled) {
2022         ALOGV("setEffectEnabled(%s) effect already %s",
2023              enabled?"true":"false", enabled?"enabled":"disabled");
2024         return INVALID_OPERATION;
2025     }
2026 
2027     if (enabled) {
2028         if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
2029             ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
2030                  effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
2031             return INVALID_OPERATION;
2032         }
2033         mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
2034         ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
2035     } else {
2036         if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
2037             ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
2038                     effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
2039             effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
2040         }
2041         mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
2042         ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
2043     }
2044     effectDesc->mEnabled = enabled;
2045     return NO_ERROR;
2046 }
2047 
isNonOffloadableEffectEnabled()2048 bool AudioPolicyManager::isNonOffloadableEffectEnabled()
2049 {
2050     for (size_t i = 0; i < mEffects.size(); i++) {
2051         sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
2052         if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
2053                 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
2054             ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
2055                   effectDesc->mDesc.name, effectDesc->mSession);
2056             return true;
2057         }
2058     }
2059     return false;
2060 }
2061 
isStreamActive(audio_stream_type_t stream,uint32_t inPastMs) const2062 bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2063 {
2064     nsecs_t sysTime = systemTime();
2065     for (size_t i = 0; i < mOutputs.size(); i++) {
2066         const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
2067         if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
2068             return true;
2069         }
2070     }
2071     return false;
2072 }
2073 
isStreamActiveRemotely(audio_stream_type_t stream,uint32_t inPastMs) const2074 bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
2075                                                     uint32_t inPastMs) const
2076 {
2077     nsecs_t sysTime = systemTime();
2078     for (size_t i = 0; i < mOutputs.size(); i++) {
2079         const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
2080         if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
2081                 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
2082             // do not consider re routing (when the output is going to a dynamic policy)
2083             // as "remote playback"
2084             if (outputDesc->mPolicyMix == NULL) {
2085                 return true;
2086             }
2087         }
2088     }
2089     return false;
2090 }
2091 
isSourceActive(audio_source_t source) const2092 bool AudioPolicyManager::isSourceActive(audio_source_t source) const
2093 {
2094     for (size_t i = 0; i < mInputs.size(); i++) {
2095         const sp<AudioInputDescriptor>  inputDescriptor = mInputs.valueAt(i);
2096         if (inputDescriptor->mRefCount == 0) {
2097             continue;
2098         }
2099         if (inputDescriptor->mInputSource == (int)source) {
2100             return true;
2101         }
2102         // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
2103         // corresponds to an active capture triggered by a hardware hotword recognition
2104         if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
2105                  (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
2106             // FIXME: we should not assume that the first session is the active one and keep
2107             // activity count per session. Same in startInput().
2108             ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
2109             if (index >= 0) {
2110                 return true;
2111             }
2112         }
2113     }
2114     return false;
2115 }
2116 
2117 // Register a list of custom mixes with their attributes and format.
2118 // When a mix is registered, corresponding input and output profiles are
2119 // added to the remote submix hw module. The profile contains only the
2120 // parameters (sampling rate, format...) specified by the mix.
2121 // The corresponding input remote submix device is also connected.
2122 //
2123 // When a remote submix device is connected, the address is checked to select the
2124 // appropriate profile and the corresponding input or output stream is opened.
2125 //
2126 // When capture starts, getInputForAttr() will:
2127 //  - 1 look for a mix matching the address passed in attribtutes tags if any
2128 //  - 2 if none found, getDeviceForInputSource() will:
2129 //     - 2.1 look for a mix matching the attributes source
2130 //     - 2.2 if none found, default to device selection by policy rules
2131 // At this time, the corresponding output remote submix device is also connected
2132 // and active playback use cases can be transferred to this mix if needed when reconnecting
2133 // after AudioTracks are invalidated
2134 //
2135 // When playback starts, getOutputForAttr() will:
2136 //  - 1 look for a mix matching the address passed in attribtutes tags if any
2137 //  - 2 if none found, look for a mix matching the attributes usage
2138 //  - 3 if none found, default to device and output selection by policy rules.
2139 
registerPolicyMixes(Vector<AudioMix> mixes)2140 status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2141 {
2142     sp<HwModule> module;
2143     for (size_t i = 0; i < mHwModules.size(); i++) {
2144         if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2145                 mHwModules[i]->mHandle != 0) {
2146             module = mHwModules[i];
2147             break;
2148         }
2149     }
2150 
2151     if (module == 0) {
2152         return INVALID_OPERATION;
2153     }
2154 
2155     ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2156 
2157     for (size_t i = 0; i < mixes.size(); i++) {
2158         String8 address = mixes[i].mRegistrationId;
2159         ssize_t index = mPolicyMixes.indexOfKey(address);
2160         if (index >= 0) {
2161             ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2162             continue;
2163         }
2164         audio_config_t outputConfig = mixes[i].mFormat;
2165         audio_config_t inputConfig = mixes[i].mFormat;
2166         // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2167         // stereo and let audio flinger do the channel conversion if needed.
2168         outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2169         inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2170         module->addOutputProfile(address, &outputConfig,
2171                                  AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2172         module->addInputProfile(address, &inputConfig,
2173                                  AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2174         sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2175         policyMix->mMix = mixes[i];
2176         mPolicyMixes.add(address, policyMix);
2177         if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2178             setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2179                                      AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2180                                      address.string());
2181         } else {
2182             setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2183                                      AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2184                                      address.string());
2185         }
2186     }
2187     return NO_ERROR;
2188 }
2189 
unregisterPolicyMixes(Vector<AudioMix> mixes)2190 status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2191 {
2192     sp<HwModule> module;
2193     for (size_t i = 0; i < mHwModules.size(); i++) {
2194         if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2195                 mHwModules[i]->mHandle != 0) {
2196             module = mHwModules[i];
2197             break;
2198         }
2199     }
2200 
2201     if (module == 0) {
2202         return INVALID_OPERATION;
2203     }
2204 
2205     ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2206 
2207     for (size_t i = 0; i < mixes.size(); i++) {
2208         String8 address = mixes[i].mRegistrationId;
2209         ssize_t index = mPolicyMixes.indexOfKey(address);
2210         if (index < 0) {
2211             ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2212             continue;
2213         }
2214 
2215         mPolicyMixes.removeItemsAt(index);
2216 
2217         if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2218                                              AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2219         {
2220             setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2221                                      AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2222                                      address.string());
2223         }
2224 
2225         if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2226                                              AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2227         {
2228             setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2229                                      AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2230                                      address.string());
2231         }
2232         module->removeOutputProfile(address);
2233         module->removeInputProfile(address);
2234     }
2235     return NO_ERROR;
2236 }
2237 
2238 
dump(int fd)2239 status_t AudioPolicyManager::dump(int fd)
2240 {
2241     const size_t SIZE = 256;
2242     char buffer[SIZE];
2243     String8 result;
2244 
2245     snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2246     result.append(buffer);
2247 
2248     snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2249     result.append(buffer);
2250     snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2251     result.append(buffer);
2252     snprintf(buffer, SIZE, " Force use for communications %d\n",
2253              mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
2254     result.append(buffer);
2255     snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
2256     result.append(buffer);
2257     snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
2258     result.append(buffer);
2259     snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
2260     result.append(buffer);
2261     snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
2262     result.append(buffer);
2263     snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2264             mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2265     result.append(buffer);
2266 
2267     snprintf(buffer, SIZE, " Available output devices:\n");
2268     result.append(buffer);
2269     write(fd, result.string(), result.size());
2270     for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2271         mAvailableOutputDevices[i]->dump(fd, 2, i);
2272     }
2273     snprintf(buffer, SIZE, "\n Available input devices:\n");
2274     write(fd, buffer, strlen(buffer));
2275     for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2276         mAvailableInputDevices[i]->dump(fd, 2, i);
2277     }
2278 
2279     snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2280     write(fd, buffer, strlen(buffer));
2281     for (size_t i = 0; i < mHwModules.size(); i++) {
2282         snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
2283         write(fd, buffer, strlen(buffer));
2284         mHwModules[i]->dump(fd);
2285     }
2286 
2287     snprintf(buffer, SIZE, "\nOutputs dump:\n");
2288     write(fd, buffer, strlen(buffer));
2289     for (size_t i = 0; i < mOutputs.size(); i++) {
2290         snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2291         write(fd, buffer, strlen(buffer));
2292         mOutputs.valueAt(i)->dump(fd);
2293     }
2294 
2295     snprintf(buffer, SIZE, "\nInputs dump:\n");
2296     write(fd, buffer, strlen(buffer));
2297     for (size_t i = 0; i < mInputs.size(); i++) {
2298         snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2299         write(fd, buffer, strlen(buffer));
2300         mInputs.valueAt(i)->dump(fd);
2301     }
2302 
2303     snprintf(buffer, SIZE, "\nStreams dump:\n");
2304     write(fd, buffer, strlen(buffer));
2305     snprintf(buffer, SIZE,
2306              " Stream  Can be muted  Index Min  Index Max  Index Cur [device : index]...\n");
2307     write(fd, buffer, strlen(buffer));
2308     for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
2309         snprintf(buffer, SIZE, " %02zu      ", i);
2310         write(fd, buffer, strlen(buffer));
2311         mStreams[i].dump(fd);
2312     }
2313 
2314     snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2315             (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2316     write(fd, buffer, strlen(buffer));
2317 
2318     snprintf(buffer, SIZE, "Registered effects:\n");
2319     write(fd, buffer, strlen(buffer));
2320     for (size_t i = 0; i < mEffects.size(); i++) {
2321         snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2322         write(fd, buffer, strlen(buffer));
2323         mEffects.valueAt(i)->dump(fd);
2324     }
2325 
2326     snprintf(buffer, SIZE, "\nAudio Patches:\n");
2327     write(fd, buffer, strlen(buffer));
2328     for (size_t i = 0; i < mAudioPatches.size(); i++) {
2329         mAudioPatches[i]->dump(fd, 2, i);
2330     }
2331 
2332     return NO_ERROR;
2333 }
2334 
2335 // This function checks for the parameters which can be offloaded.
2336 // This can be enhanced depending on the capability of the DSP and policy
2337 // of the system.
isOffloadSupported(const audio_offload_info_t & offloadInfo)2338 bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
2339 {
2340     ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
2341      " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
2342      offloadInfo.sample_rate, offloadInfo.channel_mask,
2343      offloadInfo.format,
2344      offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2345      offloadInfo.has_video);
2346 
2347     // Check if offload has been disabled
2348     char propValue[PROPERTY_VALUE_MAX];
2349     if (property_get("audio.offload.disable", propValue, "0")) {
2350         if (atoi(propValue) != 0) {
2351             ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2352             return false;
2353         }
2354     }
2355 
2356     // Check if stream type is music, then only allow offload as of now.
2357     if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2358     {
2359         ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2360         return false;
2361     }
2362 
2363     //TODO: enable audio offloading with video when ready
2364     if (offloadInfo.has_video)
2365     {
2366         ALOGV("isOffloadSupported: has_video == true, returning false");
2367         return false;
2368     }
2369 
2370     //If duration is less than minimum value defined in property, return false
2371     if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2372         if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2373             ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2374             return false;
2375         }
2376     } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2377         ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2378         return false;
2379     }
2380 
2381     // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2382     // creating an offloaded track and tearing it down immediately after start when audioflinger
2383     // detects there is an active non offloadable effect.
2384     // FIXME: We should check the audio session here but we do not have it in this context.
2385     // This may prevent offloading in rare situations where effects are left active by apps
2386     // in the background.
2387     if (isNonOffloadableEffectEnabled()) {
2388         return false;
2389     }
2390 
2391     // See if there is a profile to support this.
2392     // AUDIO_DEVICE_NONE
2393     sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
2394                                             offloadInfo.sample_rate,
2395                                             offloadInfo.format,
2396                                             offloadInfo.channel_mask,
2397                                             AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
2398     ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2399     return (profile != 0);
2400 }
2401 
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port * ports,unsigned int * generation)2402 status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2403                                             audio_port_type_t type,
2404                                             unsigned int *num_ports,
2405                                             struct audio_port *ports,
2406                                             unsigned int *generation)
2407 {
2408     if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2409             generation == NULL) {
2410         return BAD_VALUE;
2411     }
2412     ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2413     if (ports == NULL) {
2414         *num_ports = 0;
2415     }
2416 
2417     size_t portsWritten = 0;
2418     size_t portsMax = *num_ports;
2419     *num_ports = 0;
2420     if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2421         if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2422             for (size_t i = 0;
2423                     i  < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2424                 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2425             }
2426             *num_ports += mAvailableOutputDevices.size();
2427         }
2428         if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2429             for (size_t i = 0;
2430                     i  < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2431                 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2432             }
2433             *num_ports += mAvailableInputDevices.size();
2434         }
2435     }
2436     if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2437         if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2438             for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2439                 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2440             }
2441             *num_ports += mInputs.size();
2442         }
2443         if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2444             size_t numOutputs = 0;
2445             for (size_t i = 0; i < mOutputs.size(); i++) {
2446                 if (!mOutputs[i]->isDuplicated()) {
2447                     numOutputs++;
2448                     if (portsWritten < portsMax) {
2449                         mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2450                     }
2451                 }
2452             }
2453             *num_ports += numOutputs;
2454         }
2455     }
2456     *generation = curAudioPortGeneration();
2457     ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
2458     return NO_ERROR;
2459 }
2460 
getAudioPort(struct audio_port * port __unused)2461 status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2462 {
2463     return NO_ERROR;
2464 }
2465 
getOutputFromId(audio_port_handle_t id) const2466 sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
2467                                                                     audio_port_handle_t id) const
2468 {
2469     sp<AudioOutputDescriptor> outputDesc = NULL;
2470     for (size_t i = 0; i < mOutputs.size(); i++) {
2471         outputDesc = mOutputs.valueAt(i);
2472         if (outputDesc->mId == id) {
2473             break;
2474         }
2475     }
2476     return outputDesc;
2477 }
2478 
getInputFromId(audio_port_handle_t id) const2479 sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
2480                                                                     audio_port_handle_t id) const
2481 {
2482     sp<AudioInputDescriptor> inputDesc = NULL;
2483     for (size_t i = 0; i < mInputs.size(); i++) {
2484         inputDesc = mInputs.valueAt(i);
2485         if (inputDesc->mId == id) {
2486             break;
2487         }
2488     }
2489     return inputDesc;
2490 }
2491 
getModuleForDevice(audio_devices_t device) const2492 sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2493                                                                     audio_devices_t device) const
2494 {
2495     sp <HwModule> module;
2496 
2497     for (size_t i = 0; i < mHwModules.size(); i++) {
2498         if (mHwModules[i]->mHandle == 0) {
2499             continue;
2500         }
2501         if (audio_is_output_device(device)) {
2502             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2503             {
2504                 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2505                     return mHwModules[i];
2506                 }
2507             }
2508         } else {
2509             for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2510                 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2511                         device & ~AUDIO_DEVICE_BIT_IN) {
2512                     return mHwModules[i];
2513                 }
2514             }
2515         }
2516     }
2517     return module;
2518 }
2519 
getModuleFromName(const char * name) const2520 sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
2521 {
2522     sp <HwModule> module;
2523 
2524     for (size_t i = 0; i < mHwModules.size(); i++)
2525     {
2526         if (strcmp(mHwModules[i]->mName, name) == 0) {
2527             return mHwModules[i];
2528         }
2529     }
2530     return module;
2531 }
2532 
availablePrimaryOutputDevices()2533 audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2534 {
2535     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2536     audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2537     return devices & mAvailableOutputDevices.types();
2538 }
2539 
availablePrimaryInputDevices()2540 audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2541 {
2542     audio_module_handle_t primaryHandle =
2543                                 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2544     audio_devices_t devices = AUDIO_DEVICE_NONE;
2545     for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2546         if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2547             devices |= mAvailableInputDevices[i]->mDeviceType;
2548         }
2549     }
2550     return devices;
2551 }
2552 
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid)2553 status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2554                                                audio_patch_handle_t *handle,
2555                                                uid_t uid)
2556 {
2557     ALOGV("createAudioPatch()");
2558 
2559     if (handle == NULL || patch == NULL) {
2560         return BAD_VALUE;
2561     }
2562     ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2563 
2564     if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2565             patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2566         return BAD_VALUE;
2567     }
2568     // only one source per audio patch supported for now
2569     if (patch->num_sources > 1) {
2570         return INVALID_OPERATION;
2571     }
2572 
2573     if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
2574         return INVALID_OPERATION;
2575     }
2576     for (size_t i = 0; i < patch->num_sinks; i++) {
2577         if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2578             return INVALID_OPERATION;
2579         }
2580     }
2581 
2582     sp<AudioPatch> patchDesc;
2583     ssize_t index = mAudioPatches.indexOfKey(*handle);
2584 
2585     ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2586                                                            patch->sources[0].role,
2587                                                            patch->sources[0].type);
2588 #if LOG_NDEBUG == 0
2589     for (size_t i = 0; i < patch->num_sinks; i++) {
2590         ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2591                                                              patch->sinks[i].role,
2592                                                              patch->sinks[i].type);
2593     }
2594 #endif
2595 
2596     if (index >= 0) {
2597         patchDesc = mAudioPatches.valueAt(index);
2598         ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2599                                                                   mUidCached, patchDesc->mUid, uid);
2600         if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2601             return INVALID_OPERATION;
2602         }
2603     } else {
2604         *handle = 0;
2605     }
2606 
2607     if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
2608         sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
2609         if (outputDesc == NULL) {
2610             ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2611             return BAD_VALUE;
2612         }
2613         ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2614                                                 outputDesc->mIoHandle);
2615         if (patchDesc != 0) {
2616             if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2617                 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2618                                           patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2619                 return BAD_VALUE;
2620             }
2621         }
2622         DeviceVector devices;
2623         for (size_t i = 0; i < patch->num_sinks; i++) {
2624             // Only support mix to devices connection
2625             // TODO add support for mix to mix connection
2626             if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2627                 ALOGV("createAudioPatch() source mix but sink is not a device");
2628                 return INVALID_OPERATION;
2629             }
2630             sp<DeviceDescriptor> devDesc =
2631                     mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2632             if (devDesc == 0) {
2633                 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2634                 return BAD_VALUE;
2635             }
2636 
2637             if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2638                                                            devDesc->mAddress,
2639                                                            patch->sources[0].sample_rate,
2640                                                          NULL,  // updatedSamplingRate
2641                                                          patch->sources[0].format,
2642                                                          patch->sources[0].channel_mask,
2643                                                          AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2644                 ALOGV("createAudioPatch() profile not supported for device %08x",
2645                       devDesc->mDeviceType);
2646                 return INVALID_OPERATION;
2647             }
2648             devices.add(devDesc);
2649         }
2650         if (devices.size() == 0) {
2651             return INVALID_OPERATION;
2652         }
2653 
2654         // TODO: reconfigure output format and channels here
2655         ALOGV("createAudioPatch() setting device %08x on output %d",
2656               devices.types(), outputDesc->mIoHandle);
2657         setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
2658         index = mAudioPatches.indexOfKey(*handle);
2659         if (index >= 0) {
2660             if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2661                 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2662             }
2663             patchDesc = mAudioPatches.valueAt(index);
2664             patchDesc->mUid = uid;
2665             ALOGV("createAudioPatch() success");
2666         } else {
2667             ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2668             return INVALID_OPERATION;
2669         }
2670     } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2671         if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2672             // input device to input mix connection
2673             // only one sink supported when connecting an input device to a mix
2674             if (patch->num_sinks > 1) {
2675                 return INVALID_OPERATION;
2676             }
2677             sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
2678             if (inputDesc == NULL) {
2679                 return BAD_VALUE;
2680             }
2681             if (patchDesc != 0) {
2682                 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2683                     return BAD_VALUE;
2684                 }
2685             }
2686             sp<DeviceDescriptor> devDesc =
2687                     mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2688             if (devDesc == 0) {
2689                 return BAD_VALUE;
2690             }
2691 
2692             if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2693                                                           devDesc->mAddress,
2694                                                           patch->sinks[0].sample_rate,
2695                                                           NULL, /*updatedSampleRate*/
2696                                                           patch->sinks[0].format,
2697                                                           patch->sinks[0].channel_mask,
2698                                                           // FIXME for the parameter type,
2699                                                           // and the NONE
2700                                                           (audio_output_flags_t)
2701                                                             AUDIO_INPUT_FLAG_NONE)) {
2702                 return INVALID_OPERATION;
2703             }
2704             // TODO: reconfigure output format and channels here
2705             ALOGV("createAudioPatch() setting device %08x on output %d",
2706                                                   devDesc->mDeviceType, inputDesc->mIoHandle);
2707             setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
2708             index = mAudioPatches.indexOfKey(*handle);
2709             if (index >= 0) {
2710                 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2711                     ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2712                 }
2713                 patchDesc = mAudioPatches.valueAt(index);
2714                 patchDesc->mUid = uid;
2715                 ALOGV("createAudioPatch() success");
2716             } else {
2717                 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2718                 return INVALID_OPERATION;
2719             }
2720         } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2721             // device to device connection
2722             if (patchDesc != 0) {
2723                 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2724                     return BAD_VALUE;
2725                 }
2726             }
2727             sp<DeviceDescriptor> srcDeviceDesc =
2728                     mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2729             if (srcDeviceDesc == 0) {
2730                 return BAD_VALUE;
2731             }
2732 
2733             //update source and sink with our own data as the data passed in the patch may
2734             // be incomplete.
2735             struct audio_patch newPatch = *patch;
2736             srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2737 
2738             for (size_t i = 0; i < patch->num_sinks; i++) {
2739                 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2740                     ALOGV("createAudioPatch() source device but one sink is not a device");
2741                     return INVALID_OPERATION;
2742                 }
2743 
2744                 sp<DeviceDescriptor> sinkDeviceDesc =
2745                         mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2746                 if (sinkDeviceDesc == 0) {
2747                     return BAD_VALUE;
2748                 }
2749                 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2750 
2751                 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2752                     // only one sink supported when connected devices across HW modules
2753                     if (patch->num_sinks > 1) {
2754                         return INVALID_OPERATION;
2755                     }
2756                     SortedVector<audio_io_handle_t> outputs =
2757                                             getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2758                                                                 mOutputs);
2759                     // if the sink device is reachable via an opened output stream, request to go via
2760                     // this output stream by adding a second source to the patch description
2761                     audio_io_handle_t output = selectOutput(outputs,
2762                                                             AUDIO_OUTPUT_FLAG_NONE,
2763                                                             AUDIO_FORMAT_INVALID);
2764                     if (output != AUDIO_IO_HANDLE_NONE) {
2765                         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2766                         if (outputDesc->isDuplicated()) {
2767                             return INVALID_OPERATION;
2768                         }
2769                         outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2770                         newPatch.num_sources = 2;
2771                     }
2772                 }
2773             }
2774             // TODO: check from routing capabilities in config file and other conflicting patches
2775 
2776             audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2777             if (index >= 0) {
2778                 afPatchHandle = patchDesc->mAfPatchHandle;
2779             }
2780 
2781             status_t status = mpClientInterface->createAudioPatch(&newPatch,
2782                                                                   &afPatchHandle,
2783                                                                   0);
2784             ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2785                                                                   status, afPatchHandle);
2786             if (status == NO_ERROR) {
2787                 if (index < 0) {
2788                     patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2789                                                &newPatch, uid);
2790                     addAudioPatch(patchDesc->mHandle, patchDesc);
2791                 } else {
2792                     patchDesc->mPatch = newPatch;
2793                 }
2794                 patchDesc->mAfPatchHandle = afPatchHandle;
2795                 *handle = patchDesc->mHandle;
2796                 nextAudioPortGeneration();
2797                 mpClientInterface->onAudioPatchListUpdate();
2798             } else {
2799                 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2800                 status);
2801                 return INVALID_OPERATION;
2802             }
2803         } else {
2804             return BAD_VALUE;
2805         }
2806     } else {
2807         return BAD_VALUE;
2808     }
2809     return NO_ERROR;
2810 }
2811 
releaseAudioPatch(audio_patch_handle_t handle,uid_t uid)2812 status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2813                                                   uid_t uid)
2814 {
2815     ALOGV("releaseAudioPatch() patch %d", handle);
2816 
2817     ssize_t index = mAudioPatches.indexOfKey(handle);
2818 
2819     if (index < 0) {
2820         return BAD_VALUE;
2821     }
2822     sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2823     ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2824           mUidCached, patchDesc->mUid, uid);
2825     if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2826         return INVALID_OPERATION;
2827     }
2828 
2829     struct audio_patch *patch = &patchDesc->mPatch;
2830     patchDesc->mUid = mUidCached;
2831     if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
2832         sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
2833         if (outputDesc == NULL) {
2834             ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2835             return BAD_VALUE;
2836         }
2837 
2838         setOutputDevice(outputDesc->mIoHandle,
2839                         getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2840                        true,
2841                        0,
2842                        NULL);
2843     } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2844         if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2845             sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
2846             if (inputDesc == NULL) {
2847                 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2848                 return BAD_VALUE;
2849             }
2850             setInputDevice(inputDesc->mIoHandle,
2851                            getNewInputDevice(inputDesc->mIoHandle),
2852                            true,
2853                            NULL);
2854         } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2855             audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2856             status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2857             ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2858                                                               status, patchDesc->mAfPatchHandle);
2859             removeAudioPatch(patchDesc->mHandle);
2860             nextAudioPortGeneration();
2861             mpClientInterface->onAudioPatchListUpdate();
2862         } else {
2863             return BAD_VALUE;
2864         }
2865     } else {
2866         return BAD_VALUE;
2867     }
2868     return NO_ERROR;
2869 }
2870 
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)2871 status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2872                                               struct audio_patch *patches,
2873                                               unsigned int *generation)
2874 {
2875     if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2876             generation == NULL) {
2877         return BAD_VALUE;
2878     }
2879     ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
2880           *num_patches, patches, mAudioPatches.size());
2881     if (patches == NULL) {
2882         *num_patches = 0;
2883     }
2884 
2885     size_t patchesWritten = 0;
2886     size_t patchesMax = *num_patches;
2887     for (size_t i = 0;
2888             i  < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2889         patches[patchesWritten] = mAudioPatches[i]->mPatch;
2890         patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
2891         ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
2892               i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2893     }
2894     *num_patches = mAudioPatches.size();
2895 
2896     *generation = curAudioPortGeneration();
2897     ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
2898     return NO_ERROR;
2899 }
2900 
setAudioPortConfig(const struct audio_port_config * config)2901 status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
2902 {
2903     ALOGV("setAudioPortConfig()");
2904 
2905     if (config == NULL) {
2906         return BAD_VALUE;
2907     }
2908     ALOGV("setAudioPortConfig() on port handle %d", config->id);
2909     // Only support gain configuration for now
2910     if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2911         return INVALID_OPERATION;
2912     }
2913 
2914     sp<AudioPortConfig> audioPortConfig;
2915     if (config->type == AUDIO_PORT_TYPE_MIX) {
2916         if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2917             sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
2918             if (outputDesc == NULL) {
2919                 return BAD_VALUE;
2920             }
2921             ALOG_ASSERT(!outputDesc->isDuplicated(),
2922                         "setAudioPortConfig() called on duplicated output %d",
2923                         outputDesc->mIoHandle);
2924             audioPortConfig = outputDesc;
2925         } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2926             sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
2927             if (inputDesc == NULL) {
2928                 return BAD_VALUE;
2929             }
2930             audioPortConfig = inputDesc;
2931         } else {
2932             return BAD_VALUE;
2933         }
2934     } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2935         sp<DeviceDescriptor> deviceDesc;
2936         if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2937             deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2938         } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2939             deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2940         } else {
2941             return BAD_VALUE;
2942         }
2943         if (deviceDesc == NULL) {
2944             return BAD_VALUE;
2945         }
2946         audioPortConfig = deviceDesc;
2947     } else {
2948         return BAD_VALUE;
2949     }
2950 
2951     struct audio_port_config backupConfig;
2952     status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2953     if (status == NO_ERROR) {
2954         struct audio_port_config newConfig;
2955         audioPortConfig->toAudioPortConfig(&newConfig, config);
2956         status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
2957     }
2958     if (status != NO_ERROR) {
2959         audioPortConfig->applyAudioPortConfig(&backupConfig);
2960     }
2961 
2962     return status;
2963 }
2964 
clearAudioPatches(uid_t uid)2965 void AudioPolicyManager::clearAudioPatches(uid_t uid)
2966 {
2967     for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--)  {
2968         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2969         if (patchDesc->mUid == uid) {
2970             releaseAudioPatch(mAudioPatches.keyAt(i), uid);
2971         }
2972     }
2973 }
2974 
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)2975 status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2976                                        audio_io_handle_t *ioHandle,
2977                                        audio_devices_t *device)
2978 {
2979     *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2980     *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2981     *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
2982 
2983     mSoundTriggerSessions.add(*session, *ioHandle);
2984 
2985     return NO_ERROR;
2986 }
2987 
releaseSoundTriggerSession(audio_session_t session)2988 status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2989 {
2990     ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2991     if (index < 0) {
2992         ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2993         return BAD_VALUE;
2994     }
2995 
2996     mSoundTriggerSessions.removeItem(session);
2997     return NO_ERROR;
2998 }
2999 
addAudioPatch(audio_patch_handle_t handle,const sp<AudioPatch> & patch)3000 status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
3001                                            const sp<AudioPatch>& patch)
3002 {
3003     ssize_t index = mAudioPatches.indexOfKey(handle);
3004 
3005     if (index >= 0) {
3006         ALOGW("addAudioPatch() patch %d already in", handle);
3007         return ALREADY_EXISTS;
3008     }
3009     mAudioPatches.add(handle, patch);
3010     ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
3011             "sink handle %d",
3012           handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
3013           patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
3014     return NO_ERROR;
3015 }
3016 
removeAudioPatch(audio_patch_handle_t handle)3017 status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
3018 {
3019     ssize_t index = mAudioPatches.indexOfKey(handle);
3020 
3021     if (index < 0) {
3022         ALOGW("removeAudioPatch() patch %d not in", handle);
3023         return ALREADY_EXISTS;
3024     }
3025     ALOGV("removeAudioPatch() handle %d af handle %d", handle,
3026                       mAudioPatches.valueAt(index)->mAfPatchHandle);
3027     mAudioPatches.removeItemsAt(index);
3028     return NO_ERROR;
3029 }
3030 
3031 // ----------------------------------------------------------------------------
3032 // AudioPolicyManager
3033 // ----------------------------------------------------------------------------
3034 
nextUniqueId()3035 uint32_t AudioPolicyManager::nextUniqueId()
3036 {
3037     return android_atomic_inc(&mNextUniqueId);
3038 }
3039 
nextAudioPortGeneration()3040 uint32_t AudioPolicyManager::nextAudioPortGeneration()
3041 {
3042     return android_atomic_inc(&mAudioPortGeneration);
3043 }
3044 
AudioPolicyManager(AudioPolicyClientInterface * clientInterface)3045 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3046     :
3047 #ifdef AUDIO_POLICY_TEST
3048     Thread(false),
3049 #endif //AUDIO_POLICY_TEST
3050     mPrimaryOutput((audio_io_handle_t)0),
3051     mPhoneState(AUDIO_MODE_NORMAL),
3052     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3053     mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
3054     mA2dpSuspended(false),
3055     mSpeakerDrcEnabled(false), mNextUniqueId(1),
3056     mAudioPortGeneration(1),
3057     mBeaconMuteRefCount(0),
3058     mBeaconPlayingRefCount(0),
3059     mBeaconMuted(false)
3060 {
3061     mUidCached = getuid();
3062     mpClientInterface = clientInterface;
3063 
3064     for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3065         mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
3066     }
3067 
3068     mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
3069     if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3070         if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3071             ALOGE("could not load audio policy configuration file, setting defaults");
3072             defaultAudioPolicyConfig();
3073         }
3074     }
3075     // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
3076 
3077     // must be done after reading the policy
3078     initializeVolumeCurves();
3079 
3080     // open all output streams needed to access attached devices
3081     audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3082     audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
3083     for (size_t i = 0; i < mHwModules.size(); i++) {
3084         mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3085         if (mHwModules[i]->mHandle == 0) {
3086             ALOGW("could not open HW module %s", mHwModules[i]->mName);
3087             continue;
3088         }
3089         // open all output streams needed to access attached devices
3090         // except for direct output streams that are only opened when they are actually
3091         // required by an app.
3092         // This also validates mAvailableOutputDevices list
3093         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3094         {
3095             const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
3096 
3097             if (outProfile->mSupportedDevices.isEmpty()) {
3098                 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3099                 continue;
3100             }
3101 
3102             if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3103                 continue;
3104             }
3105             audio_devices_t profileType = outProfile->mSupportedDevices.types();
3106             if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3107                 profileType = mDefaultOutputDevice->mDeviceType;
3108             } else {
3109                 // chose first device present in mSupportedDevices also part of
3110                 // outputDeviceTypes
3111                 for (size_t k = 0; k  < outProfile->mSupportedDevices.size(); k++) {
3112                     profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3113                     if ((profileType & outputDeviceTypes) != 0) {
3114                         break;
3115                     }
3116                 }
3117             }
3118             if ((profileType & outputDeviceTypes) == 0) {
3119                 continue;
3120             }
3121             sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3122 
3123             outputDesc->mDevice = profileType;
3124             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3125             config.sample_rate = outputDesc->mSamplingRate;
3126             config.channel_mask = outputDesc->mChannelMask;
3127             config.format = outputDesc->mFormat;
3128             audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3129             status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3130                                                             &output,
3131                                                             &config,
3132                                                             &outputDesc->mDevice,
3133                                                             String8(""),
3134                                                             &outputDesc->mLatency,
3135                                                             outputDesc->mFlags);
3136 
3137             if (status != NO_ERROR) {
3138                 ALOGW("Cannot open output stream for device %08x on hw module %s",
3139                       outputDesc->mDevice,
3140                       mHwModules[i]->mName);
3141             } else {
3142                 outputDesc->mSamplingRate = config.sample_rate;
3143                 outputDesc->mChannelMask = config.channel_mask;
3144                 outputDesc->mFormat = config.format;
3145 
3146                 for (size_t k = 0; k  < outProfile->mSupportedDevices.size(); k++) {
3147                     audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3148                     ssize_t index =
3149                             mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3150                     // give a valid ID to an attached device once confirmed it is reachable
3151                     if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3152                         mAvailableOutputDevices[index]->mId = nextUniqueId();
3153                         mAvailableOutputDevices[index]->mModule = mHwModules[i];
3154                     }
3155                 }
3156                 if (mPrimaryOutput == 0 &&
3157                         outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3158                     mPrimaryOutput = output;
3159                 }
3160                 addOutput(output, outputDesc);
3161                 setOutputDevice(output,
3162                                 outputDesc->mDevice,
3163                                 true);
3164             }
3165         }
3166         // open input streams needed to access attached devices to validate
3167         // mAvailableInputDevices list
3168         for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3169         {
3170             const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
3171 
3172             if (inProfile->mSupportedDevices.isEmpty()) {
3173                 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3174                 continue;
3175             }
3176             // chose first device present in mSupportedDevices also part of
3177             // inputDeviceTypes
3178             audio_devices_t profileType = AUDIO_DEVICE_NONE;
3179             for (size_t k = 0; k  < inProfile->mSupportedDevices.size(); k++) {
3180                 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3181                 if (profileType & inputDeviceTypes) {
3182                     break;
3183                 }
3184             }
3185             if ((profileType & inputDeviceTypes) == 0) {
3186                 continue;
3187             }
3188             sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3189 
3190             inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3191             inputDesc->mDevice = profileType;
3192 
3193             // find the address
3194             DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3195             //   the inputs vector must be of size 1, but we don't want to crash here
3196             String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3197                     : String8("");
3198             ALOGV("  for input device 0x%x using address %s", profileType, address.string());
3199             ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3200 
3201             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3202             config.sample_rate = inputDesc->mSamplingRate;
3203             config.channel_mask = inputDesc->mChannelMask;
3204             config.format = inputDesc->mFormat;
3205             audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3206             status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3207                                                            &input,
3208                                                            &config,
3209                                                            &inputDesc->mDevice,
3210                                                            address,
3211                                                            AUDIO_SOURCE_MIC,
3212                                                            AUDIO_INPUT_FLAG_NONE);
3213 
3214             if (status == NO_ERROR) {
3215                 for (size_t k = 0; k  < inProfile->mSupportedDevices.size(); k++) {
3216                     audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3217                     ssize_t index =
3218                             mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3219                     // give a valid ID to an attached device once confirmed it is reachable
3220                     if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3221                         mAvailableInputDevices[index]->mId = nextUniqueId();
3222                         mAvailableInputDevices[index]->mModule = mHwModules[i];
3223                     }
3224                 }
3225                 mpClientInterface->closeInput(input);
3226             } else {
3227                 ALOGW("Cannot open input stream for device %08x on hw module %s",
3228                       inputDesc->mDevice,
3229                       mHwModules[i]->mName);
3230             }
3231         }
3232     }
3233     // make sure all attached devices have been allocated a unique ID
3234     for (size_t i = 0; i  < mAvailableOutputDevices.size();) {
3235         if (mAvailableOutputDevices[i]->mId == 0) {
3236             ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
3237             mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3238             continue;
3239         }
3240         i++;
3241     }
3242     for (size_t i = 0; i  < mAvailableInputDevices.size();) {
3243         if (mAvailableInputDevices[i]->mId == 0) {
3244             ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
3245             mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3246             continue;
3247         }
3248         i++;
3249     }
3250     // make sure default device is reachable
3251     if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
3252         ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
3253     }
3254 
3255     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3256 
3257     updateDevicesAndOutputs();
3258 
3259 #ifdef AUDIO_POLICY_TEST
3260     if (mPrimaryOutput != 0) {
3261         AudioParameter outputCmd = AudioParameter();
3262         outputCmd.addInt(String8("set_id"), 0);
3263         mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3264 
3265         mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3266         mTestSamplingRate = 44100;
3267         mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3268         mTestChannels =  AUDIO_CHANNEL_OUT_STEREO;
3269         mTestLatencyMs = 0;
3270         mCurOutput = 0;
3271         mDirectOutput = false;
3272         for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3273             mTestOutputs[i] = 0;
3274         }
3275 
3276         const size_t SIZE = 256;
3277         char buffer[SIZE];
3278         snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3279         run(buffer, ANDROID_PRIORITY_AUDIO);
3280     }
3281 #endif //AUDIO_POLICY_TEST
3282 }
3283 
~AudioPolicyManager()3284 AudioPolicyManager::~AudioPolicyManager()
3285 {
3286 #ifdef AUDIO_POLICY_TEST
3287     exit();
3288 #endif //AUDIO_POLICY_TEST
3289    for (size_t i = 0; i < mOutputs.size(); i++) {
3290         mpClientInterface->closeOutput(mOutputs.keyAt(i));
3291    }
3292    for (size_t i = 0; i < mInputs.size(); i++) {
3293         mpClientInterface->closeInput(mInputs.keyAt(i));
3294    }
3295    mAvailableOutputDevices.clear();
3296    mAvailableInputDevices.clear();
3297    mOutputs.clear();
3298    mInputs.clear();
3299    mHwModules.clear();
3300 }
3301 
initCheck()3302 status_t AudioPolicyManager::initCheck()
3303 {
3304     return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3305 }
3306 
3307 #ifdef AUDIO_POLICY_TEST
threadLoop()3308 bool AudioPolicyManager::threadLoop()
3309 {
3310     ALOGV("entering threadLoop()");
3311     while (!exitPending())
3312     {
3313         String8 command;
3314         int valueInt;
3315         String8 value;
3316 
3317         Mutex::Autolock _l(mLock);
3318         mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3319 
3320         command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3321         AudioParameter param = AudioParameter(command);
3322 
3323         if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3324             valueInt != 0) {
3325             ALOGV("Test command %s received", command.string());
3326             String8 target;
3327             if (param.get(String8("target"), target) != NO_ERROR) {
3328                 target = "Manager";
3329             }
3330             if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3331                 param.remove(String8("test_cmd_policy_output"));
3332                 mCurOutput = valueInt;
3333             }
3334             if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3335                 param.remove(String8("test_cmd_policy_direct"));
3336                 if (value == "false") {
3337                     mDirectOutput = false;
3338                 } else if (value == "true") {
3339                     mDirectOutput = true;
3340                 }
3341             }
3342             if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3343                 param.remove(String8("test_cmd_policy_input"));
3344                 mTestInput = valueInt;
3345             }
3346 
3347             if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3348                 param.remove(String8("test_cmd_policy_format"));
3349                 int format = AUDIO_FORMAT_INVALID;
3350                 if (value == "PCM 16 bits") {
3351                     format = AUDIO_FORMAT_PCM_16_BIT;
3352                 } else if (value == "PCM 8 bits") {
3353                     format = AUDIO_FORMAT_PCM_8_BIT;
3354                 } else if (value == "Compressed MP3") {
3355                     format = AUDIO_FORMAT_MP3;
3356                 }
3357                 if (format != AUDIO_FORMAT_INVALID) {
3358                     if (target == "Manager") {
3359                         mTestFormat = format;
3360                     } else if (mTestOutputs[mCurOutput] != 0) {
3361                         AudioParameter outputParam = AudioParameter();
3362                         outputParam.addInt(String8("format"), format);
3363                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3364                     }
3365                 }
3366             }
3367             if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3368                 param.remove(String8("test_cmd_policy_channels"));
3369                 int channels = 0;
3370 
3371                 if (value == "Channels Stereo") {
3372                     channels =  AUDIO_CHANNEL_OUT_STEREO;
3373                 } else if (value == "Channels Mono") {
3374                     channels =  AUDIO_CHANNEL_OUT_MONO;
3375                 }
3376                 if (channels != 0) {
3377                     if (target == "Manager") {
3378                         mTestChannels = channels;
3379                     } else if (mTestOutputs[mCurOutput] != 0) {
3380                         AudioParameter outputParam = AudioParameter();
3381                         outputParam.addInt(String8("channels"), channels);
3382                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3383                     }
3384                 }
3385             }
3386             if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3387                 param.remove(String8("test_cmd_policy_sampleRate"));
3388                 if (valueInt >= 0 && valueInt <= 96000) {
3389                     int samplingRate = valueInt;
3390                     if (target == "Manager") {
3391                         mTestSamplingRate = samplingRate;
3392                     } else if (mTestOutputs[mCurOutput] != 0) {
3393                         AudioParameter outputParam = AudioParameter();
3394                         outputParam.addInt(String8("sampling_rate"), samplingRate);
3395                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3396                     }
3397                 }
3398             }
3399 
3400             if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3401                 param.remove(String8("test_cmd_policy_reopen"));
3402 
3403                 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
3404                 mpClientInterface->closeOutput(mPrimaryOutput);
3405 
3406                 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3407 
3408                 mOutputs.removeItem(mPrimaryOutput);
3409 
3410                 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
3411                 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
3412                 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3413                 config.sample_rate = outputDesc->mSamplingRate;
3414                 config.channel_mask = outputDesc->mChannelMask;
3415                 config.format = outputDesc->mFormat;
3416                 status_t status = mpClientInterface->openOutput(moduleHandle,
3417                                                                 &mPrimaryOutput,
3418                                                                 &config,
3419                                                                 &outputDesc->mDevice,
3420                                                                 String8(""),
3421                                                                 &outputDesc->mLatency,
3422                                                                 outputDesc->mFlags);
3423                 if (status != NO_ERROR) {
3424                     ALOGE("Failed to reopen hardware output stream, "
3425                         "samplingRate: %d, format %d, channels %d",
3426                         outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
3427                 } else {
3428                     outputDesc->mSamplingRate = config.sample_rate;
3429                     outputDesc->mChannelMask = config.channel_mask;
3430                     outputDesc->mFormat = config.format;
3431                     AudioParameter outputCmd = AudioParameter();
3432                     outputCmd.addInt(String8("set_id"), 0);
3433                     mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3434                     addOutput(mPrimaryOutput, outputDesc);
3435                 }
3436             }
3437 
3438 
3439             mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3440         }
3441     }
3442     return false;
3443 }
3444 
exit()3445 void AudioPolicyManager::exit()
3446 {
3447     {
3448         AutoMutex _l(mLock);
3449         requestExit();
3450         mWaitWorkCV.signal();
3451     }
3452     requestExitAndWait();
3453 }
3454 
testOutputIndex(audio_io_handle_t output)3455 int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
3456 {
3457     for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3458         if (output == mTestOutputs[i]) return i;
3459     }
3460     return 0;
3461 }
3462 #endif //AUDIO_POLICY_TEST
3463 
3464 // ---
3465 
addOutput(audio_io_handle_t output,sp<AudioOutputDescriptor> outputDesc)3466 void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
3467 {
3468     outputDesc->mIoHandle = output;
3469     outputDesc->mId = nextUniqueId();
3470     mOutputs.add(output, outputDesc);
3471     nextAudioPortGeneration();
3472 }
3473 
addInput(audio_io_handle_t input,sp<AudioInputDescriptor> inputDesc)3474 void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
3475 {
3476     inputDesc->mIoHandle = input;
3477     inputDesc->mId = nextUniqueId();
3478     mInputs.add(input, inputDesc);
3479     nextAudioPortGeneration();
3480 }
3481 
findIoHandlesByAddress(sp<AudioOutputDescriptor> desc,const audio_devices_t device,const String8 address,SortedVector<audio_io_handle_t> & outputs)3482 void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3483         const audio_devices_t device /*in*/,
3484         const String8 address /*in*/,
3485         SortedVector<audio_io_handle_t>& outputs /*out*/) {
3486     sp<DeviceDescriptor> devDesc =
3487         desc->mProfile->mSupportedDevices.getDevice(device, address);
3488     if (devDesc != 0) {
3489         ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3490               desc->mIoHandle, address.string());
3491         outputs.add(desc->mIoHandle);
3492     }
3493 }
3494 
checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,audio_policy_dev_state_t state,SortedVector<audio_io_handle_t> & outputs,const String8 address)3495 status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
3496                                                        audio_policy_dev_state_t state,
3497                                                        SortedVector<audio_io_handle_t>& outputs,
3498                                                        const String8 address)
3499 {
3500     audio_devices_t device = devDesc->mDeviceType;
3501     sp<AudioOutputDescriptor> desc;
3502     // erase all current sample rates, formats and channel masks
3503     devDesc->clearCapabilities();
3504 
3505     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3506         // first list already open outputs that can be routed to this device
3507         for (size_t i = 0; i < mOutputs.size(); i++) {
3508             desc = mOutputs.valueAt(i);
3509             if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
3510                 if (!deviceDistinguishesOnAddress(device)) {
3511                     ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3512                     outputs.add(mOutputs.keyAt(i));
3513                 } else {
3514                     ALOGV("  checking address match due to device 0x%x", device);
3515                     findIoHandlesByAddress(desc, device, address, outputs);
3516                 }
3517             }
3518         }
3519         // then look for output profiles that can be routed to this device
3520         SortedVector< sp<IOProfile> > profiles;
3521         for (size_t i = 0; i < mHwModules.size(); i++)
3522         {
3523             if (mHwModules[i]->mHandle == 0) {
3524                 continue;
3525             }
3526             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3527             {
3528                 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3529                 if (profile->mSupportedDevices.types() & device) {
3530                     if (!deviceDistinguishesOnAddress(device) ||
3531                             address == profile->mSupportedDevices[0]->mAddress) {
3532                         profiles.add(profile);
3533                         ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3534                     }
3535                 }
3536             }
3537         }
3538 
3539         ALOGV("  found %d profiles, %d outputs", profiles.size(), outputs.size());
3540 
3541         if (profiles.isEmpty() && outputs.isEmpty()) {
3542             ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3543             return BAD_VALUE;
3544         }
3545 
3546         // open outputs for matching profiles if needed. Direct outputs are also opened to
3547         // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3548         for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3549             sp<IOProfile> profile = profiles[profile_index];
3550 
3551             // nothing to do if one output is already opened for this profile
3552             size_t j;
3553             for (j = 0; j < outputs.size(); j++) {
3554                 desc = mOutputs.valueFor(outputs.itemAt(j));
3555                 if (!desc->isDuplicated() && desc->mProfile == profile) {
3556                     // matching profile: save the sample rates, format and channel masks supported
3557                     // by the profile in our device descriptor
3558                     devDesc->importAudioPort(profile);
3559                     break;
3560                 }
3561             }
3562             if (j != outputs.size()) {
3563                 continue;
3564             }
3565 
3566             ALOGV("opening output for device %08x with params %s profile %p",
3567                                                       device, address.string(), profile.get());
3568             desc = new AudioOutputDescriptor(profile);
3569             desc->mDevice = device;
3570             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3571             config.sample_rate = desc->mSamplingRate;
3572             config.channel_mask = desc->mChannelMask;
3573             config.format = desc->mFormat;
3574             config.offload_info.sample_rate = desc->mSamplingRate;
3575             config.offload_info.channel_mask = desc->mChannelMask;
3576             config.offload_info.format = desc->mFormat;
3577             audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3578             status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3579                                                             &output,
3580                                                             &config,
3581                                                             &desc->mDevice,
3582                                                             address,
3583                                                             &desc->mLatency,
3584                                                             desc->mFlags);
3585             if (status == NO_ERROR) {
3586                 desc->mSamplingRate = config.sample_rate;
3587                 desc->mChannelMask = config.channel_mask;
3588                 desc->mFormat = config.format;
3589 
3590                 // Here is where the out_set_parameters() for card & device gets called
3591                 if (!address.isEmpty()) {
3592                     char *param = audio_device_address_to_parameter(device, address);
3593                     mpClientInterface->setParameters(output, String8(param));
3594                     free(param);
3595                 }
3596 
3597                 // Here is where we step through and resolve any "dynamic" fields
3598                 String8 reply;
3599                 char *value;
3600                 if (profile->mSamplingRates[0] == 0) {
3601                     reply = mpClientInterface->getParameters(output,
3602                                             String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3603                     ALOGV("checkOutputsForDevice() supported sampling rates %s",
3604                               reply.string());
3605                     value = strpbrk((char *)reply.string(), "=");
3606                     if (value != NULL) {
3607                         profile->loadSamplingRates(value + 1);
3608                     }
3609                 }
3610                 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3611                     reply = mpClientInterface->getParameters(output,
3612                                                    String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3613                     ALOGV("checkOutputsForDevice() supported formats %s",
3614                               reply.string());
3615                     value = strpbrk((char *)reply.string(), "=");
3616                     if (value != NULL) {
3617                         profile->loadFormats(value + 1);
3618                     }
3619                 }
3620                 if (profile->mChannelMasks[0] == 0) {
3621                     reply = mpClientInterface->getParameters(output,
3622                                                   String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3623                     ALOGV("checkOutputsForDevice() supported channel masks %s",
3624                               reply.string());
3625                     value = strpbrk((char *)reply.string(), "=");
3626                     if (value != NULL) {
3627                         profile->loadOutChannels(value + 1);
3628                     }
3629                 }
3630                 if (((profile->mSamplingRates[0] == 0) &&
3631                          (profile->mSamplingRates.size() < 2)) ||
3632                      ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3633                          (profile->mFormats.size() < 2)) ||
3634                      ((profile->mChannelMasks[0] == 0) &&
3635                          (profile->mChannelMasks.size() < 2))) {
3636                     ALOGW("checkOutputsForDevice() missing param");
3637                     mpClientInterface->closeOutput(output);
3638                     output = AUDIO_IO_HANDLE_NONE;
3639                 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3640                             profile->mChannelMasks[0] == 0) {
3641                     mpClientInterface->closeOutput(output);
3642                     config.sample_rate = profile->pickSamplingRate();
3643                     config.channel_mask = profile->pickChannelMask();
3644                     config.format = profile->pickFormat();
3645                     config.offload_info.sample_rate = config.sample_rate;
3646                     config.offload_info.channel_mask = config.channel_mask;
3647                     config.offload_info.format = config.format;
3648                     status = mpClientInterface->openOutput(profile->mModule->mHandle,
3649                                                            &output,
3650                                                            &config,
3651                                                            &desc->mDevice,
3652                                                            address,
3653                                                            &desc->mLatency,
3654                                                            desc->mFlags);
3655                     if (status == NO_ERROR) {
3656                         desc->mSamplingRate = config.sample_rate;
3657                         desc->mChannelMask = config.channel_mask;
3658                         desc->mFormat = config.format;
3659                     } else {
3660                         output = AUDIO_IO_HANDLE_NONE;
3661                     }
3662                 }
3663 
3664                 if (output != AUDIO_IO_HANDLE_NONE) {
3665                     addOutput(output, desc);
3666                     if (deviceDistinguishesOnAddress(device) && address != "0") {
3667                         ssize_t index = mPolicyMixes.indexOfKey(address);
3668                         if (index >= 0) {
3669                             mPolicyMixes[index]->mOutput = desc;
3670                             desc->mPolicyMix = &mPolicyMixes[index]->mMix;
3671                         } else {
3672                             ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3673                                   address.string());
3674                         }
3675                     } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3676                         // no duplicated output for direct outputs and
3677                         // outputs used by dynamic policy mixes
3678                         audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
3679 
3680                         // set initial stream volume for device
3681                         applyStreamVolumes(output, device, 0, true);
3682 
3683                         //TODO: configure audio effect output stage here
3684 
3685                         // open a duplicating output thread for the new output and the primary output
3686                         duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3687                                                                                   mPrimaryOutput);
3688                         if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
3689                             // add duplicated output descriptor
3690                             sp<AudioOutputDescriptor> dupOutputDesc =
3691                                     new AudioOutputDescriptor(NULL);
3692                             dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3693                             dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3694                             dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3695                             dupOutputDesc->mFormat = desc->mFormat;
3696                             dupOutputDesc->mChannelMask = desc->mChannelMask;
3697                             dupOutputDesc->mLatency = desc->mLatency;
3698                             addOutput(duplicatedOutput, dupOutputDesc);
3699                             applyStreamVolumes(duplicatedOutput, device, 0, true);
3700                         } else {
3701                             ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3702                                     mPrimaryOutput, output);
3703                             mpClientInterface->closeOutput(output);
3704                             mOutputs.removeItem(output);
3705                             nextAudioPortGeneration();
3706                             output = AUDIO_IO_HANDLE_NONE;
3707                         }
3708                     }
3709                 }
3710             } else {
3711                 output = AUDIO_IO_HANDLE_NONE;
3712             }
3713             if (output == AUDIO_IO_HANDLE_NONE) {
3714                 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
3715                 profiles.removeAt(profile_index);
3716                 profile_index--;
3717             } else {
3718                 outputs.add(output);
3719                 devDesc->importAudioPort(profile);
3720 
3721                 if (deviceDistinguishesOnAddress(device)) {
3722                     ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3723                             device, address.string());
3724                     setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3725                             NULL/*patch handle*/, address.string());
3726                 }
3727                 ALOGV("checkOutputsForDevice(): adding output %d", output);
3728             }
3729         }
3730 
3731         if (profiles.isEmpty()) {
3732             ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3733             return BAD_VALUE;
3734         }
3735     } else { // Disconnect
3736         // check if one opened output is not needed any more after disconnecting one device
3737         for (size_t i = 0; i < mOutputs.size(); i++) {
3738             desc = mOutputs.valueAt(i);
3739             if (!desc->isDuplicated()) {
3740                 // exact match on device
3741                 if (deviceDistinguishesOnAddress(device) &&
3742                         (desc->mProfile->mSupportedDevices.types() == device)) {
3743                     findIoHandlesByAddress(desc, device, address, outputs);
3744                 } else if (!(desc->mProfile->mSupportedDevices.types()
3745                         & mAvailableOutputDevices.types())) {
3746                     ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3747                             mOutputs.keyAt(i));
3748                     outputs.add(mOutputs.keyAt(i));
3749                 }
3750             }
3751         }
3752         // Clear any profiles associated with the disconnected device.
3753         for (size_t i = 0; i < mHwModules.size(); i++)
3754         {
3755             if (mHwModules[i]->mHandle == 0) {
3756                 continue;
3757             }
3758             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3759             {
3760                 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3761                 if (profile->mSupportedDevices.types() & device) {
3762                     ALOGV("checkOutputsForDevice(): "
3763                             "clearing direct output profile %zu on module %zu", j, i);
3764                     if (profile->mSamplingRates[0] == 0) {
3765                         profile->mSamplingRates.clear();
3766                         profile->mSamplingRates.add(0);
3767                     }
3768                     if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3769                         profile->mFormats.clear();
3770                         profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3771                     }
3772                     if (profile->mChannelMasks[0] == 0) {
3773                         profile->mChannelMasks.clear();
3774                         profile->mChannelMasks.add(0);
3775                     }
3776                 }
3777             }
3778         }
3779     }
3780     return NO_ERROR;
3781 }
3782 
checkInputsForDevice(audio_devices_t device,audio_policy_dev_state_t state,SortedVector<audio_io_handle_t> & inputs,const String8 address)3783 status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3784                                                       audio_policy_dev_state_t state,
3785                                                       SortedVector<audio_io_handle_t>& inputs,
3786                                                       const String8 address)
3787 {
3788     sp<AudioInputDescriptor> desc;
3789     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3790         // first list already open inputs that can be routed to this device
3791         for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3792             desc = mInputs.valueAt(input_index);
3793             if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3794                 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3795                inputs.add(mInputs.keyAt(input_index));
3796             }
3797         }
3798 
3799         // then look for input profiles that can be routed to this device
3800         SortedVector< sp<IOProfile> > profiles;
3801         for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3802         {
3803             if (mHwModules[module_idx]->mHandle == 0) {
3804                 continue;
3805             }
3806             for (size_t profile_index = 0;
3807                  profile_index < mHwModules[module_idx]->mInputProfiles.size();
3808                  profile_index++)
3809             {
3810                 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3811 
3812                 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3813                     if (!deviceDistinguishesOnAddress(device) ||
3814                             address == profile->mSupportedDevices[0]->mAddress) {
3815                         profiles.add(profile);
3816                         ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3817                               profile_index, module_idx);
3818                     }
3819                 }
3820             }
3821         }
3822 
3823         if (profiles.isEmpty() && inputs.isEmpty()) {
3824             ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3825             return BAD_VALUE;
3826         }
3827 
3828         // open inputs for matching profiles if needed. Direct inputs are also opened to
3829         // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3830         for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3831 
3832             sp<IOProfile> profile = profiles[profile_index];
3833             // nothing to do if one input is already opened for this profile
3834             size_t input_index;
3835             for (input_index = 0; input_index < mInputs.size(); input_index++) {
3836                 desc = mInputs.valueAt(input_index);
3837                 if (desc->mProfile == profile) {
3838                     break;
3839                 }
3840             }
3841             if (input_index != mInputs.size()) {
3842                 continue;
3843             }
3844 
3845             ALOGV("opening input for device 0x%X with params %s", device, address.string());
3846             desc = new AudioInputDescriptor(profile);
3847             desc->mDevice = device;
3848             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3849             config.sample_rate = desc->mSamplingRate;
3850             config.channel_mask = desc->mChannelMask;
3851             config.format = desc->mFormat;
3852             audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3853             status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3854                                                            &input,
3855                                                            &config,
3856                                                            &desc->mDevice,
3857                                                            address,
3858                                                            AUDIO_SOURCE_MIC,
3859                                                            AUDIO_INPUT_FLAG_NONE /*FIXME*/);
3860 
3861             if (status == NO_ERROR) {
3862                 desc->mSamplingRate = config.sample_rate;
3863                 desc->mChannelMask = config.channel_mask;
3864                 desc->mFormat = config.format;
3865 
3866                 if (!address.isEmpty()) {
3867                     char *param = audio_device_address_to_parameter(device, address);
3868                     mpClientInterface->setParameters(input, String8(param));
3869                     free(param);
3870                 }
3871 
3872                 // Here is where we step through and resolve any "dynamic" fields
3873                 String8 reply;
3874                 char *value;
3875                 if (profile->mSamplingRates[0] == 0) {
3876                     reply = mpClientInterface->getParameters(input,
3877                                             String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3878                     ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3879                               reply.string());
3880                     value = strpbrk((char *)reply.string(), "=");
3881                     if (value != NULL) {
3882                         profile->loadSamplingRates(value + 1);
3883                     }
3884                 }
3885                 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3886                     reply = mpClientInterface->getParameters(input,
3887                                                    String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3888                     ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3889                     value = strpbrk((char *)reply.string(), "=");
3890                     if (value != NULL) {
3891                         profile->loadFormats(value + 1);
3892                     }
3893                 }
3894                 if (profile->mChannelMasks[0] == 0) {
3895                     reply = mpClientInterface->getParameters(input,
3896                                                   String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3897                     ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3898                               reply.string());
3899                     value = strpbrk((char *)reply.string(), "=");
3900                     if (value != NULL) {
3901                         profile->loadInChannels(value + 1);
3902                     }
3903                 }
3904                 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3905                      ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3906                      ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3907                     ALOGW("checkInputsForDevice() direct input missing param");
3908                     mpClientInterface->closeInput(input);
3909                     input = AUDIO_IO_HANDLE_NONE;
3910                 }
3911 
3912                 if (input != 0) {
3913                     addInput(input, desc);
3914                 }
3915             } // endif input != 0
3916 
3917             if (input == AUDIO_IO_HANDLE_NONE) {
3918                 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
3919                 profiles.removeAt(profile_index);
3920                 profile_index--;
3921             } else {
3922                 inputs.add(input);
3923                 ALOGV("checkInputsForDevice(): adding input %d", input);
3924             }
3925         } // end scan profiles
3926 
3927         if (profiles.isEmpty()) {
3928             ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3929             return BAD_VALUE;
3930         }
3931     } else {
3932         // Disconnect
3933         // check if one opened input is not needed any more after disconnecting one device
3934         for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3935             desc = mInputs.valueAt(input_index);
3936             if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3937                     ~AUDIO_DEVICE_BIT_IN)) {
3938                 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3939                       mInputs.keyAt(input_index));
3940                 inputs.add(mInputs.keyAt(input_index));
3941             }
3942         }
3943         // Clear any profiles associated with the disconnected device.
3944         for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3945             if (mHwModules[module_index]->mHandle == 0) {
3946                 continue;
3947             }
3948             for (size_t profile_index = 0;
3949                  profile_index < mHwModules[module_index]->mInputProfiles.size();
3950                  profile_index++) {
3951                 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
3952                 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
3953                     ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
3954                           profile_index, module_index);
3955                     if (profile->mSamplingRates[0] == 0) {
3956                         profile->mSamplingRates.clear();
3957                         profile->mSamplingRates.add(0);
3958                     }
3959                     if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3960                         profile->mFormats.clear();
3961                         profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3962                     }
3963                     if (profile->mChannelMasks[0] == 0) {
3964                         profile->mChannelMasks.clear();
3965                         profile->mChannelMasks.add(0);
3966                     }
3967                 }
3968             }
3969         }
3970     } // end disconnect
3971 
3972     return NO_ERROR;
3973 }
3974 
3975 
closeOutput(audio_io_handle_t output)3976 void AudioPolicyManager::closeOutput(audio_io_handle_t output)
3977 {
3978     ALOGV("closeOutput(%d)", output);
3979 
3980     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3981     if (outputDesc == NULL) {
3982         ALOGW("closeOutput() unknown output %d", output);
3983         return;
3984     }
3985 
3986     for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3987         if (mPolicyMixes[i]->mOutput == outputDesc) {
3988             mPolicyMixes[i]->mOutput.clear();
3989         }
3990     }
3991 
3992     // look for duplicated outputs connected to the output being removed.
3993     for (size_t i = 0; i < mOutputs.size(); i++) {
3994         sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
3995         if (dupOutputDesc->isDuplicated() &&
3996                 (dupOutputDesc->mOutput1 == outputDesc ||
3997                 dupOutputDesc->mOutput2 == outputDesc)) {
3998             sp<AudioOutputDescriptor> outputDesc2;
3999             if (dupOutputDesc->mOutput1 == outputDesc) {
4000                 outputDesc2 = dupOutputDesc->mOutput2;
4001             } else {
4002                 outputDesc2 = dupOutputDesc->mOutput1;
4003             }
4004             // As all active tracks on duplicated output will be deleted,
4005             // and as they were also referenced on the other output, the reference
4006             // count for their stream type must be adjusted accordingly on
4007             // the other output.
4008             for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
4009                 int refCount = dupOutputDesc->mRefCount[j];
4010                 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
4011             }
4012             audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4013             ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4014 
4015             mpClientInterface->closeOutput(duplicatedOutput);
4016             mOutputs.removeItem(duplicatedOutput);
4017         }
4018     }
4019 
4020     nextAudioPortGeneration();
4021 
4022     ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4023     if (index >= 0) {
4024         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4025         status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4026         mAudioPatches.removeItemsAt(index);
4027         mpClientInterface->onAudioPatchListUpdate();
4028     }
4029 
4030     AudioParameter param;
4031     param.add(String8("closing"), String8("true"));
4032     mpClientInterface->setParameters(output, param.toString());
4033 
4034     mpClientInterface->closeOutput(output);
4035     mOutputs.removeItem(output);
4036     mPreviousOutputs = mOutputs;
4037 }
4038 
closeInput(audio_io_handle_t input)4039 void AudioPolicyManager::closeInput(audio_io_handle_t input)
4040 {
4041     ALOGV("closeInput(%d)", input);
4042 
4043     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4044     if (inputDesc == NULL) {
4045         ALOGW("closeInput() unknown input %d", input);
4046         return;
4047     }
4048 
4049     nextAudioPortGeneration();
4050 
4051     ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4052     if (index >= 0) {
4053         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4054         status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4055         mAudioPatches.removeItemsAt(index);
4056         mpClientInterface->onAudioPatchListUpdate();
4057     }
4058 
4059     mpClientInterface->closeInput(input);
4060     mInputs.removeItem(input);
4061 }
4062 
getOutputsForDevice(audio_devices_t device,DefaultKeyedVector<audio_io_handle_t,sp<AudioOutputDescriptor>> openOutputs)4063 SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
4064                         DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
4065 {
4066     SortedVector<audio_io_handle_t> outputs;
4067 
4068     ALOGVV("getOutputsForDevice() device %04x", device);
4069     for (size_t i = 0; i < openOutputs.size(); i++) {
4070         ALOGVV("output %d isDuplicated=%d device=%04x",
4071                 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4072         if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4073             ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4074             outputs.add(openOutputs.keyAt(i));
4075         }
4076     }
4077     return outputs;
4078 }
4079 
vectorsEqual(SortedVector<audio_io_handle_t> & outputs1,SortedVector<audio_io_handle_t> & outputs2)4080 bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
4081                                    SortedVector<audio_io_handle_t>& outputs2)
4082 {
4083     if (outputs1.size() != outputs2.size()) {
4084         return false;
4085     }
4086     for (size_t i = 0; i < outputs1.size(); i++) {
4087         if (outputs1[i] != outputs2[i]) {
4088             return false;
4089         }
4090     }
4091     return true;
4092 }
4093 
checkOutputForStrategy(routing_strategy strategy)4094 void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
4095 {
4096     audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4097     audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4098     SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4099     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4100 
4101     // also take into account external policy-related changes: add all outputs which are
4102     // associated with policies in the "before" and "after" output vectors
4103     ALOGVV("checkOutputForStrategy(): policy related outputs");
4104     for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4105         const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4106         if (desc != 0 && desc->mPolicyMix != NULL) {
4107             srcOutputs.add(desc->mIoHandle);
4108             ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4109         }
4110     }
4111     for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4112         const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4113         if (desc != 0 && desc->mPolicyMix != NULL) {
4114             dstOutputs.add(desc->mIoHandle);
4115             ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4116         }
4117     }
4118 
4119     if (!vectorsEqual(srcOutputs,dstOutputs)) {
4120         ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4121               strategy, srcOutputs[0], dstOutputs[0]);
4122         // mute strategy while moving tracks from one output to another
4123         for (size_t i = 0; i < srcOutputs.size(); i++) {
4124             sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
4125             if (desc->isStrategyActive(strategy)) {
4126                 setStrategyMute(strategy, true, srcOutputs[i]);
4127                 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4128             }
4129         }
4130 
4131         // Move effects associated to this strategy from previous output to new output
4132         if (strategy == STRATEGY_MEDIA) {
4133             audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4134             SortedVector<audio_io_handle_t> moved;
4135             for (size_t i = 0; i < mEffects.size(); i++) {
4136                 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4137                 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4138                         effectDesc->mIo != fxOutput) {
4139                     if (moved.indexOf(effectDesc->mIo) < 0) {
4140                         ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4141                               mEffects.keyAt(i), fxOutput);
4142                         mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
4143                                                        fxOutput);
4144                         moved.add(effectDesc->mIo);
4145                     }
4146                     effectDesc->mIo = fxOutput;
4147                 }
4148             }
4149         }
4150         // Move tracks associated to this strategy from previous output to new output
4151         for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4152             if (i == AUDIO_STREAM_PATCH) {
4153                 continue;
4154             }
4155             if (getStrategy((audio_stream_type_t)i) == strategy) {
4156                 mpClientInterface->invalidateStream((audio_stream_type_t)i);
4157             }
4158         }
4159     }
4160 }
4161 
checkOutputForAllStrategies()4162 void AudioPolicyManager::checkOutputForAllStrategies()
4163 {
4164     if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4165         checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
4166     checkOutputForStrategy(STRATEGY_PHONE);
4167     if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4168         checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
4169     checkOutputForStrategy(STRATEGY_SONIFICATION);
4170     checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4171     checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
4172     checkOutputForStrategy(STRATEGY_MEDIA);
4173     checkOutputForStrategy(STRATEGY_DTMF);
4174     checkOutputForStrategy(STRATEGY_REROUTING);
4175 }
4176 
getA2dpOutput()4177 audio_io_handle_t AudioPolicyManager::getA2dpOutput()
4178 {
4179     for (size_t i = 0; i < mOutputs.size(); i++) {
4180         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4181         if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4182             return mOutputs.keyAt(i);
4183         }
4184     }
4185 
4186     return 0;
4187 }
4188 
checkA2dpSuspend()4189 void AudioPolicyManager::checkA2dpSuspend()
4190 {
4191     audio_io_handle_t a2dpOutput = getA2dpOutput();
4192     if (a2dpOutput == 0) {
4193         mA2dpSuspended = false;
4194         return;
4195     }
4196 
4197     bool isScoConnected =
4198             ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4199                     ~AUDIO_DEVICE_BIT_IN) != 0) ||
4200             ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
4201     // suspend A2DP output if:
4202     //      (NOT already suspended) &&
4203     //      ((SCO device is connected &&
4204     //       (forced usage for communication || for record is SCO))) ||
4205     //      (phone state is ringing || in call)
4206     //
4207     // restore A2DP output if:
4208     //      (Already suspended) &&
4209     //      ((SCO device is NOT connected ||
4210     //       (forced usage NOT for communication && NOT for record is SCO))) &&
4211     //      (phone state is NOT ringing && NOT in call)
4212     //
4213     if (mA2dpSuspended) {
4214         if ((!isScoConnected ||
4215              ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4216               (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4217              ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4218               (mPhoneState != AUDIO_MODE_RINGTONE))) {
4219 
4220             mpClientInterface->restoreOutput(a2dpOutput);
4221             mA2dpSuspended = false;
4222         }
4223     } else {
4224         if ((isScoConnected &&
4225              ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4226               (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4227              ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4228               (mPhoneState == AUDIO_MODE_RINGTONE))) {
4229 
4230             mpClientInterface->suspendOutput(a2dpOutput);
4231             mA2dpSuspended = true;
4232         }
4233     }
4234 }
4235 
getNewOutputDevice(audio_io_handle_t output,bool fromCache)4236 audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
4237 {
4238     audio_devices_t device = AUDIO_DEVICE_NONE;
4239 
4240     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
4241 
4242     ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4243     if (index >= 0) {
4244         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4245         if (patchDesc->mUid != mUidCached) {
4246             ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4247                   outputDesc->device(), outputDesc->mPatchHandle);
4248             return outputDesc->device();
4249         }
4250     }
4251 
4252     // check the following by order of priority to request a routing change if necessary:
4253     // 1: the strategy enforced audible is active and enforced on the output:
4254     //      use device for strategy enforced audible
4255     // 2: we are in call or the strategy phone is active on the output:
4256     //      use device for strategy phone
4257     // 3: the strategy for enforced audible is active but not enforced on the output:
4258     //      use the device for strategy enforced audible
4259     // 4: the strategy sonification is active on the output:
4260     //      use device for strategy sonification
4261     // 5: the strategy "respectful" sonification is active on the output:
4262     //      use device for strategy "respectful" sonification
4263     // 6: the strategy accessibility is active on the output:
4264     //      use device for strategy accessibility
4265     // 7: the strategy media is active on the output:
4266     //      use device for strategy media
4267     // 8: the strategy DTMF is active on the output:
4268     //      use device for strategy DTMF
4269     // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
4270     //      use device for strategy t-t-s
4271     if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4272         mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
4273         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4274     } else if (isInCall() ||
4275                     outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4276         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
4277     } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4278         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4279     } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4280         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4281     } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4282         device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
4283     } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4284         device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
4285     } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4286         device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4287     } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4288         device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
4289     } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4290         device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
4291     } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4292         device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
4293     }
4294 
4295     ALOGV("getNewOutputDevice() selected device %x", device);
4296     return device;
4297 }
4298 
getNewInputDevice(audio_io_handle_t input)4299 audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4300 {
4301     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4302 
4303     ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4304     if (index >= 0) {
4305         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4306         if (patchDesc->mUid != mUidCached) {
4307             ALOGV("getNewInputDevice() device %08x forced by patch %d",
4308                   inputDesc->mDevice, inputDesc->mPatchHandle);
4309             return inputDesc->mDevice;
4310         }
4311     }
4312 
4313     audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
4314 
4315     ALOGV("getNewInputDevice() selected device %x", device);
4316     return device;
4317 }
4318 
getStrategyForStream(audio_stream_type_t stream)4319 uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
4320     return (uint32_t)getStrategy(stream);
4321 }
4322 
getDevicesForStream(audio_stream_type_t stream)4323 audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
4324     // By checking the range of stream before calling getStrategy, we avoid
4325     // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
4326     // and then return STRATEGY_MEDIA, but we want to return the empty set.
4327     if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
4328         return AUDIO_DEVICE_NONE;
4329     }
4330     audio_devices_t devices;
4331     AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4332     devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4333     SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4334     for (size_t i = 0; i < outputs.size(); i++) {
4335         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
4336         if (outputDesc->isStrategyActive(strategy)) {
4337             devices = outputDesc->device();
4338             break;
4339         }
4340     }
4341 
4342     /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4343       and doesn't really need to.*/
4344     if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4345         devices |= AUDIO_DEVICE_OUT_SPEAKER;
4346         devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4347     }
4348 
4349     return devices;
4350 }
4351 
getStrategy(audio_stream_type_t stream)4352 AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
4353         audio_stream_type_t stream) {
4354 
4355     ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4356 
4357     // stream to strategy mapping
4358     switch (stream) {
4359     case AUDIO_STREAM_VOICE_CALL:
4360     case AUDIO_STREAM_BLUETOOTH_SCO:
4361         return STRATEGY_PHONE;
4362     case AUDIO_STREAM_RING:
4363     case AUDIO_STREAM_ALARM:
4364         return STRATEGY_SONIFICATION;
4365     case AUDIO_STREAM_NOTIFICATION:
4366         return STRATEGY_SONIFICATION_RESPECTFUL;
4367     case AUDIO_STREAM_DTMF:
4368         return STRATEGY_DTMF;
4369     default:
4370         ALOGE("unknown stream type %d", stream);
4371     case AUDIO_STREAM_SYSTEM:
4372         // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4373         // while key clicks are played produces a poor result
4374     case AUDIO_STREAM_MUSIC:
4375         return STRATEGY_MEDIA;
4376     case AUDIO_STREAM_ENFORCED_AUDIBLE:
4377         return STRATEGY_ENFORCED_AUDIBLE;
4378     case AUDIO_STREAM_TTS:
4379         return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4380     case AUDIO_STREAM_ACCESSIBILITY:
4381         return STRATEGY_ACCESSIBILITY;
4382     case AUDIO_STREAM_REROUTING:
4383         return STRATEGY_REROUTING;
4384     }
4385 }
4386 
getStrategyForAttr(const audio_attributes_t * attr)4387 uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4388     // flags to strategy mapping
4389     if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4390         return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4391     }
4392     if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4393         return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4394     }
4395 
4396     // usage to strategy mapping
4397     switch (attr->usage) {
4398     case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4399         if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4400             return (uint32_t) STRATEGY_SONIFICATION;
4401         }
4402         if (isInCall()) {
4403             return (uint32_t) STRATEGY_PHONE;
4404         }
4405         return (uint32_t) STRATEGY_ACCESSIBILITY;
4406 
4407     case AUDIO_USAGE_MEDIA:
4408     case AUDIO_USAGE_GAME:
4409     case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4410     case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4411         return (uint32_t) STRATEGY_MEDIA;
4412 
4413     case AUDIO_USAGE_VOICE_COMMUNICATION:
4414         return (uint32_t) STRATEGY_PHONE;
4415 
4416     case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4417         return (uint32_t) STRATEGY_DTMF;
4418 
4419     case AUDIO_USAGE_ALARM:
4420     case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4421         return (uint32_t) STRATEGY_SONIFICATION;
4422 
4423     case AUDIO_USAGE_NOTIFICATION:
4424     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4425     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4426     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4427     case AUDIO_USAGE_NOTIFICATION_EVENT:
4428         return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4429 
4430     case AUDIO_USAGE_UNKNOWN:
4431     default:
4432         return (uint32_t) STRATEGY_MEDIA;
4433     }
4434 }
4435 
handleNotificationRoutingForStream(audio_stream_type_t stream)4436 void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
4437     switch(stream) {
4438     case AUDIO_STREAM_MUSIC:
4439         checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4440         updateDevicesAndOutputs();
4441         break;
4442     default:
4443         break;
4444     }
4445 }
4446 
isAnyOutputActive(audio_stream_type_t streamToIgnore)4447 bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4448     for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4449         if (s == (size_t) streamToIgnore) {
4450             continue;
4451         }
4452         for (size_t i = 0; i < mOutputs.size(); i++) {
4453             const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4454             if (outputDesc->mRefCount[s] != 0) {
4455                 return true;
4456             }
4457         }
4458     }
4459     return false;
4460 }
4461 
handleEventForBeacon(int event)4462 uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4463     switch(event) {
4464     case STARTING_OUTPUT:
4465         mBeaconMuteRefCount++;
4466         break;
4467     case STOPPING_OUTPUT:
4468         if (mBeaconMuteRefCount > 0) {
4469             mBeaconMuteRefCount--;
4470         }
4471         break;
4472     case STARTING_BEACON:
4473         mBeaconPlayingRefCount++;
4474         break;
4475     case STOPPING_BEACON:
4476         if (mBeaconPlayingRefCount > 0) {
4477             mBeaconPlayingRefCount--;
4478         }
4479         break;
4480     }
4481 
4482     if (mBeaconMuteRefCount > 0) {
4483         // any playback causes beacon to be muted
4484         return setBeaconMute(true);
4485     } else {
4486         // no other playback: unmute when beacon starts playing, mute when it stops
4487         return setBeaconMute(mBeaconPlayingRefCount == 0);
4488     }
4489 }
4490 
setBeaconMute(bool mute)4491 uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4492     ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4493             mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4494     // keep track of muted state to avoid repeating mute/unmute operations
4495     if (mBeaconMuted != mute) {
4496         // mute/unmute AUDIO_STREAM_TTS on all outputs
4497         ALOGV("\t muting %d", mute);
4498         uint32_t maxLatency = 0;
4499         for (size_t i = 0; i < mOutputs.size(); i++) {
4500             sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4501             setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4502                     desc->mIoHandle,
4503                     0 /*delay*/, AUDIO_DEVICE_NONE);
4504             const uint32_t latency = desc->latency() * 2;
4505             if (latency > maxLatency) {
4506                 maxLatency = latency;
4507             }
4508         }
4509         mBeaconMuted = mute;
4510         return maxLatency;
4511     }
4512     return 0;
4513 }
4514 
getDeviceForStrategy(routing_strategy strategy,bool fromCache)4515 audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
4516                                                              bool fromCache)
4517 {
4518     uint32_t device = AUDIO_DEVICE_NONE;
4519 
4520     if (fromCache) {
4521         ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4522               strategy, mDeviceForStrategy[strategy]);
4523         return mDeviceForStrategy[strategy];
4524     }
4525     audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
4526     switch (strategy) {
4527 
4528     case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4529         device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4530         if (!device) {
4531             ALOGE("getDeviceForStrategy() no device found for "\
4532                     "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4533         }
4534         break;
4535 
4536     case STRATEGY_SONIFICATION_RESPECTFUL:
4537         if (isInCall()) {
4538             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
4539         } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
4540                 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4541             // while media is playing on a remote device, use the the sonification behavior.
4542             // Note that we test this usecase before testing if media is playing because
4543             //   the isStreamActive() method only informs about the activity of a stream, not
4544             //   if it's for local playback. Note also that we use the same delay between both tests
4545             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
4546             //user "safe" speaker if available instead of normal speaker to avoid triggering
4547             //other acoustic safety mechanisms for notification
4548             if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4549                 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4550         } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4551             // while media is playing (or has recently played), use the same device
4552             device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4553         } else {
4554             // when media is not playing anymore, fall back on the sonification behavior
4555             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
4556             //user "safe" speaker if available instead of normal speaker to avoid triggering
4557             //other acoustic safety mechanisms for notification
4558             if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4559                 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4560         }
4561 
4562         break;
4563 
4564     case STRATEGY_DTMF:
4565         if (!isInCall()) {
4566             // when off call, DTMF strategy follows the same rules as MEDIA strategy
4567             device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4568             break;
4569         }
4570         // when in call, DTMF and PHONE strategies follow the same rules
4571         // FALL THROUGH
4572 
4573     case STRATEGY_PHONE:
4574         // Force use of only devices on primary output if:
4575         // - in call AND
4576         //   - cannot route from voice call RX OR
4577         //   - audio HAL version is < 3.0 and TX device is on the primary HW module
4578         if (mPhoneState == AUDIO_MODE_IN_CALL) {
4579             audio_devices_t txDevice =
4580                     getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4581             sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4582             if (((mAvailableInputDevices.types() &
4583                     AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4584                     (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4585                          (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
4586                              AUDIO_DEVICE_API_VERSION_3_0))) {
4587                 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4588             }
4589         }
4590         // for phone strategy, we first consider the forced use and then the available devices by order
4591         // of priority
4592         switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4593         case AUDIO_POLICY_FORCE_BT_SCO:
4594             if (!isInCall() || strategy != STRATEGY_DTMF) {
4595                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
4596                 if (device) break;
4597             }
4598             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
4599             if (device) break;
4600             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
4601             if (device) break;
4602             // if SCO device is requested but no SCO device is available, fall back to default case
4603             // FALL THROUGH
4604 
4605         default:    // FORCE_NONE
4606             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
4607             if (!isInCall() &&
4608                     (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
4609                     (getA2dpOutput() != 0)) {
4610                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
4611                 if (device) break;
4612                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
4613                 if (device) break;
4614             }
4615             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
4616             if (device) break;
4617             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
4618             if (device) break;
4619             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4620             if (device) break;
4621             if (mPhoneState != AUDIO_MODE_IN_CALL) {
4622                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
4623                 if (device) break;
4624                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
4625                 if (device) break;
4626                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
4627                 if (device) break;
4628                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
4629                 if (device) break;
4630             }
4631             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
4632             if (device) break;
4633             device = mDefaultOutputDevice->mDeviceType;
4634             if (device == AUDIO_DEVICE_NONE) {
4635                 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4636             }
4637             break;
4638 
4639         case AUDIO_POLICY_FORCE_SPEAKER:
4640             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4641             // A2DP speaker when forcing to speaker output
4642             if (!isInCall() &&
4643                     (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
4644                     (getA2dpOutput() != 0)) {
4645                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
4646                 if (device) break;
4647             }
4648             if (!isInCall()) {
4649                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
4650                 if (device) break;
4651                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4652                 if (device) break;
4653                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
4654                 if (device) break;
4655                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
4656                 if (device) break;
4657                 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
4658                 if (device) break;
4659             }
4660             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4661             if (device) break;
4662             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4663             if (device) break;
4664             device = mDefaultOutputDevice->mDeviceType;
4665             if (device == AUDIO_DEVICE_NONE) {
4666                 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4667             }
4668             break;
4669         }
4670     break;
4671 
4672     case STRATEGY_SONIFICATION:
4673 
4674         // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4675         // handleIncallSonification().
4676         if (isInCall()) {
4677             device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4678             break;
4679         }
4680         // FALL THROUGH
4681 
4682     case STRATEGY_ENFORCED_AUDIBLE:
4683         // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4684         // except:
4685         //   - when in call where it doesn't default to STRATEGY_PHONE behavior
4686         //   - in countries where not enforced in which case it follows STRATEGY_MEDIA
4687 
4688         if ((strategy == STRATEGY_SONIFICATION) ||
4689                 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
4690             device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4691             if (device == AUDIO_DEVICE_NONE) {
4692                 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4693             }
4694         }
4695         // The second device used for sonification is the same as the device used by media strategy
4696         // FALL THROUGH
4697 
4698     // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4699     case STRATEGY_ACCESSIBILITY:
4700         if (strategy == STRATEGY_ACCESSIBILITY) {
4701             // do not route accessibility prompts to a digital output currently configured with a
4702             // compressed format as they would likely not be mixed and dropped.
4703             for (size_t i = 0; i < mOutputs.size(); i++) {
4704                 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4705                 audio_devices_t devices = desc->device() &
4706                     (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4707                 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4708                         devices != AUDIO_DEVICE_NONE) {
4709                     availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4710                 }
4711             }
4712         }
4713         // FALL THROUGH
4714 
4715     case STRATEGY_REROUTING:
4716     case STRATEGY_MEDIA: {
4717         uint32_t device2 = AUDIO_DEVICE_NONE;
4718         if (strategy != STRATEGY_SONIFICATION) {
4719             // no sonification on remote submix (e.g. WFD)
4720             if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4721                 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4722             }
4723         }
4724         if ((device2 == AUDIO_DEVICE_NONE) &&
4725                 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
4726                 (getA2dpOutput() != 0)) {
4727             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
4728             if (device2 == AUDIO_DEVICE_NONE) {
4729                 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
4730             }
4731             if (device2 == AUDIO_DEVICE_NONE) {
4732                 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
4733             }
4734         }
4735         if ((device2 == AUDIO_DEVICE_NONE) &&
4736             (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4737             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4738         }
4739         if (device2 == AUDIO_DEVICE_NONE) {
4740             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
4741         }
4742         if ((device2 == AUDIO_DEVICE_NONE)) {
4743             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4744         }
4745         if (device2 == AUDIO_DEVICE_NONE) {
4746             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
4747         }
4748         if (device2 == AUDIO_DEVICE_NONE) {
4749             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
4750         }
4751         if (device2 == AUDIO_DEVICE_NONE) {
4752             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4753         }
4754         if (device2 == AUDIO_DEVICE_NONE) {
4755             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
4756         }
4757         if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4758             // no sonification on aux digital (e.g. HDMI)
4759             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
4760         }
4761         if ((device2 == AUDIO_DEVICE_NONE) &&
4762                 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
4763             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
4764         }
4765         if (device2 == AUDIO_DEVICE_NONE) {
4766             device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4767         }
4768         int device3 = AUDIO_DEVICE_NONE;
4769         if (strategy == STRATEGY_MEDIA) {
4770             // ARC, SPDIF and AUX_LINE can co-exist with others.
4771             device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4772             device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
4773             device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
4774         }
4775 
4776         device2 |= device3;
4777         // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4778         // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4779         device |= device2;
4780 
4781         // If hdmi system audio mode is on, remove speaker out of output list.
4782         if ((strategy == STRATEGY_MEDIA) &&
4783             (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4784                 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4785             device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4786         }
4787 
4788         if (device) break;
4789         device = mDefaultOutputDevice->mDeviceType;
4790         if (device == AUDIO_DEVICE_NONE) {
4791             ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4792         }
4793         } break;
4794 
4795     default:
4796         ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4797         break;
4798     }
4799 
4800     ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4801     return device;
4802 }
4803 
updateDevicesAndOutputs()4804 void AudioPolicyManager::updateDevicesAndOutputs()
4805 {
4806     for (int i = 0; i < NUM_STRATEGIES; i++) {
4807         mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4808     }
4809     mPreviousOutputs = mOutputs;
4810 }
4811 
checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,audio_devices_t prevDevice,uint32_t delayMs)4812 uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
4813                                                        audio_devices_t prevDevice,
4814                                                        uint32_t delayMs)
4815 {
4816     // mute/unmute strategies using an incompatible device combination
4817     // if muting, wait for the audio in pcm buffer to be drained before proceeding
4818     // if unmuting, unmute only after the specified delay
4819     if (outputDesc->isDuplicated()) {
4820         return 0;
4821     }
4822 
4823     uint32_t muteWaitMs = 0;
4824     audio_devices_t device = outputDesc->device();
4825     bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
4826 
4827     for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4828         audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4829         curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
4830         bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4831         bool doMute = false;
4832 
4833         if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4834             doMute = true;
4835             outputDesc->mStrategyMutedByDevice[i] = true;
4836         } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4837             doMute = true;
4838             outputDesc->mStrategyMutedByDevice[i] = false;
4839         }
4840         if (doMute) {
4841             for (size_t j = 0; j < mOutputs.size(); j++) {
4842                 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
4843                 // skip output if it does not share any device with current output
4844                 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4845                         == AUDIO_DEVICE_NONE) {
4846                     continue;
4847                 }
4848                 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4849                 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4850                       mute ? "muting" : "unmuting", i, curDevice, curOutput);
4851                 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4852                 if (desc->isStrategyActive((routing_strategy)i)) {
4853                     if (mute) {
4854                         // FIXME: should not need to double latency if volume could be applied
4855                         // immediately by the audioflinger mixer. We must account for the delay
4856                         // between now and the next time the audioflinger thread for this output
4857                         // will process a buffer (which corresponds to one buffer size,
4858                         // usually 1/2 or 1/4 of the latency).
4859                         if (muteWaitMs < desc->latency() * 2) {
4860                             muteWaitMs = desc->latency() * 2;
4861                         }
4862                     }
4863                 }
4864             }
4865         }
4866     }
4867 
4868     // temporary mute output if device selection changes to avoid volume bursts due to
4869     // different per device volumes
4870     if (outputDesc->isActive() && (device != prevDevice)) {
4871         if (muteWaitMs < outputDesc->latency() * 2) {
4872             muteWaitMs = outputDesc->latency() * 2;
4873         }
4874         for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4875             if (outputDesc->isStrategyActive((routing_strategy)i)) {
4876                 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
4877                 // do tempMute unmute after twice the mute wait time
4878                 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
4879                                 muteWaitMs *2, device);
4880             }
4881         }
4882     }
4883 
4884     // wait for the PCM output buffers to empty before proceeding with the rest of the command
4885     if (muteWaitMs > delayMs) {
4886         muteWaitMs -= delayMs;
4887         usleep(muteWaitMs * 1000);
4888         return muteWaitMs;
4889     }
4890     return 0;
4891 }
4892 
setOutputDevice(audio_io_handle_t output,audio_devices_t device,bool force,int delayMs,audio_patch_handle_t * patchHandle,const char * address)4893 uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
4894                                              audio_devices_t device,
4895                                              bool force,
4896                                              int delayMs,
4897                                              audio_patch_handle_t *patchHandle,
4898                                              const char* address)
4899 {
4900     ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
4901     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
4902     AudioParameter param;
4903     uint32_t muteWaitMs;
4904 
4905     if (outputDesc->isDuplicated()) {
4906         muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4907         muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
4908         return muteWaitMs;
4909     }
4910     // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4911     // output profile
4912     if ((device != AUDIO_DEVICE_NONE) &&
4913             ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
4914         return 0;
4915     }
4916 
4917     // filter devices according to output selected
4918     device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
4919 
4920     audio_devices_t prevDevice = outputDesc->mDevice;
4921 
4922     ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4923 
4924     if (device != AUDIO_DEVICE_NONE) {
4925         outputDesc->mDevice = device;
4926     }
4927     muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4928 
4929     // Do not change the routing if:
4930     //      the requested device is AUDIO_DEVICE_NONE
4931     //      OR the requested device is the same as current device
4932     //  AND force is not specified
4933     //  AND the output is connected by a valid audio patch.
4934     // Doing this check here allows the caller to call setOutputDevice() without conditions
4935     if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4936             outputDesc->mPatchHandle != 0) {
4937         ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4938               device, output);
4939         return muteWaitMs;
4940     }
4941 
4942     ALOGV("setOutputDevice() changing device");
4943 
4944     // do the routing
4945     if (device == AUDIO_DEVICE_NONE) {
4946         resetOutputDevice(output, delayMs, NULL);
4947     } else {
4948         DeviceVector deviceList = (address == NULL) ?
4949                 mAvailableOutputDevices.getDevicesFromType(device)
4950                 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4951         if (!deviceList.isEmpty()) {
4952             struct audio_patch patch;
4953             outputDesc->toAudioPortConfig(&patch.sources[0]);
4954             patch.num_sources = 1;
4955             patch.num_sinks = 0;
4956             for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4957                 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
4958                 patch.num_sinks++;
4959             }
4960             ssize_t index;
4961             if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4962                 index = mAudioPatches.indexOfKey(*patchHandle);
4963             } else {
4964                 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4965             }
4966             sp< AudioPatch> patchDesc;
4967             audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4968             if (index >= 0) {
4969                 patchDesc = mAudioPatches.valueAt(index);
4970                 afPatchHandle = patchDesc->mAfPatchHandle;
4971             }
4972 
4973             status_t status = mpClientInterface->createAudioPatch(&patch,
4974                                                                    &afPatchHandle,
4975                                                                    delayMs);
4976             ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4977                     "num_sources %d num_sinks %d",
4978                                        status, afPatchHandle, patch.num_sources, patch.num_sinks);
4979             if (status == NO_ERROR) {
4980                 if (index < 0) {
4981                     patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4982                                                &patch, mUidCached);
4983                     addAudioPatch(patchDesc->mHandle, patchDesc);
4984                 } else {
4985                     patchDesc->mPatch = patch;
4986                 }
4987                 patchDesc->mAfPatchHandle = afPatchHandle;
4988                 patchDesc->mUid = mUidCached;
4989                 if (patchHandle) {
4990                     *patchHandle = patchDesc->mHandle;
4991                 }
4992                 outputDesc->mPatchHandle = patchDesc->mHandle;
4993                 nextAudioPortGeneration();
4994                 mpClientInterface->onAudioPatchListUpdate();
4995             }
4996         }
4997 
4998         // inform all input as well
4999         for (size_t i = 0; i < mInputs.size(); i++) {
5000             const sp<AudioInputDescriptor>  inputDescriptor = mInputs.valueAt(i);
5001             if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
5002                 AudioParameter inputCmd = AudioParameter();
5003                 ALOGV("%s: inform input %d of device:%d", __func__,
5004                       inputDescriptor->mIoHandle, device);
5005                 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5006                 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5007                                                  inputCmd.toString(),
5008                                                  delayMs);
5009             }
5010         }
5011     }
5012 
5013     // update stream volumes according to new device
5014     applyStreamVolumes(output, device, delayMs);
5015 
5016     return muteWaitMs;
5017 }
5018 
resetOutputDevice(audio_io_handle_t output,int delayMs,audio_patch_handle_t * patchHandle)5019 status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
5020                                                int delayMs,
5021                                                audio_patch_handle_t *patchHandle)
5022 {
5023     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
5024     ssize_t index;
5025     if (patchHandle) {
5026         index = mAudioPatches.indexOfKey(*patchHandle);
5027     } else {
5028         index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
5029     }
5030     if (index < 0) {
5031         return INVALID_OPERATION;
5032     }
5033     sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5034     status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
5035     ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5036     outputDesc->mPatchHandle = 0;
5037     removeAudioPatch(patchDesc->mHandle);
5038     nextAudioPortGeneration();
5039     mpClientInterface->onAudioPatchListUpdate();
5040     return status;
5041 }
5042 
setInputDevice(audio_io_handle_t input,audio_devices_t device,bool force,audio_patch_handle_t * patchHandle)5043 status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5044                                             audio_devices_t device,
5045                                             bool force,
5046                                             audio_patch_handle_t *patchHandle)
5047 {
5048     status_t status = NO_ERROR;
5049 
5050     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5051     if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5052         inputDesc->mDevice = device;
5053 
5054         DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5055         if (!deviceList.isEmpty()) {
5056             struct audio_patch patch;
5057             inputDesc->toAudioPortConfig(&patch.sinks[0]);
5058             // AUDIO_SOURCE_HOTWORD is for internal use only:
5059             // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
5060             if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5061                     !inputDesc->mIsSoundTrigger) {
5062                 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5063             }
5064             patch.num_sinks = 1;
5065             //only one input device for now
5066             deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
5067             patch.num_sources = 1;
5068             ssize_t index;
5069             if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5070                 index = mAudioPatches.indexOfKey(*patchHandle);
5071             } else {
5072                 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5073             }
5074             sp< AudioPatch> patchDesc;
5075             audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5076             if (index >= 0) {
5077                 patchDesc = mAudioPatches.valueAt(index);
5078                 afPatchHandle = patchDesc->mAfPatchHandle;
5079             }
5080 
5081             status_t status = mpClientInterface->createAudioPatch(&patch,
5082                                                                   &afPatchHandle,
5083                                                                   0);
5084             ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
5085                                                                           status, afPatchHandle);
5086             if (status == NO_ERROR) {
5087                 if (index < 0) {
5088                     patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5089                                                &patch, mUidCached);
5090                     addAudioPatch(patchDesc->mHandle, patchDesc);
5091                 } else {
5092                     patchDesc->mPatch = patch;
5093                 }
5094                 patchDesc->mAfPatchHandle = afPatchHandle;
5095                 patchDesc->mUid = mUidCached;
5096                 if (patchHandle) {
5097                     *patchHandle = patchDesc->mHandle;
5098                 }
5099                 inputDesc->mPatchHandle = patchDesc->mHandle;
5100                 nextAudioPortGeneration();
5101                 mpClientInterface->onAudioPatchListUpdate();
5102             }
5103         }
5104     }
5105     return status;
5106 }
5107 
resetInputDevice(audio_io_handle_t input,audio_patch_handle_t * patchHandle)5108 status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5109                                               audio_patch_handle_t *patchHandle)
5110 {
5111     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5112     ssize_t index;
5113     if (patchHandle) {
5114         index = mAudioPatches.indexOfKey(*patchHandle);
5115     } else {
5116         index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5117     }
5118     if (index < 0) {
5119         return INVALID_OPERATION;
5120     }
5121     sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5122     status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
5123     ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5124     inputDesc->mPatchHandle = 0;
5125     removeAudioPatch(patchDesc->mHandle);
5126     nextAudioPortGeneration();
5127     mpClientInterface->onAudioPatchListUpdate();
5128     return status;
5129 }
5130 
getInputProfile(audio_devices_t device,String8 address,uint32_t & samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_input_flags_t flags)5131 sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
5132                                                    String8 address,
5133                                                    uint32_t& samplingRate,
5134                                                    audio_format_t format,
5135                                                    audio_channel_mask_t channelMask,
5136                                                    audio_input_flags_t flags)
5137 {
5138     // Choose an input profile based on the requested capture parameters: select the first available
5139     // profile supporting all requested parameters.
5140 
5141     for (size_t i = 0; i < mHwModules.size(); i++)
5142     {
5143         if (mHwModules[i]->mHandle == 0) {
5144             continue;
5145         }
5146         for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5147         {
5148             sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
5149             // profile->log();
5150             if (profile->isCompatibleProfile(device, address, samplingRate,
5151                                              &samplingRate /*updatedSamplingRate*/,
5152                                              format, channelMask, (audio_output_flags_t) flags)) {
5153 
5154                 return profile;
5155             }
5156         }
5157     }
5158     return NULL;
5159 }
5160 
5161 
getDeviceAndMixForInputSource(audio_source_t inputSource,AudioMix ** policyMix)5162 audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
5163                                                             AudioMix **policyMix)
5164 {
5165     audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5166                                             ~AUDIO_DEVICE_BIT_IN;
5167 
5168     for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5169         if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5170             continue;
5171         }
5172         for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5173             if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5174                     mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5175                (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5176                     mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5177                 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
5178                     if (policyMix != NULL) {
5179                         *policyMix = &mPolicyMixes[i]->mMix;
5180                     }
5181                     return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5182                 }
5183                 break;
5184             }
5185         }
5186     }
5187 
5188     return getDeviceForInputSource(inputSource);
5189 }
5190 
getDeviceForInputSource(audio_source_t inputSource)5191 audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5192 {
5193     uint32_t device = AUDIO_DEVICE_NONE;
5194     audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5195                                             ~AUDIO_DEVICE_BIT_IN;
5196 
5197     switch (inputSource) {
5198     case AUDIO_SOURCE_VOICE_UPLINK:
5199       if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
5200           device = AUDIO_DEVICE_IN_VOICE_CALL;
5201           break;
5202       }
5203       break;
5204 
5205     case AUDIO_SOURCE_DEFAULT:
5206     case AUDIO_SOURCE_MIC:
5207     if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5208         device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
5209     } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5210         (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5211         device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5212     } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5213         device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5214     } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5215         device = AUDIO_DEVICE_IN_USB_DEVICE;
5216     } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5217         device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5218     }
5219     break;
5220 
5221     case AUDIO_SOURCE_VOICE_COMMUNICATION:
5222         // Allow only use of devices on primary input if in call and HAL does not support routing
5223         // to voice call path.
5224         if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5225                 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5226             availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5227         }
5228 
5229         switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5230         case AUDIO_POLICY_FORCE_BT_SCO:
5231             // if SCO device is requested but no SCO device is available, fall back to default case
5232             if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5233                 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5234                 break;
5235             }
5236             // FALL THROUGH
5237 
5238         default:    // FORCE_NONE
5239             if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5240                 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5241             } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5242                 device = AUDIO_DEVICE_IN_USB_DEVICE;
5243             } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5244                 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5245             }
5246             break;
5247 
5248         case AUDIO_POLICY_FORCE_SPEAKER:
5249             if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5250                 device = AUDIO_DEVICE_IN_BACK_MIC;
5251             } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5252                 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5253             }
5254             break;
5255         }
5256         break;
5257 
5258     case AUDIO_SOURCE_VOICE_RECOGNITION:
5259     case AUDIO_SOURCE_HOTWORD:
5260         if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
5261                 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5262             device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5263         } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5264             device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5265         } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5266             device = AUDIO_DEVICE_IN_USB_DEVICE;
5267         } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5268             device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5269         }
5270         break;
5271     case AUDIO_SOURCE_CAMCORDER:
5272         if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5273             device = AUDIO_DEVICE_IN_BACK_MIC;
5274         } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5275             device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5276         }
5277         break;
5278     case AUDIO_SOURCE_VOICE_DOWNLINK:
5279     case AUDIO_SOURCE_VOICE_CALL:
5280         if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
5281             device = AUDIO_DEVICE_IN_VOICE_CALL;
5282         }
5283         break;
5284     case AUDIO_SOURCE_REMOTE_SUBMIX:
5285         if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
5286             device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5287         }
5288         break;
5289      case AUDIO_SOURCE_FM_TUNER:
5290         if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5291             device = AUDIO_DEVICE_IN_FM_TUNER;
5292         }
5293         break;
5294     default:
5295         ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5296         break;
5297     }
5298     ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5299     return device;
5300 }
5301 
isVirtualInputDevice(audio_devices_t device)5302 bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
5303 {
5304     if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5305         device &= ~AUDIO_DEVICE_BIT_IN;
5306         if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5307             return true;
5308     }
5309     return false;
5310 }
5311 
deviceDistinguishesOnAddress(audio_devices_t device)5312 bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
5313     return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
5314 }
5315 
getActiveInput(bool ignoreVirtualInputs)5316 audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
5317 {
5318     for (size_t i = 0; i < mInputs.size(); i++) {
5319         const sp<AudioInputDescriptor>  input_descriptor = mInputs.valueAt(i);
5320         if ((input_descriptor->mRefCount > 0)
5321                 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5322             return mInputs.keyAt(i);
5323         }
5324     }
5325     return 0;
5326 }
5327 
activeInputsCount() const5328 uint32_t AudioPolicyManager::activeInputsCount() const
5329 {
5330     uint32_t count = 0;
5331     for (size_t i = 0; i < mInputs.size(); i++) {
5332         const sp<AudioInputDescriptor>  desc = mInputs.valueAt(i);
5333         if (desc->mRefCount > 0) {
5334             count++;
5335         }
5336     }
5337     return count;
5338 }
5339 
5340 
getDeviceForVolume(audio_devices_t device)5341 audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
5342 {
5343     if (device == AUDIO_DEVICE_NONE) {
5344         // this happens when forcing a route update and no track is active on an output.
5345         // In this case the returned category is not important.
5346         device =  AUDIO_DEVICE_OUT_SPEAKER;
5347     } else if (popcount(device) > 1) {
5348         // Multiple device selection is either:
5349         //  - speaker + one other device: give priority to speaker in this case.
5350         //  - one A2DP device + another device: happens with duplicated output. In this case
5351         // retain the device on the A2DP output as the other must not correspond to an active
5352         // selection if not the speaker.
5353         //  - HDMI-CEC system audio mode only output: give priority to available item in order.
5354         if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5355             device = AUDIO_DEVICE_OUT_SPEAKER;
5356         } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5357             device = AUDIO_DEVICE_OUT_HDMI_ARC;
5358         } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5359             device = AUDIO_DEVICE_OUT_AUX_LINE;
5360         } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5361             device = AUDIO_DEVICE_OUT_SPDIF;
5362         } else {
5363             device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5364         }
5365     }
5366 
5367     /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5368     if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5369         device = AUDIO_DEVICE_OUT_SPEAKER;
5370 
5371     ALOGW_IF(popcount(device) != 1,
5372             "getDeviceForVolume() invalid device combination: %08x",
5373             device);
5374 
5375     return device;
5376 }
5377 
getDeviceCategory(audio_devices_t device)5378 AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
5379 {
5380     switch(getDeviceForVolume(device)) {
5381         case AUDIO_DEVICE_OUT_EARPIECE:
5382             return DEVICE_CATEGORY_EARPIECE;
5383         case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5384         case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5385         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5386         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5387         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5388         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5389             return DEVICE_CATEGORY_HEADSET;
5390         case AUDIO_DEVICE_OUT_LINE:
5391         case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5392         /*USB?  Remote submix?*/
5393             return DEVICE_CATEGORY_EXT_MEDIA;
5394         case AUDIO_DEVICE_OUT_SPEAKER:
5395         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5396         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
5397         case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5398         case AUDIO_DEVICE_OUT_USB_DEVICE:
5399         case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5400         default:
5401             return DEVICE_CATEGORY_SPEAKER;
5402     }
5403 }
5404 
5405 /* static */
volIndexToAmpl(audio_devices_t device,const StreamDescriptor & streamDesc,int indexInUi)5406 float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
5407         int indexInUi)
5408 {
5409     device_category deviceCategory = getDeviceCategory(device);
5410     const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5411 
5412     // the volume index in the UI is relative to the min and max volume indices for this stream type
5413     int nbSteps = 1 + curve[VOLMAX].mIndex -
5414             curve[VOLMIN].mIndex;
5415     int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5416             (streamDesc.mIndexMax - streamDesc.mIndexMin);
5417 
5418     // find what part of the curve this index volume belongs to, or if it's out of bounds
5419     int segment = 0;
5420     if (volIdx < curve[VOLMIN].mIndex) {         // out of bounds
5421         return 0.0f;
5422     } else if (volIdx < curve[VOLKNEE1].mIndex) {
5423         segment = 0;
5424     } else if (volIdx < curve[VOLKNEE2].mIndex) {
5425         segment = 1;
5426     } else if (volIdx <= curve[VOLMAX].mIndex) {
5427         segment = 2;
5428     } else {                                                               // out of bounds
5429         return 1.0f;
5430     }
5431 
5432     // linear interpolation in the attenuation table in dB
5433     float decibels = curve[segment].mDBAttenuation +
5434             ((float)(volIdx - curve[segment].mIndex)) *
5435                 ( (curve[segment+1].mDBAttenuation -
5436                         curve[segment].mDBAttenuation) /
5437                     ((float)(curve[segment+1].mIndex -
5438                             curve[segment].mIndex)) );
5439 
5440     float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5441 
5442     ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5443             curve[segment].mIndex, volIdx,
5444             curve[segment+1].mIndex,
5445             curve[segment].mDBAttenuation,
5446             decibels,
5447             curve[segment+1].mDBAttenuation,
5448             amplification);
5449 
5450     return amplification;
5451 }
5452 
5453 const AudioPolicyManager::VolumeCurvePoint
5454     AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
5455     {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5456 };
5457 
5458 const AudioPolicyManager::VolumeCurvePoint
5459     AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
5460     {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5461 };
5462 
5463 const AudioPolicyManager::VolumeCurvePoint
5464     AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5465     {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5466 };
5467 
5468 const AudioPolicyManager::VolumeCurvePoint
5469     AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
5470     {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5471 };
5472 
5473 const AudioPolicyManager::VolumeCurvePoint
5474     AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
5475     {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
5476 };
5477 
5478 const AudioPolicyManager::VolumeCurvePoint
5479     AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
5480     {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5481 };
5482 
5483 const AudioPolicyManager::VolumeCurvePoint
5484     AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
5485     {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5486 };
5487 
5488 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5489 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5490 // AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5491 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5492 
5493 const AudioPolicyManager::VolumeCurvePoint
5494     AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5495     {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5496 };
5497 
5498 const AudioPolicyManager::VolumeCurvePoint
5499     AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
5500     {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5501 };
5502 
5503 const AudioPolicyManager::VolumeCurvePoint
5504     AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5505     {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5506 };
5507 
5508 const AudioPolicyManager::VolumeCurvePoint
5509     AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
5510     {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5511 };
5512 
5513 const AudioPolicyManager::VolumeCurvePoint
5514     AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
5515     {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5516 };
5517 
5518 const AudioPolicyManager::VolumeCurvePoint
5519     AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5520     {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5521 };
5522 
5523 const AudioPolicyManager::VolumeCurvePoint
5524     AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5525     {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5526 };
5527 
5528 const AudioPolicyManager::VolumeCurvePoint
5529     AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5530     {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5531 };
5532 
5533 const AudioPolicyManager::VolumeCurvePoint
5534             *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5535                                                    [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
5536     { // AUDIO_STREAM_VOICE_CALL
5537         sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5538         sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5539         sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5540         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5541     },
5542     { // AUDIO_STREAM_SYSTEM
5543         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5544         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5545         sDefaultSystemVolumeCurve,  // DEVICE_CATEGORY_EARPIECE
5546         sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5547     },
5548     { // AUDIO_STREAM_RING
5549         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5550         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5551         sDefaultVolumeCurve,  // DEVICE_CATEGORY_EARPIECE
5552         sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5553     },
5554     { // AUDIO_STREAM_MUSIC
5555         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5556         sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5557         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5558         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5559     },
5560     { // AUDIO_STREAM_ALARM
5561         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5562         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5563         sDefaultVolumeCurve,  // DEVICE_CATEGORY_EARPIECE
5564         sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5565     },
5566     { // AUDIO_STREAM_NOTIFICATION
5567         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5568         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5569         sDefaultVolumeCurve,  // DEVICE_CATEGORY_EARPIECE
5570         sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5571     },
5572     { // AUDIO_STREAM_BLUETOOTH_SCO
5573         sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5574         sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5575         sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5576         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5577     },
5578     { // AUDIO_STREAM_ENFORCED_AUDIBLE
5579         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5580         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5581         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5582         sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5583     },
5584     {  // AUDIO_STREAM_DTMF
5585         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5586         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5587         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5588         sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5589     },
5590     { // AUDIO_STREAM_TTS
5591       // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5592         sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5593         sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5594         sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5595         sSilentVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5596     },
5597     { // AUDIO_STREAM_ACCESSIBILITY
5598         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5599         sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5600         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5601         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5602     },
5603     { // AUDIO_STREAM_REROUTING
5604         sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5605         sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5606         sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5607         sFullScaleVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5608     },
5609     { // AUDIO_STREAM_PATCH
5610         sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5611         sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5612         sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5613         sFullScaleVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
5614     },
5615 };
5616 
initializeVolumeCurves()5617 void AudioPolicyManager::initializeVolumeCurves()
5618 {
5619     for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5620         for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5621             mStreams[i].mVolumeCurve[j] =
5622                     sVolumeProfiles[i][j];
5623         }
5624     }
5625 
5626     // Check availability of DRC on speaker path: if available, override some of the speaker curves
5627     if (mSpeakerDrcEnabled) {
5628         mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5629                 sDefaultSystemVolumeCurveDrc;
5630         mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5631                 sSpeakerSonificationVolumeCurveDrc;
5632         mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5633                 sSpeakerSonificationVolumeCurveDrc;
5634         mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5635                 sSpeakerSonificationVolumeCurveDrc;
5636         mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5637                 sSpeakerMediaVolumeCurveDrc;
5638         mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5639                 sSpeakerMediaVolumeCurveDrc;
5640     }
5641 }
5642 
computeVolume(audio_stream_type_t stream,int index,audio_io_handle_t output,audio_devices_t device)5643 float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
5644                                             int index,
5645                                             audio_io_handle_t output,
5646                                             audio_devices_t device)
5647 {
5648     float volume = 1.0;
5649     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
5650     StreamDescriptor &streamDesc = mStreams[stream];
5651 
5652     if (device == AUDIO_DEVICE_NONE) {
5653         device = outputDesc->device();
5654     }
5655 
5656     volume = volIndexToAmpl(device, streamDesc, index);
5657 
5658     // if a headset is connected, apply the following rules to ring tones and notifications
5659     // to avoid sound level bursts in user's ears:
5660     // - always attenuate ring tones and notifications volume by 6dB
5661     // - if music is playing, always limit the volume to current music volume,
5662     // with a minimum threshold at -36dB so that notification is always perceived.
5663     const routing_strategy stream_strategy = getStrategy(stream);
5664     if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5665             AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5666             AUDIO_DEVICE_OUT_WIRED_HEADSET |
5667             AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5668         ((stream_strategy == STRATEGY_SONIFICATION)
5669                 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
5670                 || (stream == AUDIO_STREAM_SYSTEM)
5671                 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
5672                     (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
5673         streamDesc.mCanBeMuted) {
5674         volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5675         // when the phone is ringing we must consider that music could have been paused just before
5676         // by the music application and behave as if music was active if the last music track was
5677         // just stopped
5678         if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
5679                 mLimitRingtoneVolume) {
5680             audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
5681             float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5682                                mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
5683                                output,
5684                                musicDevice);
5685             float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5686                                 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5687             if (volume > minVol) {
5688                 volume = minVol;
5689                 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5690             }
5691         }
5692     }
5693 
5694     return volume;
5695 }
5696 
checkAndSetVolume(audio_stream_type_t stream,int index,audio_io_handle_t output,audio_devices_t device,int delayMs,bool force)5697 status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
5698                                                    int index,
5699                                                    audio_io_handle_t output,
5700                                                    audio_devices_t device,
5701                                                    int delayMs,
5702                                                    bool force)
5703 {
5704 
5705     // do not change actual stream volume if the stream is muted
5706     if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5707         ALOGVV("checkAndSetVolume() stream %d muted count %d",
5708               stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5709         return NO_ERROR;
5710     }
5711 
5712     // do not change in call volume if bluetooth is connected and vice versa
5713     if ((stream == AUDIO_STREAM_VOICE_CALL &&
5714             mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5715         (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5716                 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
5717         ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
5718              stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
5719         return INVALID_OPERATION;
5720     }
5721 
5722     float volume = computeVolume(stream, index, output, device);
5723     // unit gain if rerouting to external policy
5724     if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5725         ssize_t index = mOutputs.indexOfKey(output);
5726         if (index >= 0) {
5727             sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
5728             if (outputDesc->mPolicyMix != NULL) {
5729                 ALOGV("max gain when rerouting for output=%d", output);
5730                 volume = 1.0f;
5731             }
5732         }
5733 
5734     }
5735     // We actually change the volume if:
5736     // - the float value returned by computeVolume() changed
5737     // - the force flag is set
5738     if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5739             force) {
5740         mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5741         ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5742         // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5743         // enabled
5744         if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5745             mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
5746         }
5747         mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
5748     }
5749 
5750     if (stream == AUDIO_STREAM_VOICE_CALL ||
5751         stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5752         float voiceVolume;
5753         // Force voice volume to max for bluetooth SCO as volume is managed by the headset
5754         if (stream == AUDIO_STREAM_VOICE_CALL) {
5755             voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5756         } else {
5757             voiceVolume = 1.0;
5758         }
5759 
5760         if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5761             mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5762             mLastVoiceVolume = voiceVolume;
5763         }
5764     }
5765 
5766     return NO_ERROR;
5767 }
5768 
applyStreamVolumes(audio_io_handle_t output,audio_devices_t device,int delayMs,bool force)5769 void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
5770                                                 audio_devices_t device,
5771                                                 int delayMs,
5772                                                 bool force)
5773 {
5774     ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5775 
5776     for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5777         if (stream == AUDIO_STREAM_PATCH) {
5778             continue;
5779         }
5780         checkAndSetVolume((audio_stream_type_t)stream,
5781                           mStreams[stream].getVolumeIndex(device),
5782                           output,
5783                           device,
5784                           delayMs,
5785                           force);
5786     }
5787 }
5788 
setStrategyMute(routing_strategy strategy,bool on,audio_io_handle_t output,int delayMs,audio_devices_t device)5789 void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
5790                                              bool on,
5791                                              audio_io_handle_t output,
5792                                              int delayMs,
5793                                              audio_devices_t device)
5794 {
5795     ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
5796     for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5797         if (stream == AUDIO_STREAM_PATCH) {
5798             continue;
5799         }
5800         if (getStrategy((audio_stream_type_t)stream) == strategy) {
5801             setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
5802         }
5803     }
5804 }
5805 
setStreamMute(audio_stream_type_t stream,bool on,audio_io_handle_t output,int delayMs,audio_devices_t device)5806 void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
5807                                            bool on,
5808                                            audio_io_handle_t output,
5809                                            int delayMs,
5810                                            audio_devices_t device)
5811 {
5812     StreamDescriptor &streamDesc = mStreams[stream];
5813     sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
5814     if (device == AUDIO_DEVICE_NONE) {
5815         device = outputDesc->device();
5816     }
5817 
5818     ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5819           stream, on, output, outputDesc->mMuteCount[stream], device);
5820 
5821     if (on) {
5822         if (outputDesc->mMuteCount[stream] == 0) {
5823             if (streamDesc.mCanBeMuted &&
5824                     ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5825                      (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
5826                 checkAndSetVolume(stream, 0, output, device, delayMs);
5827             }
5828         }
5829         // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5830         outputDesc->mMuteCount[stream]++;
5831     } else {
5832         if (outputDesc->mMuteCount[stream] == 0) {
5833             ALOGV("setStreamMute() unmuting non muted stream!");
5834             return;
5835         }
5836         if (--outputDesc->mMuteCount[stream] == 0) {
5837             checkAndSetVolume(stream,
5838                               streamDesc.getVolumeIndex(device),
5839                               output,
5840                               device,
5841                               delayMs);
5842         }
5843     }
5844 }
5845 
handleIncallSonification(audio_stream_type_t stream,bool starting,bool stateChange)5846 void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
5847                                                       bool starting, bool stateChange)
5848 {
5849     // if the stream pertains to sonification strategy and we are in call we must
5850     // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5851     // in the device used for phone strategy and play the tone if the selected device does not
5852     // interfere with the device used for phone strategy
5853     // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5854     // many times as there are active tracks on the output
5855     const routing_strategy stream_strategy = getStrategy(stream);
5856     if ((stream_strategy == STRATEGY_SONIFICATION) ||
5857             ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
5858         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
5859         ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5860                 stream, starting, outputDesc->mDevice, stateChange);
5861         if (outputDesc->mRefCount[stream]) {
5862             int muteCount = 1;
5863             if (stateChange) {
5864                 muteCount = outputDesc->mRefCount[stream];
5865             }
5866             if (audio_is_low_visibility(stream)) {
5867                 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5868                 for (int i = 0; i < muteCount; i++) {
5869                     setStreamMute(stream, starting, mPrimaryOutput);
5870                 }
5871             } else {
5872                 ALOGV("handleIncallSonification() high visibility");
5873                 if (outputDesc->device() &
5874                         getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5875                     ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5876                     for (int i = 0; i < muteCount; i++) {
5877                         setStreamMute(stream, starting, mPrimaryOutput);
5878                     }
5879                 }
5880                 if (starting) {
5881                     mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5882                                                  AUDIO_STREAM_VOICE_CALL);
5883                 } else {
5884                     mpClientInterface->stopTone();
5885                 }
5886             }
5887         }
5888     }
5889 }
5890 
isInCall()5891 bool AudioPolicyManager::isInCall()
5892 {
5893     return isStateInCall(mPhoneState);
5894 }
5895 
isStateInCall(int state)5896 bool AudioPolicyManager::isStateInCall(int state) {
5897     return ((state == AUDIO_MODE_IN_CALL) ||
5898             (state == AUDIO_MODE_IN_COMMUNICATION));
5899 }
5900 
getMaxEffectsCpuLoad()5901 uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
5902 {
5903     return MAX_EFFECTS_CPU_LOAD;
5904 }
5905 
getMaxEffectsMemory()5906 uint32_t AudioPolicyManager::getMaxEffectsMemory()
5907 {
5908     return MAX_EFFECTS_MEMORY;
5909 }
5910 
5911 
5912 // --- AudioOutputDescriptor class implementation
5913 
AudioOutputDescriptor(const sp<IOProfile> & profile)5914 AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
5915         const sp<IOProfile>& profile)
5916     : mId(0), mIoHandle(0), mLatency(0),
5917     mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
5918     mPatchHandle(0),
5919     mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5920 {
5921     // clear usage count for all stream types
5922     for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5923         mRefCount[i] = 0;
5924         mCurVolume[i] = -1.0;
5925         mMuteCount[i] = 0;
5926         mStopTime[i] = 0;
5927     }
5928     for (int i = 0; i < NUM_STRATEGIES; i++) {
5929         mStrategyMutedByDevice[i] = false;
5930     }
5931     if (profile != NULL) {
5932         mFlags = (audio_output_flags_t)profile->mFlags;
5933         mSamplingRate = profile->pickSamplingRate();
5934         mFormat = profile->pickFormat();
5935         mChannelMask = profile->pickChannelMask();
5936         if (profile->mGains.size() > 0) {
5937             profile->mGains[0]->getDefaultConfig(&mGain);
5938         }
5939     }
5940 }
5941 
device() const5942 audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
5943 {
5944     if (isDuplicated()) {
5945         return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5946     } else {
5947         return mDevice;
5948     }
5949 }
5950 
latency()5951 uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
5952 {
5953     if (isDuplicated()) {
5954         return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5955     } else {
5956         return mLatency;
5957     }
5958 }
5959 
sharesHwModuleWith(const sp<AudioOutputDescriptor> outputDesc)5960 bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
5961         const sp<AudioOutputDescriptor> outputDesc)
5962 {
5963     if (isDuplicated()) {
5964         return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5965     } else if (outputDesc->isDuplicated()){
5966         return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5967     } else {
5968         return (mProfile->mModule == outputDesc->mProfile->mModule);
5969     }
5970 }
5971 
changeRefCount(audio_stream_type_t stream,int delta)5972 void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
5973                                                                    int delta)
5974 {
5975     // forward usage count change to attached outputs
5976     if (isDuplicated()) {
5977         mOutput1->changeRefCount(stream, delta);
5978         mOutput2->changeRefCount(stream, delta);
5979     }
5980     if ((delta + (int)mRefCount[stream]) < 0) {
5981         ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5982               delta, stream, mRefCount[stream]);
5983         mRefCount[stream] = 0;
5984         return;
5985     }
5986     mRefCount[stream] += delta;
5987     ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5988 }
5989 
supportedDevices()5990 audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
5991 {
5992     if (isDuplicated()) {
5993         return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5994     } else {
5995         return mProfile->mSupportedDevices.types() ;
5996     }
5997 }
5998 
isActive(uint32_t inPastMs) const5999 bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
6000 {
6001     return isStrategyActive(NUM_STRATEGIES, inPastMs);
6002 }
6003 
isStrategyActive(routing_strategy strategy,uint32_t inPastMs,nsecs_t sysTime) const6004 bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
6005                                                                        uint32_t inPastMs,
6006                                                                        nsecs_t sysTime) const
6007 {
6008     if ((sysTime == 0) && (inPastMs != 0)) {
6009         sysTime = systemTime();
6010     }
6011     for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6012         if (i == AUDIO_STREAM_PATCH) {
6013             continue;
6014         }
6015         if (((getStrategy((audio_stream_type_t)i) == strategy) ||
6016                 (NUM_STRATEGIES == strategy)) &&
6017                 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
6018             return true;
6019         }
6020     }
6021     return false;
6022 }
6023 
isStreamActive(audio_stream_type_t stream,uint32_t inPastMs,nsecs_t sysTime) const6024 bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
6025                                                                        uint32_t inPastMs,
6026                                                                        nsecs_t sysTime) const
6027 {
6028     if (mRefCount[stream] != 0) {
6029         return true;
6030     }
6031     if (inPastMs == 0) {
6032         return false;
6033     }
6034     if (sysTime == 0) {
6035         sysTime = systemTime();
6036     }
6037     if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
6038         return true;
6039     }
6040     return false;
6041 }
6042 
toAudioPortConfig(struct audio_port_config * dstConfig,const struct audio_port_config * srcConfig) const6043 void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
6044                                                  struct audio_port_config *dstConfig,
6045                                                  const struct audio_port_config *srcConfig) const
6046 {
6047     ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
6048 
6049     dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6050                             AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6051     if (srcConfig != NULL) {
6052         dstConfig->config_mask |= srcConfig->config_mask;
6053     }
6054     AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6055 
6056     dstConfig->id = mId;
6057     dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
6058     dstConfig->type = AUDIO_PORT_TYPE_MIX;
6059     dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6060     dstConfig->ext.mix.handle = mIoHandle;
6061     dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
6062 }
6063 
toAudioPort(struct audio_port * port) const6064 void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6065                                                     struct audio_port *port) const
6066 {
6067     ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
6068     mProfile->toAudioPort(port);
6069     port->id = mId;
6070     toAudioPortConfig(&port->active_config);
6071     port->ext.mix.hw_module = mProfile->mModule->mHandle;
6072     port->ext.mix.handle = mIoHandle;
6073     port->ext.mix.latency_class =
6074             mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6075 }
6076 
dump(int fd)6077 status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
6078 {
6079     const size_t SIZE = 256;
6080     char buffer[SIZE];
6081     String8 result;
6082 
6083     snprintf(buffer, SIZE, " ID: %d\n", mId);
6084     result.append(buffer);
6085     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6086     result.append(buffer);
6087     snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6088     result.append(buffer);
6089     snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6090     result.append(buffer);
6091     snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6092     result.append(buffer);
6093     snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6094     result.append(buffer);
6095     snprintf(buffer, SIZE, " Devices %08x\n", device());
6096     result.append(buffer);
6097     snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6098     result.append(buffer);
6099     for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6100         snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n",
6101                  i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
6102         result.append(buffer);
6103     }
6104     write(fd, result.string(), result.size());
6105 
6106     return NO_ERROR;
6107 }
6108 
6109 // --- AudioInputDescriptor class implementation
6110 
AudioInputDescriptor(const sp<IOProfile> & profile)6111 AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
6112     : mId(0), mIoHandle(0),
6113       mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
6114       mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
6115 {
6116     if (profile != NULL) {
6117         mSamplingRate = profile->pickSamplingRate();
6118         mFormat = profile->pickFormat();
6119         mChannelMask = profile->pickChannelMask();
6120         if (profile->mGains.size() > 0) {
6121             profile->mGains[0]->getDefaultConfig(&mGain);
6122         }
6123     }
6124 }
6125 
toAudioPortConfig(struct audio_port_config * dstConfig,const struct audio_port_config * srcConfig) const6126 void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
6127                                                    struct audio_port_config *dstConfig,
6128                                                    const struct audio_port_config *srcConfig) const
6129 {
6130     ALOG_ASSERT(mProfile != 0,
6131                 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
6132     dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6133                             AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6134     if (srcConfig != NULL) {
6135         dstConfig->config_mask |= srcConfig->config_mask;
6136     }
6137 
6138     AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6139 
6140     dstConfig->id = mId;
6141     dstConfig->role = AUDIO_PORT_ROLE_SINK;
6142     dstConfig->type = AUDIO_PORT_TYPE_MIX;
6143     dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6144     dstConfig->ext.mix.handle = mIoHandle;
6145     dstConfig->ext.mix.usecase.source = mInputSource;
6146 }
6147 
toAudioPort(struct audio_port * port) const6148 void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6149                                                     struct audio_port *port) const
6150 {
6151     ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6152 
6153     mProfile->toAudioPort(port);
6154     port->id = mId;
6155     toAudioPortConfig(&port->active_config);
6156     port->ext.mix.hw_module = mProfile->mModule->mHandle;
6157     port->ext.mix.handle = mIoHandle;
6158     port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6159 }
6160 
dump(int fd)6161 status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
6162 {
6163     const size_t SIZE = 256;
6164     char buffer[SIZE];
6165     String8 result;
6166 
6167     snprintf(buffer, SIZE, " ID: %d\n", mId);
6168     result.append(buffer);
6169     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6170     result.append(buffer);
6171     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6172     result.append(buffer);
6173     snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6174     result.append(buffer);
6175     snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6176     result.append(buffer);
6177     snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6178     result.append(buffer);
6179     snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6180     result.append(buffer);
6181 
6182     write(fd, result.string(), result.size());
6183 
6184     return NO_ERROR;
6185 }
6186 
6187 // --- StreamDescriptor class implementation
6188 
StreamDescriptor()6189 AudioPolicyManager::StreamDescriptor::StreamDescriptor()
6190     :   mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6191 {
6192     mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6193 }
6194 
getVolumeIndex(audio_devices_t device)6195 int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
6196 {
6197     device = AudioPolicyManager::getDeviceForVolume(device);
6198     // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6199     if (mIndexCur.indexOfKey(device) < 0) {
6200         device = AUDIO_DEVICE_OUT_DEFAULT;
6201     }
6202     return mIndexCur.valueFor(device);
6203 }
6204 
dump(int fd)6205 void AudioPolicyManager::StreamDescriptor::dump(int fd)
6206 {
6207     const size_t SIZE = 256;
6208     char buffer[SIZE];
6209     String8 result;
6210 
6211     snprintf(buffer, SIZE, "%s         %02d         %02d         ",
6212              mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6213     result.append(buffer);
6214     for (size_t i = 0; i < mIndexCur.size(); i++) {
6215         snprintf(buffer, SIZE, "%04x : %02d, ",
6216                  mIndexCur.keyAt(i),
6217                  mIndexCur.valueAt(i));
6218         result.append(buffer);
6219     }
6220     result.append("\n");
6221 
6222     write(fd, result.string(), result.size());
6223 }
6224 
6225 // --- EffectDescriptor class implementation
6226 
dump(int fd)6227 status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
6228 {
6229     const size_t SIZE = 256;
6230     char buffer[SIZE];
6231     String8 result;
6232 
6233     snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6234     result.append(buffer);
6235     snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6236     result.append(buffer);
6237     snprintf(buffer, SIZE, " Session: %d\n", mSession);
6238     result.append(buffer);
6239     snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
6240     result.append(buffer);
6241     snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
6242     result.append(buffer);
6243     write(fd, result.string(), result.size());
6244 
6245     return NO_ERROR;
6246 }
6247 
6248 // --- HwModule class implementation
6249 
HwModule(const char * name)6250 AudioPolicyManager::HwModule::HwModule(const char *name)
6251     : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6252       mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
6253 {
6254 }
6255 
~HwModule()6256 AudioPolicyManager::HwModule::~HwModule()
6257 {
6258     for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6259         mOutputProfiles[i]->mSupportedDevices.clear();
6260     }
6261     for (size_t i = 0; i < mInputProfiles.size(); i++) {
6262         mInputProfiles[i]->mSupportedDevices.clear();
6263     }
6264     free((void *)mName);
6265 }
6266 
loadInput(cnode * root)6267 status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6268 {
6269     cnode *node = root->first_child;
6270 
6271     sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6272 
6273     while (node) {
6274         if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6275             profile->loadSamplingRates((char *)node->value);
6276         } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6277             profile->loadFormats((char *)node->value);
6278         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6279             profile->loadInChannels((char *)node->value);
6280         } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6281             profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6282                                                            mDeclaredDevices);
6283         } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6284             profile->mFlags = parseInputFlagNames((char *)node->value);
6285         } else if (strcmp(node->name, GAINS_TAG) == 0) {
6286             profile->loadGains(node);
6287         }
6288         node = node->next;
6289     }
6290     ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6291             "loadInput() invalid supported devices");
6292     ALOGW_IF(profile->mChannelMasks.size() == 0,
6293             "loadInput() invalid supported channel masks");
6294     ALOGW_IF(profile->mSamplingRates.size() == 0,
6295             "loadInput() invalid supported sampling rates");
6296     ALOGW_IF(profile->mFormats.size() == 0,
6297             "loadInput() invalid supported formats");
6298     if (!profile->mSupportedDevices.isEmpty() &&
6299             (profile->mChannelMasks.size() != 0) &&
6300             (profile->mSamplingRates.size() != 0) &&
6301             (profile->mFormats.size() != 0)) {
6302 
6303         ALOGV("loadInput() adding input Supported Devices %04x",
6304               profile->mSupportedDevices.types());
6305 
6306         mInputProfiles.add(profile);
6307         return NO_ERROR;
6308     } else {
6309         return BAD_VALUE;
6310     }
6311 }
6312 
loadOutput(cnode * root)6313 status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6314 {
6315     cnode *node = root->first_child;
6316 
6317     sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6318 
6319     while (node) {
6320         if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6321             profile->loadSamplingRates((char *)node->value);
6322         } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6323             profile->loadFormats((char *)node->value);
6324         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6325             profile->loadOutChannels((char *)node->value);
6326         } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6327             profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6328                                                            mDeclaredDevices);
6329         } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6330             profile->mFlags = parseOutputFlagNames((char *)node->value);
6331         } else if (strcmp(node->name, GAINS_TAG) == 0) {
6332             profile->loadGains(node);
6333         }
6334         node = node->next;
6335     }
6336     ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6337             "loadOutput() invalid supported devices");
6338     ALOGW_IF(profile->mChannelMasks.size() == 0,
6339             "loadOutput() invalid supported channel masks");
6340     ALOGW_IF(profile->mSamplingRates.size() == 0,
6341             "loadOutput() invalid supported sampling rates");
6342     ALOGW_IF(profile->mFormats.size() == 0,
6343             "loadOutput() invalid supported formats");
6344     if (!profile->mSupportedDevices.isEmpty() &&
6345             (profile->mChannelMasks.size() != 0) &&
6346             (profile->mSamplingRates.size() != 0) &&
6347             (profile->mFormats.size() != 0)) {
6348 
6349         ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6350               profile->mSupportedDevices.types(), profile->mFlags);
6351 
6352         mOutputProfiles.add(profile);
6353         return NO_ERROR;
6354     } else {
6355         return BAD_VALUE;
6356     }
6357 }
6358 
loadDevice(cnode * root)6359 status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6360 {
6361     cnode *node = root->first_child;
6362 
6363     audio_devices_t type = AUDIO_DEVICE_NONE;
6364     while (node) {
6365         if (strcmp(node->name, DEVICE_TYPE) == 0) {
6366             type = parseDeviceNames((char *)node->value);
6367             break;
6368         }
6369         node = node->next;
6370     }
6371     if (type == AUDIO_DEVICE_NONE ||
6372             (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6373         ALOGW("loadDevice() bad type %08x", type);
6374         return BAD_VALUE;
6375     }
6376     sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6377     deviceDesc->mModule = this;
6378 
6379     node = root->first_child;
6380     while (node) {
6381         if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6382             deviceDesc->mAddress = String8((char *)node->value);
6383         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6384             if (audio_is_input_device(type)) {
6385                 deviceDesc->loadInChannels((char *)node->value);
6386             } else {
6387                 deviceDesc->loadOutChannels((char *)node->value);
6388             }
6389         } else if (strcmp(node->name, GAINS_TAG) == 0) {
6390             deviceDesc->loadGains(node);
6391         }
6392         node = node->next;
6393     }
6394 
6395     ALOGV("loadDevice() adding device name %s type %08x address %s",
6396           deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6397 
6398     mDeclaredDevices.add(deviceDesc);
6399 
6400     return NO_ERROR;
6401 }
6402 
addOutputProfile(String8 name,const audio_config_t * config,audio_devices_t device,String8 address)6403 status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6404                                                   audio_devices_t device, String8 address)
6405 {
6406     sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6407 
6408     profile->mSamplingRates.add(config->sample_rate);
6409     profile->mChannelMasks.add(config->channel_mask);
6410     profile->mFormats.add(config->format);
6411 
6412     sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6413     devDesc->mAddress = address;
6414     profile->mSupportedDevices.add(devDesc);
6415 
6416     mOutputProfiles.add(profile);
6417 
6418     return NO_ERROR;
6419 }
6420 
removeOutputProfile(String8 name)6421 status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6422 {
6423     for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6424         if (mOutputProfiles[i]->mName == name) {
6425             mOutputProfiles.removeAt(i);
6426             break;
6427         }
6428     }
6429 
6430     return NO_ERROR;
6431 }
6432 
addInputProfile(String8 name,const audio_config_t * config,audio_devices_t device,String8 address)6433 status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6434                                                   audio_devices_t device, String8 address)
6435 {
6436     sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6437 
6438     profile->mSamplingRates.add(config->sample_rate);
6439     profile->mChannelMasks.add(config->channel_mask);
6440     profile->mFormats.add(config->format);
6441 
6442     sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6443     devDesc->mAddress = address;
6444     profile->mSupportedDevices.add(devDesc);
6445 
6446     ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6447 
6448     mInputProfiles.add(profile);
6449 
6450     return NO_ERROR;
6451 }
6452 
removeInputProfile(String8 name)6453 status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6454 {
6455     for (size_t i = 0; i < mInputProfiles.size(); i++) {
6456         if (mInputProfiles[i]->mName == name) {
6457             mInputProfiles.removeAt(i);
6458             break;
6459         }
6460     }
6461 
6462     return NO_ERROR;
6463 }
6464 
6465 
dump(int fd)6466 void AudioPolicyManager::HwModule::dump(int fd)
6467 {
6468     const size_t SIZE = 256;
6469     char buffer[SIZE];
6470     String8 result;
6471 
6472     snprintf(buffer, SIZE, "  - name: %s\n", mName);
6473     result.append(buffer);
6474     snprintf(buffer, SIZE, "  - handle: %d\n", mHandle);
6475     result.append(buffer);
6476     snprintf(buffer, SIZE, "  - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6477     result.append(buffer);
6478     write(fd, result.string(), result.size());
6479     if (mOutputProfiles.size()) {
6480         write(fd, "  - outputs:\n", strlen("  - outputs:\n"));
6481         for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6482             snprintf(buffer, SIZE, "    output %zu:\n", i);
6483             write(fd, buffer, strlen(buffer));
6484             mOutputProfiles[i]->dump(fd);
6485         }
6486     }
6487     if (mInputProfiles.size()) {
6488         write(fd, "  - inputs:\n", strlen("  - inputs:\n"));
6489         for (size_t i = 0; i < mInputProfiles.size(); i++) {
6490             snprintf(buffer, SIZE, "    input %zu:\n", i);
6491             write(fd, buffer, strlen(buffer));
6492             mInputProfiles[i]->dump(fd);
6493         }
6494     }
6495     if (mDeclaredDevices.size()) {
6496         write(fd, "  - devices:\n", strlen("  - devices:\n"));
6497         for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6498             mDeclaredDevices[i]->dump(fd, 4, i);
6499         }
6500     }
6501 }
6502 
6503 // --- AudioPort class implementation
6504 
6505 
AudioPort(const String8 & name,audio_port_type_t type,audio_port_role_t role,const sp<HwModule> & module)6506 AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6507           audio_port_role_t role, const sp<HwModule>& module) :
6508     mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
6509 {
6510     mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6511                     ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6512 }
6513 
toAudioPort(struct audio_port * port) const6514 void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6515 {
6516     port->role = mRole;
6517     port->type = mType;
6518     unsigned int i;
6519     for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
6520         if (mSamplingRates[i] != 0) {
6521             port->sample_rates[i] = mSamplingRates[i];
6522         }
6523     }
6524     port->num_sample_rates = i;
6525     for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
6526         if (mChannelMasks[i] != 0) {
6527             port->channel_masks[i] = mChannelMasks[i];
6528         }
6529     }
6530     port->num_channel_masks = i;
6531     for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
6532         if (mFormats[i] != 0) {
6533             port->formats[i] = mFormats[i];
6534         }
6535     }
6536     port->num_formats = i;
6537 
6538     ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
6539 
6540     for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6541         port->gains[i] = mGains[i]->mGain;
6542     }
6543     port->num_gains = i;
6544 }
6545 
importAudioPort(const sp<AudioPort> port)6546 void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6547     for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6548         const uint32_t rate = port->mSamplingRates.itemAt(k);
6549         if (rate != 0) { // skip "dynamic" rates
6550             bool hasRate = false;
6551             for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6552                 if (rate == mSamplingRates.itemAt(l)) {
6553                     hasRate = true;
6554                     break;
6555                 }
6556             }
6557             if (!hasRate) { // never import a sampling rate twice
6558                 mSamplingRates.add(rate);
6559             }
6560         }
6561     }
6562     for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6563         const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6564         if (mask != 0) { // skip "dynamic" masks
6565             bool hasMask = false;
6566             for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6567                 if (mask == mChannelMasks.itemAt(l)) {
6568                     hasMask = true;
6569                     break;
6570                 }
6571             }
6572             if (!hasMask) { // never import a channel mask twice
6573                 mChannelMasks.add(mask);
6574             }
6575         }
6576     }
6577     for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6578         const audio_format_t format = port->mFormats.itemAt(k);
6579         if (format != 0) { // skip "dynamic" formats
6580             bool hasFormat = false;
6581             for (size_t l = 0 ; l < mFormats.size() ; l++) {
6582                 if (format == mFormats.itemAt(l)) {
6583                     hasFormat = true;
6584                     break;
6585                 }
6586             }
6587             if (!hasFormat) { // never import a channel mask twice
6588                 mFormats.add(format);
6589             }
6590         }
6591     }
6592     for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6593         sp<AudioGain> gain = port->mGains.itemAt(k);
6594         if (gain != 0) {
6595             bool hasGain = false;
6596             for (size_t l = 0 ; l < mGains.size() ; l++) {
6597                 if (gain == mGains.itemAt(l)) {
6598                     hasGain = true;
6599                     break;
6600                 }
6601             }
6602             if (!hasGain) { // never import a gain twice
6603                 mGains.add(gain);
6604             }
6605         }
6606     }
6607 }
6608 
clearCapabilities()6609 void AudioPolicyManager::AudioPort::clearCapabilities() {
6610     mChannelMasks.clear();
6611     mFormats.clear();
6612     mSamplingRates.clear();
6613     mGains.clear();
6614 }
6615 
loadSamplingRates(char * name)6616 void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6617 {
6618     char *str = strtok(name, "|");
6619 
6620     // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6621     // rates should be read from the output stream after it is opened for the first time
6622     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6623         mSamplingRates.add(0);
6624         return;
6625     }
6626 
6627     while (str != NULL) {
6628         uint32_t rate = atoi(str);
6629         if (rate != 0) {
6630             ALOGV("loadSamplingRates() adding rate %d", rate);
6631             mSamplingRates.add(rate);
6632         }
6633         str = strtok(NULL, "|");
6634     }
6635 }
6636 
loadFormats(char * name)6637 void AudioPolicyManager::AudioPort::loadFormats(char *name)
6638 {
6639     char *str = strtok(name, "|");
6640 
6641     // by convention, "0' in the first entry in mFormats indicates the supported formats
6642     // should be read from the output stream after it is opened for the first time
6643     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6644         mFormats.add(AUDIO_FORMAT_DEFAULT);
6645         return;
6646     }
6647 
6648     while (str != NULL) {
6649         audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6650                                                              ARRAY_SIZE(sFormatNameToEnumTable),
6651                                                              str);
6652         if (format != AUDIO_FORMAT_DEFAULT) {
6653             mFormats.add(format);
6654         }
6655         str = strtok(NULL, "|");
6656     }
6657 }
6658 
loadInChannels(char * name)6659 void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6660 {
6661     const char *str = strtok(name, "|");
6662 
6663     ALOGV("loadInChannels() %s", name);
6664 
6665     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6666         mChannelMasks.add(0);
6667         return;
6668     }
6669 
6670     while (str != NULL) {
6671         audio_channel_mask_t channelMask =
6672                 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6673                                                    ARRAY_SIZE(sInChannelsNameToEnumTable),
6674                                                    str);
6675         if (channelMask != 0) {
6676             ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6677             mChannelMasks.add(channelMask);
6678         }
6679         str = strtok(NULL, "|");
6680     }
6681 }
6682 
loadOutChannels(char * name)6683 void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6684 {
6685     const char *str = strtok(name, "|");
6686 
6687     ALOGV("loadOutChannels() %s", name);
6688 
6689     // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6690     // masks should be read from the output stream after it is opened for the first time
6691     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6692         mChannelMasks.add(0);
6693         return;
6694     }
6695 
6696     while (str != NULL) {
6697         audio_channel_mask_t channelMask =
6698                 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6699                                                    ARRAY_SIZE(sOutChannelsNameToEnumTable),
6700                                                    str);
6701         if (channelMask != 0) {
6702             mChannelMasks.add(channelMask);
6703         }
6704         str = strtok(NULL, "|");
6705     }
6706     return;
6707 }
6708 
loadGainMode(char * name)6709 audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6710 {
6711     const char *str = strtok(name, "|");
6712 
6713     ALOGV("loadGainMode() %s", name);
6714     audio_gain_mode_t mode = 0;
6715     while (str != NULL) {
6716         mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6717                                                 ARRAY_SIZE(sGainModeNameToEnumTable),
6718                                                 str);
6719         str = strtok(NULL, "|");
6720     }
6721     return mode;
6722 }
6723 
loadGain(cnode * root,int index)6724 void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
6725 {
6726     cnode *node = root->first_child;
6727 
6728     sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
6729 
6730     while (node) {
6731         if (strcmp(node->name, GAIN_MODE) == 0) {
6732             gain->mGain.mode = loadGainMode((char *)node->value);
6733         } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
6734             if (mUseInChannelMask) {
6735                 gain->mGain.channel_mask =
6736                         (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6737                                                            ARRAY_SIZE(sInChannelsNameToEnumTable),
6738                                                            (char *)node->value);
6739             } else {
6740                 gain->mGain.channel_mask =
6741                         (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6742                                                            ARRAY_SIZE(sOutChannelsNameToEnumTable),
6743                                                            (char *)node->value);
6744             }
6745         } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6746             gain->mGain.min_value = atoi((char *)node->value);
6747         } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6748             gain->mGain.max_value = atoi((char *)node->value);
6749         } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6750             gain->mGain.default_value = atoi((char *)node->value);
6751         } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6752             gain->mGain.step_value = atoi((char *)node->value);
6753         } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6754             gain->mGain.min_ramp_ms = atoi((char *)node->value);
6755         } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6756             gain->mGain.max_ramp_ms = atoi((char *)node->value);
6757         }
6758         node = node->next;
6759     }
6760 
6761     ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6762           gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6763 
6764     if (gain->mGain.mode == 0) {
6765         return;
6766     }
6767     mGains.add(gain);
6768 }
6769 
loadGains(cnode * root)6770 void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6771 {
6772     cnode *node = root->first_child;
6773     int index = 0;
6774     while (node) {
6775         ALOGV("loadGains() loading gain %s", node->name);
6776         loadGain(node, index++);
6777         node = node->next;
6778     }
6779 }
6780 
checkExactSamplingRate(uint32_t samplingRate) const6781 status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
6782 {
6783     if (mSamplingRates.isEmpty()) {
6784         return NO_ERROR;
6785     }
6786 
6787     for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6788         if (mSamplingRates[i] == samplingRate) {
6789             return NO_ERROR;
6790         }
6791     }
6792     return BAD_VALUE;
6793 }
6794 
checkCompatibleSamplingRate(uint32_t samplingRate,uint32_t * updatedSamplingRate) const6795 status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6796         uint32_t *updatedSamplingRate) const
6797 {
6798     if (mSamplingRates.isEmpty()) {
6799         return NO_ERROR;
6800     }
6801 
6802     // Search for the closest supported sampling rate that is above (preferred)
6803     // or below (acceptable) the desired sampling rate, within a permitted ratio.
6804     // The sampling rates do not need to be sorted in ascending order.
6805     ssize_t maxBelow = -1;
6806     ssize_t minAbove = -1;
6807     uint32_t candidate;
6808     for (size_t i = 0; i < mSamplingRates.size(); i++) {
6809         candidate = mSamplingRates[i];
6810         if (candidate == samplingRate) {
6811             if (updatedSamplingRate != NULL) {
6812                 *updatedSamplingRate = candidate;
6813             }
6814             return NO_ERROR;
6815         }
6816         // candidate < desired
6817         if (candidate < samplingRate) {
6818             if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6819                 maxBelow = i;
6820             }
6821         // candidate > desired
6822         } else {
6823             if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6824                 minAbove = i;
6825             }
6826         }
6827     }
6828     // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6829     // TODO Move these assumptions out.
6830     static const uint32_t kMaxDownSampleRatio = 6;  // beyond this aliasing occurs
6831     static const uint32_t kMaxUpSampleRatio = 256;  // beyond this sample rate inaccuracies occur
6832                                                     // due to approximation by an int32_t of the
6833                                                     // phase increments
6834     // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6835     if (minAbove >= 0) {
6836         candidate = mSamplingRates[minAbove];
6837         if (candidate / kMaxDownSampleRatio <= samplingRate) {
6838             if (updatedSamplingRate != NULL) {
6839                 *updatedSamplingRate = candidate;
6840             }
6841             return NO_ERROR;
6842         }
6843     }
6844     // But if we have to up-sample from a lower sampling rate, that's OK.
6845     if (maxBelow >= 0) {
6846         candidate = mSamplingRates[maxBelow];
6847         if (candidate * kMaxUpSampleRatio >= samplingRate) {
6848             if (updatedSamplingRate != NULL) {
6849                 *updatedSamplingRate = candidate;
6850             }
6851             return NO_ERROR;
6852         }
6853     }
6854     // leave updatedSamplingRate unmodified
6855     return BAD_VALUE;
6856 }
6857 
checkExactChannelMask(audio_channel_mask_t channelMask) const6858 status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6859 {
6860     if (mChannelMasks.isEmpty()) {
6861         return NO_ERROR;
6862     }
6863 
6864     for (size_t i = 0; i < mChannelMasks.size(); i++) {
6865         if (mChannelMasks[i] == channelMask) {
6866             return NO_ERROR;
6867         }
6868     }
6869     return BAD_VALUE;
6870 }
6871 
checkCompatibleChannelMask(audio_channel_mask_t channelMask) const6872 status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6873         const
6874 {
6875     if (mChannelMasks.isEmpty()) {
6876         return NO_ERROR;
6877     }
6878 
6879     const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6880     for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6881         // FIXME Does not handle multi-channel automatic conversions yet
6882         audio_channel_mask_t supported = mChannelMasks[i];
6883         if (supported == channelMask) {
6884             return NO_ERROR;
6885         }
6886         if (isRecordThread) {
6887             // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6888             // FIXME Abstract this out to a table.
6889             if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6890                     && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6891                 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6892                     || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6893                 return NO_ERROR;
6894             }
6895         }
6896     }
6897     return BAD_VALUE;
6898 }
6899 
checkFormat(audio_format_t format) const6900 status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6901 {
6902     if (mFormats.isEmpty()) {
6903         return NO_ERROR;
6904     }
6905 
6906     for (size_t i = 0; i < mFormats.size(); i ++) {
6907         if (mFormats[i] == format) {
6908             return NO_ERROR;
6909         }
6910     }
6911     return BAD_VALUE;
6912 }
6913 
6914 
pickSamplingRate() const6915 uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6916 {
6917     // special case for uninitialized dynamic profile
6918     if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6919         return 0;
6920     }
6921 
6922     // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6923     // channel count / sampling rate combination chosen will be supported by the connected
6924     // sink
6925     if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6926             (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6927         uint32_t samplingRate = UINT_MAX;
6928         for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6929             if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6930                 samplingRate = mSamplingRates[i];
6931             }
6932         }
6933         return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6934     }
6935 
6936     uint32_t samplingRate = 0;
6937     uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6938 
6939     // For mixed output and inputs, use max mixer sampling rates. Do not
6940     // limit sampling rate otherwise
6941     if (mType != AUDIO_PORT_TYPE_MIX) {
6942         maxRate = UINT_MAX;
6943     }
6944     for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6945         if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6946             samplingRate = mSamplingRates[i];
6947         }
6948     }
6949     return samplingRate;
6950 }
6951 
pickChannelMask() const6952 audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6953 {
6954     // special case for uninitialized dynamic profile
6955     if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6956         return AUDIO_CHANNEL_NONE;
6957     }
6958     audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
6959 
6960     // For direct outputs, pick minimum channel count: this helps ensuring that the
6961     // channel count / sampling rate combination chosen will be supported by the connected
6962     // sink
6963     if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6964             (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6965         uint32_t channelCount = UINT_MAX;
6966         for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6967             uint32_t cnlCount;
6968             if (mUseInChannelMask) {
6969                 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6970             } else {
6971                 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6972             }
6973             if ((cnlCount < channelCount) && (cnlCount > 0)) {
6974                 channelMask = mChannelMasks[i];
6975                 channelCount = cnlCount;
6976             }
6977         }
6978         return channelMask;
6979     }
6980 
6981     uint32_t channelCount = 0;
6982     uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6983 
6984     // For mixed output and inputs, use max mixer channel count. Do not
6985     // limit channel count otherwise
6986     if (mType != AUDIO_PORT_TYPE_MIX) {
6987         maxCount = UINT_MAX;
6988     }
6989     for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6990         uint32_t cnlCount;
6991         if (mUseInChannelMask) {
6992             cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6993         } else {
6994             cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6995         }
6996         if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6997             channelMask = mChannelMasks[i];
6998             channelCount = cnlCount;
6999         }
7000     }
7001     return channelMask;
7002 }
7003 
7004 /* format in order of increasing preference */
7005 const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
7006         AUDIO_FORMAT_DEFAULT,
7007         AUDIO_FORMAT_PCM_16_BIT,
7008         AUDIO_FORMAT_PCM_8_24_BIT,
7009         AUDIO_FORMAT_PCM_24_BIT_PACKED,
7010         AUDIO_FORMAT_PCM_32_BIT,
7011         AUDIO_FORMAT_PCM_FLOAT,
7012 };
7013 
compareFormats(audio_format_t format1,audio_format_t format2)7014 int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
7015                                                   audio_format_t format2)
7016 {
7017     // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
7018     // compressed format and better than any PCM format. This is by design of pickFormat()
7019     if (!audio_is_linear_pcm(format1)) {
7020         if (!audio_is_linear_pcm(format2)) {
7021             return 0;
7022         }
7023         return 1;
7024     }
7025     if (!audio_is_linear_pcm(format2)) {
7026         return -1;
7027     }
7028 
7029     int index1 = -1, index2 = -1;
7030     for (size_t i = 0;
7031             (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
7032             i ++) {
7033         if (sPcmFormatCompareTable[i] == format1) {
7034             index1 = i;
7035         }
7036         if (sPcmFormatCompareTable[i] == format2) {
7037             index2 = i;
7038         }
7039     }
7040     // format1 not found => index1 < 0 => format2 > format1
7041     // format2 not found => index2 < 0 => format2 < format1
7042     return index1 - index2;
7043 }
7044 
pickFormat() const7045 audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
7046 {
7047     // special case for uninitialized dynamic profile
7048     if (mFormats.size() == 1 && mFormats[0] == 0) {
7049         return AUDIO_FORMAT_DEFAULT;
7050     }
7051 
7052     audio_format_t format = AUDIO_FORMAT_DEFAULT;
7053     audio_format_t bestFormat =
7054             AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
7055                 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
7056     // For mixed output and inputs, use best mixer output format. Do not
7057     // limit format otherwise
7058     if ((mType != AUDIO_PORT_TYPE_MIX) ||
7059             ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
7060              (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
7061         bestFormat = AUDIO_FORMAT_INVALID;
7062     }
7063 
7064     for (size_t i = 0; i < mFormats.size(); i ++) {
7065         if ((compareFormats(mFormats[i], format) > 0) &&
7066                 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7067             format = mFormats[i];
7068         }
7069     }
7070     return format;
7071 }
7072 
checkGain(const struct audio_gain_config * gainConfig,int index) const7073 status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7074                                                   int index) const
7075 {
7076     if (index < 0 || (size_t)index >= mGains.size()) {
7077         return BAD_VALUE;
7078     }
7079     return mGains[index]->checkConfig(gainConfig);
7080 }
7081 
dump(int fd,int spaces) const7082 void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7083 {
7084     const size_t SIZE = 256;
7085     char buffer[SIZE];
7086     String8 result;
7087 
7088     if (mName.size() != 0) {
7089         snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7090         result.append(buffer);
7091     }
7092 
7093     if (mSamplingRates.size() != 0) {
7094         snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7095         result.append(buffer);
7096         for (size_t i = 0; i < mSamplingRates.size(); i++) {
7097             if (i == 0 && mSamplingRates[i] == 0) {
7098                 snprintf(buffer, SIZE, "Dynamic");
7099             } else {
7100                 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7101             }
7102             result.append(buffer);
7103             result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7104         }
7105         result.append("\n");
7106     }
7107 
7108     if (mChannelMasks.size() != 0) {
7109         snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7110         result.append(buffer);
7111         for (size_t i = 0; i < mChannelMasks.size(); i++) {
7112             ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7113 
7114             if (i == 0 && mChannelMasks[i] == 0) {
7115                 snprintf(buffer, SIZE, "Dynamic");
7116             } else {
7117                 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7118             }
7119             result.append(buffer);
7120             result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7121         }
7122         result.append("\n");
7123     }
7124 
7125     if (mFormats.size() != 0) {
7126         snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7127         result.append(buffer);
7128         for (size_t i = 0; i < mFormats.size(); i++) {
7129             const char *formatStr = enumToString(sFormatNameToEnumTable,
7130                                                  ARRAY_SIZE(sFormatNameToEnumTable),
7131                                                  mFormats[i]);
7132             if (i == 0 && strcmp(formatStr, "") == 0) {
7133                 snprintf(buffer, SIZE, "Dynamic");
7134             } else {
7135                 snprintf(buffer, SIZE, "%s", formatStr);
7136             }
7137             result.append(buffer);
7138             result.append(i == (mFormats.size() - 1) ? "" : ", ");
7139         }
7140         result.append("\n");
7141     }
7142     write(fd, result.string(), result.size());
7143     if (mGains.size() != 0) {
7144         snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7145         write(fd, buffer, strlen(buffer) + 1);
7146         result.append(buffer);
7147         for (size_t i = 0; i < mGains.size(); i++) {
7148             mGains[i]->dump(fd, spaces + 2, i);
7149         }
7150     }
7151 }
7152 
7153 // --- AudioGain class implementation
7154 
AudioGain(int index,bool useInChannelMask)7155 AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
7156 {
7157     mIndex = index;
7158     mUseInChannelMask = useInChannelMask;
7159     memset(&mGain, 0, sizeof(struct audio_gain));
7160 }
7161 
getDefaultConfig(struct audio_gain_config * config)7162 void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7163 {
7164     config->index = mIndex;
7165     config->mode = mGain.mode;
7166     config->channel_mask = mGain.channel_mask;
7167     if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7168         config->values[0] = mGain.default_value;
7169     } else {
7170         uint32_t numValues;
7171         if (mUseInChannelMask) {
7172             numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7173         } else {
7174             numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7175         }
7176         for (size_t i = 0; i < numValues; i++) {
7177             config->values[i] = mGain.default_value;
7178         }
7179     }
7180     if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7181         config->ramp_duration_ms = mGain.min_ramp_ms;
7182     }
7183 }
7184 
checkConfig(const struct audio_gain_config * config)7185 status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7186 {
7187     if ((config->mode & ~mGain.mode) != 0) {
7188         return BAD_VALUE;
7189     }
7190     if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7191         if ((config->values[0] < mGain.min_value) ||
7192                     (config->values[0] > mGain.max_value)) {
7193             return BAD_VALUE;
7194         }
7195     } else {
7196         if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7197             return BAD_VALUE;
7198         }
7199         uint32_t numValues;
7200         if (mUseInChannelMask) {
7201             numValues = audio_channel_count_from_in_mask(config->channel_mask);
7202         } else {
7203             numValues = audio_channel_count_from_out_mask(config->channel_mask);
7204         }
7205         for (size_t i = 0; i < numValues; i++) {
7206             if ((config->values[i] < mGain.min_value) ||
7207                     (config->values[i] > mGain.max_value)) {
7208                 return BAD_VALUE;
7209             }
7210         }
7211     }
7212     if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7213         if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7214                     (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7215             return BAD_VALUE;
7216         }
7217     }
7218     return NO_ERROR;
7219 }
7220 
dump(int fd,int spaces,int index) const7221 void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7222 {
7223     const size_t SIZE = 256;
7224     char buffer[SIZE];
7225     String8 result;
7226 
7227     snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7228     result.append(buffer);
7229     snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7230     result.append(buffer);
7231     snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7232     result.append(buffer);
7233     snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7234     result.append(buffer);
7235     snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7236     result.append(buffer);
7237     snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7238     result.append(buffer);
7239     snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7240     result.append(buffer);
7241     snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7242     result.append(buffer);
7243     snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7244     result.append(buffer);
7245 
7246     write(fd, result.string(), result.size());
7247 }
7248 
7249 // --- AudioPortConfig class implementation
7250 
AudioPortConfig()7251 AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7252 {
7253     mSamplingRate = 0;
7254     mChannelMask = AUDIO_CHANNEL_NONE;
7255     mFormat = AUDIO_FORMAT_INVALID;
7256     mGain.index = -1;
7257 }
7258 
applyAudioPortConfig(const struct audio_port_config * config,struct audio_port_config * backupConfig)7259 status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7260                                                         const struct audio_port_config *config,
7261                                                         struct audio_port_config *backupConfig)
7262 {
7263     struct audio_port_config localBackupConfig;
7264     status_t status = NO_ERROR;
7265 
7266     localBackupConfig.config_mask = config->config_mask;
7267     toAudioPortConfig(&localBackupConfig);
7268 
7269     sp<AudioPort> audioport = getAudioPort();
7270     if (audioport == 0) {
7271         status = NO_INIT;
7272         goto exit;
7273     }
7274     if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7275         status = audioport->checkExactSamplingRate(config->sample_rate);
7276         if (status != NO_ERROR) {
7277             goto exit;
7278         }
7279         mSamplingRate = config->sample_rate;
7280     }
7281     if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7282         status = audioport->checkExactChannelMask(config->channel_mask);
7283         if (status != NO_ERROR) {
7284             goto exit;
7285         }
7286         mChannelMask = config->channel_mask;
7287     }
7288     if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7289         status = audioport->checkFormat(config->format);
7290         if (status != NO_ERROR) {
7291             goto exit;
7292         }
7293         mFormat = config->format;
7294     }
7295     if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7296         status = audioport->checkGain(&config->gain, config->gain.index);
7297         if (status != NO_ERROR) {
7298             goto exit;
7299         }
7300         mGain = config->gain;
7301     }
7302 
7303 exit:
7304     if (status != NO_ERROR) {
7305         applyAudioPortConfig(&localBackupConfig);
7306     }
7307     if (backupConfig != NULL) {
7308         *backupConfig = localBackupConfig;
7309     }
7310     return status;
7311 }
7312 
toAudioPortConfig(struct audio_port_config * dstConfig,const struct audio_port_config * srcConfig) const7313 void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7314                                                     struct audio_port_config *dstConfig,
7315                                                     const struct audio_port_config *srcConfig) const
7316 {
7317     if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7318         dstConfig->sample_rate = mSamplingRate;
7319         if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7320             dstConfig->sample_rate = srcConfig->sample_rate;
7321         }
7322     } else {
7323         dstConfig->sample_rate = 0;
7324     }
7325     if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7326         dstConfig->channel_mask = mChannelMask;
7327         if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7328             dstConfig->channel_mask = srcConfig->channel_mask;
7329         }
7330     } else {
7331         dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7332     }
7333     if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7334         dstConfig->format = mFormat;
7335         if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7336             dstConfig->format = srcConfig->format;
7337         }
7338     } else {
7339         dstConfig->format = AUDIO_FORMAT_INVALID;
7340     }
7341     if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7342         dstConfig->gain = mGain;
7343         if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7344             dstConfig->gain = srcConfig->gain;
7345         }
7346     } else {
7347         dstConfig->gain.index = -1;
7348     }
7349     if (dstConfig->gain.index != -1) {
7350         dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7351     } else {
7352         dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7353     }
7354 }
7355 
7356 // --- IOProfile class implementation
7357 
IOProfile(const String8 & name,audio_port_role_t role,const sp<HwModule> & module)7358 AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
7359                                          const sp<HwModule>& module)
7360     : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
7361 {
7362 }
7363 
~IOProfile()7364 AudioPolicyManager::IOProfile::~IOProfile()
7365 {
7366 }
7367 
7368 // checks if the IO profile is compatible with specified parameters.
7369 // Sampling rate, format and channel mask must be specified in order to
7370 // get a valid a match
isCompatibleProfile(audio_devices_t device,String8 address,uint32_t samplingRate,uint32_t * updatedSamplingRate,audio_format_t format,audio_channel_mask_t channelMask,uint32_t flags) const7371 bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
7372                                                         String8 address,
7373                                                         uint32_t samplingRate,
7374                                                         uint32_t *updatedSamplingRate,
7375                                                         audio_format_t format,
7376                                                         audio_channel_mask_t channelMask,
7377                                                         uint32_t flags) const
7378 {
7379     const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7380     const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7381     ALOG_ASSERT(isPlaybackThread != isRecordThread);
7382 
7383     if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
7384         return false;
7385     }
7386 
7387     if (samplingRate == 0) {
7388          return false;
7389     }
7390     uint32_t myUpdatedSamplingRate = samplingRate;
7391     if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
7392          return false;
7393     }
7394     if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7395             NO_ERROR) {
7396          return false;
7397     }
7398 
7399     if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7400         return false;
7401     }
7402 
7403     if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7404             checkExactChannelMask(channelMask) != NO_ERROR)) {
7405         return false;
7406     }
7407     if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7408             checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7409         return false;
7410     }
7411 
7412     if (isPlaybackThread && (mFlags & flags) != flags) {
7413         return false;
7414     }
7415     // The only input flag that is allowed to be different is the fast flag.
7416     // An existing fast stream is compatible with a normal track request.
7417     // An existing normal stream is compatible with a fast track request,
7418     // but the fast request will be denied by AudioFlinger and converted to normal track.
7419     if (isRecordThread && ((mFlags ^ flags) &
7420             ~AUDIO_INPUT_FLAG_FAST)) {
7421         return false;
7422     }
7423 
7424     if (updatedSamplingRate != NULL) {
7425         *updatedSamplingRate = myUpdatedSamplingRate;
7426     }
7427     return true;
7428 }
7429 
dump(int fd)7430 void AudioPolicyManager::IOProfile::dump(int fd)
7431 {
7432     const size_t SIZE = 256;
7433     char buffer[SIZE];
7434     String8 result;
7435 
7436     AudioPort::dump(fd, 4);
7437 
7438     snprintf(buffer, SIZE, "    - flags: 0x%04x\n", mFlags);
7439     result.append(buffer);
7440     snprintf(buffer, SIZE, "    - devices:\n");
7441     result.append(buffer);
7442     write(fd, result.string(), result.size());
7443     for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7444         mSupportedDevices[i]->dump(fd, 6, i);
7445     }
7446 }
7447 
log()7448 void AudioPolicyManager::IOProfile::log()
7449 {
7450     const size_t SIZE = 256;
7451     char buffer[SIZE];
7452     String8 result;
7453 
7454     ALOGV("    - sampling rates: ");
7455     for (size_t i = 0; i < mSamplingRates.size(); i++) {
7456         ALOGV("  %d", mSamplingRates[i]);
7457     }
7458 
7459     ALOGV("    - channel masks: ");
7460     for (size_t i = 0; i < mChannelMasks.size(); i++) {
7461         ALOGV("  0x%04x", mChannelMasks[i]);
7462     }
7463 
7464     ALOGV("    - formats: ");
7465     for (size_t i = 0; i < mFormats.size(); i++) {
7466         ALOGV("  0x%08x", mFormats[i]);
7467     }
7468 
7469     ALOGV("    - devices: 0x%04x\n", mSupportedDevices.types());
7470     ALOGV("    - flags: 0x%04x\n", mFlags);
7471 }
7472 
7473 
7474 // --- DeviceDescriptor implementation
7475 
7476 
DeviceDescriptor(const String8 & name,audio_devices_t type)7477 AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7478                      AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7479                                audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7480                                                               AUDIO_PORT_ROLE_SOURCE,
7481                              NULL),
7482                      mDeviceType(type), mAddress(""), mId(0)
7483 {
7484 }
7485 
equals(const sp<DeviceDescriptor> & other) const7486 bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
7487 {
7488     // Devices are considered equal if they:
7489     // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7490     // - have the same address or one device does not specify the address
7491     // - have the same channel mask or one device does not specify the channel mask
7492     return (mDeviceType == other->mDeviceType) &&
7493            (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
7494            (mChannelMask == 0 || other->mChannelMask == 0 ||
7495                 mChannelMask == other->mChannelMask);
7496 }
7497 
loadGains(cnode * root)7498 void AudioPolicyManager::DeviceDescriptor::loadGains(cnode *root)
7499 {
7500     AudioPort::loadGains(root);
7501     if (mGains.size() > 0) {
7502         mGains[0]->getDefaultConfig(&mGain);
7503     }
7504 }
7505 
7506 
refreshTypes()7507 void AudioPolicyManager::DeviceVector::refreshTypes()
7508 {
7509     mDeviceTypes = AUDIO_DEVICE_NONE;
7510     for(size_t i = 0; i < size(); i++) {
7511         mDeviceTypes |= itemAt(i)->mDeviceType;
7512     }
7513     ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
7514 }
7515 
indexOf(const sp<DeviceDescriptor> & item) const7516 ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7517 {
7518     for(size_t i = 0; i < size(); i++) {
7519         if (item->equals(itemAt(i))) {
7520             return i;
7521         }
7522     }
7523     return -1;
7524 }
7525 
add(const sp<DeviceDescriptor> & item)7526 ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
7527 {
7528     ssize_t ret = indexOf(item);
7529 
7530     if (ret < 0) {
7531         ret = SortedVector::add(item);
7532         if (ret >= 0) {
7533             refreshTypes();
7534         }
7535     } else {
7536         ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
7537         ret = -1;
7538     }
7539     return ret;
7540 }
7541 
remove(const sp<DeviceDescriptor> & item)7542 ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7543 {
7544     size_t i;
7545     ssize_t ret = indexOf(item);
7546 
7547     if (ret < 0) {
7548         ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
7549     } else {
7550         ret = SortedVector::removeAt(ret);
7551         if (ret >= 0) {
7552             refreshTypes();
7553         }
7554     }
7555     return ret;
7556 }
7557 
loadDevicesFromType(audio_devices_t types)7558 void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7559 {
7560     DeviceVector deviceList;
7561 
7562     uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7563     types &= ~role_bit;
7564 
7565     while (types) {
7566         uint32_t i = 31 - __builtin_clz(types);
7567         uint32_t type = 1 << i;
7568         types &= ~type;
7569         add(new DeviceDescriptor(String8(""), type | role_bit));
7570     }
7571 }
7572 
loadDevicesFromName(char * name,const DeviceVector & declaredDevices)7573 void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7574                                                            const DeviceVector& declaredDevices)
7575 {
7576     char *devName = strtok(name, "|");
7577     while (devName != NULL) {
7578         if (strlen(devName) != 0) {
7579             audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7580                                  ARRAY_SIZE(sDeviceNameToEnumTable),
7581                                  devName);
7582             if (type != AUDIO_DEVICE_NONE) {
7583                 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
7584                 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7585                         type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
7586                     dev->mAddress = String8("0");
7587                 }
7588                 add(dev);
7589             } else {
7590                 sp<DeviceDescriptor> deviceDesc =
7591                         declaredDevices.getDeviceFromName(String8(devName));
7592                 if (deviceDesc != 0) {
7593                     add(deviceDesc);
7594                 }
7595             }
7596          }
7597          devName = strtok(NULL, "|");
7598      }
7599 }
7600 
getDevice(audio_devices_t type,String8 address) const7601 sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7602                                                         audio_devices_t type, String8 address) const
7603 {
7604     sp<DeviceDescriptor> device;
7605     for (size_t i = 0; i < size(); i++) {
7606         if (itemAt(i)->mDeviceType == type) {
7607             if (address == "" || itemAt(i)->mAddress == address) {
7608                 device = itemAt(i);
7609                 if (itemAt(i)->mAddress == address) {
7610                     break;
7611                 }
7612             }
7613         }
7614     }
7615     ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
7616           type, address.string(), device.get());
7617     return device;
7618 }
7619 
getDeviceFromId(audio_port_handle_t id) const7620 sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7621                                                                     audio_port_handle_t id) const
7622 {
7623     sp<DeviceDescriptor> device;
7624     for (size_t i = 0; i < size(); i++) {
7625         ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
7626         if (itemAt(i)->mId == id) {
7627             device = itemAt(i);
7628             break;
7629         }
7630     }
7631     return device;
7632 }
7633 
getDevicesFromType(audio_devices_t type) const7634 AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7635                                                                         audio_devices_t type) const
7636 {
7637     DeviceVector devices;
7638     for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7639         if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7640             devices.add(itemAt(i));
7641             type &= ~itemAt(i)->mDeviceType;
7642             ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7643                   itemAt(i)->mDeviceType, itemAt(i).get());
7644         }
7645     }
7646     return devices;
7647 }
7648 
getDevicesFromTypeAddr(audio_devices_t type,String8 address) const7649 AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7650         audio_devices_t type, String8 address) const
7651 {
7652     DeviceVector devices;
7653     for (size_t i = 0; i < size(); i++) {
7654         if (itemAt(i)->mDeviceType == type) {
7655             if (itemAt(i)->mAddress == address) {
7656                 devices.add(itemAt(i));
7657             }
7658         }
7659     }
7660     return devices;
7661 }
7662 
getDeviceFromName(const String8 & name) const7663 sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7664         const String8& name) const
7665 {
7666     sp<DeviceDescriptor> device;
7667     for (size_t i = 0; i < size(); i++) {
7668         if (itemAt(i)->mName == name) {
7669             device = itemAt(i);
7670             break;
7671         }
7672     }
7673     return device;
7674 }
7675 
toAudioPortConfig(struct audio_port_config * dstConfig,const struct audio_port_config * srcConfig) const7676 void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7677                                                     struct audio_port_config *dstConfig,
7678                                                     const struct audio_port_config *srcConfig) const
7679 {
7680     dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7681     if (srcConfig != NULL) {
7682         dstConfig->config_mask |= srcConfig->config_mask;
7683     }
7684 
7685     AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7686 
7687     dstConfig->id = mId;
7688     dstConfig->role = audio_is_output_device(mDeviceType) ?
7689                         AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
7690     dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
7691     dstConfig->ext.device.type = mDeviceType;
7692     dstConfig->ext.device.hw_module = mModule->mHandle;
7693     strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7694 }
7695 
toAudioPort(struct audio_port * port) const7696 void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7697 {
7698     ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
7699     AudioPort::toAudioPort(port);
7700     port->id = mId;
7701     toAudioPortConfig(&port->active_config);
7702     port->ext.device.type = mDeviceType;
7703     port->ext.device.hw_module = mModule->mHandle;
7704     strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7705 }
7706 
dump(int fd,int spaces,int index) const7707 status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
7708 {
7709     const size_t SIZE = 256;
7710     char buffer[SIZE];
7711     String8 result;
7712 
7713     snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7714     result.append(buffer);
7715     if (mId != 0) {
7716         snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7717         result.append(buffer);
7718     }
7719     snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7720                                               enumToString(sDeviceNameToEnumTable,
7721                                                            ARRAY_SIZE(sDeviceNameToEnumTable),
7722                                                            mDeviceType));
7723     result.append(buffer);
7724     if (mAddress.size() != 0) {
7725         snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7726         result.append(buffer);
7727     }
7728     write(fd, result.string(), result.size());
7729     AudioPort::dump(fd, spaces);
7730 
7731     return NO_ERROR;
7732 }
7733 
dump(int fd,int spaces,int index) const7734 status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7735 {
7736     const size_t SIZE = 256;
7737     char buffer[SIZE];
7738     String8 result;
7739 
7740 
7741     snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7742     result.append(buffer);
7743     snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7744     result.append(buffer);
7745     snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7746     result.append(buffer);
7747     snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7748     result.append(buffer);
7749     snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7750     result.append(buffer);
7751     for (size_t i = 0; i < mPatch.num_sources; i++) {
7752         if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7753             snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7754                      mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7755                                                         ARRAY_SIZE(sDeviceNameToEnumTable),
7756                                                         mPatch.sources[i].ext.device.type));
7757         } else {
7758             snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7759                      mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7760         }
7761         result.append(buffer);
7762     }
7763     snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7764     result.append(buffer);
7765     for (size_t i = 0; i < mPatch.num_sinks; i++) {
7766         if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7767             snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7768                      mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7769                                                         ARRAY_SIZE(sDeviceNameToEnumTable),
7770                                                         mPatch.sinks[i].ext.device.type));
7771         } else {
7772             snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7773                      mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7774         }
7775         result.append(buffer);
7776     }
7777 
7778     write(fd, result.string(), result.size());
7779     return NO_ERROR;
7780 }
7781 
7782 // --- audio_policy.conf file parsing
7783 
parseOutputFlagNames(char * name)7784 uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
7785 {
7786     uint32_t flag = 0;
7787 
7788     // it is OK to cast name to non const here as we are not going to use it after
7789     // strtok() modifies it
7790     char *flagName = strtok(name, "|");
7791     while (flagName != NULL) {
7792         if (strlen(flagName) != 0) {
7793             flag |= stringToEnum(sOutputFlagNameToEnumTable,
7794                                ARRAY_SIZE(sOutputFlagNameToEnumTable),
7795                                flagName);
7796         }
7797         flagName = strtok(NULL, "|");
7798     }
7799     //force direct flag if offload flag is set: offloading implies a direct output stream
7800     // and all common behaviors are driven by checking only the direct flag
7801     // this should normally be set appropriately in the policy configuration file
7802     if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7803         flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7804     }
7805 
7806     return flag;
7807 }
7808 
parseInputFlagNames(char * name)7809 uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7810 {
7811     uint32_t flag = 0;
7812 
7813     // it is OK to cast name to non const here as we are not going to use it after
7814     // strtok() modifies it
7815     char *flagName = strtok(name, "|");
7816     while (flagName != NULL) {
7817         if (strlen(flagName) != 0) {
7818             flag |= stringToEnum(sInputFlagNameToEnumTable,
7819                                ARRAY_SIZE(sInputFlagNameToEnumTable),
7820                                flagName);
7821         }
7822         flagName = strtok(NULL, "|");
7823     }
7824     return flag;
7825 }
7826 
parseDeviceNames(char * name)7827 audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
7828 {
7829     uint32_t device = 0;
7830 
7831     char *devName = strtok(name, "|");
7832     while (devName != NULL) {
7833         if (strlen(devName) != 0) {
7834             device |= stringToEnum(sDeviceNameToEnumTable,
7835                                  ARRAY_SIZE(sDeviceNameToEnumTable),
7836                                  devName);
7837          }
7838         devName = strtok(NULL, "|");
7839      }
7840     return device;
7841 }
7842 
loadHwModule(cnode * root)7843 void AudioPolicyManager::loadHwModule(cnode *root)
7844 {
7845     status_t status = NAME_NOT_FOUND;
7846     cnode *node;
7847     sp<HwModule> module = new HwModule(root->name);
7848 
7849     node = config_find(root, DEVICES_TAG);
7850     if (node != NULL) {
7851         node = node->first_child;
7852         while (node) {
7853             ALOGV("loadHwModule() loading device %s", node->name);
7854             status_t tmpStatus = module->loadDevice(node);
7855             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7856                 status = tmpStatus;
7857             }
7858             node = node->next;
7859         }
7860     }
7861     node = config_find(root, OUTPUTS_TAG);
7862     if (node != NULL) {
7863         node = node->first_child;
7864         while (node) {
7865             ALOGV("loadHwModule() loading output %s", node->name);
7866             status_t tmpStatus = module->loadOutput(node);
7867             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7868                 status = tmpStatus;
7869             }
7870             node = node->next;
7871         }
7872     }
7873     node = config_find(root, INPUTS_TAG);
7874     if (node != NULL) {
7875         node = node->first_child;
7876         while (node) {
7877             ALOGV("loadHwModule() loading input %s", node->name);
7878             status_t tmpStatus = module->loadInput(node);
7879             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7880                 status = tmpStatus;
7881             }
7882             node = node->next;
7883         }
7884     }
7885     loadGlobalConfig(root, module);
7886 
7887     if (status == NO_ERROR) {
7888         mHwModules.add(module);
7889     }
7890 }
7891 
loadHwModules(cnode * root)7892 void AudioPolicyManager::loadHwModules(cnode *root)
7893 {
7894     cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7895     if (node == NULL) {
7896         return;
7897     }
7898 
7899     node = node->first_child;
7900     while (node) {
7901         ALOGV("loadHwModules() loading module %s", node->name);
7902         loadHwModule(node);
7903         node = node->next;
7904     }
7905 }
7906 
loadGlobalConfig(cnode * root,const sp<HwModule> & module)7907 void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
7908 {
7909     cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
7910 
7911     if (node == NULL) {
7912         return;
7913     }
7914     DeviceVector declaredDevices;
7915     if (module != NULL) {
7916         declaredDevices = module->mDeclaredDevices;
7917     }
7918 
7919     node = node->first_child;
7920     while (node) {
7921         if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
7922             mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7923                                                         declaredDevices);
7924             ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7925                   mAvailableOutputDevices.types());
7926         } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
7927             audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
7928                                               ARRAY_SIZE(sDeviceNameToEnumTable),
7929                                               (char *)node->value);
7930             if (device != AUDIO_DEVICE_NONE) {
7931                 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
7932             } else {
7933                 ALOGW("loadGlobalConfig() default device not specified");
7934             }
7935             ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
7936         } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
7937             mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7938                                                        declaredDevices);
7939             ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
7940         } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7941             mSpeakerDrcEnabled = stringToBool((char *)node->value);
7942             ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
7943         } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7944             uint32_t major, minor;
7945             sscanf((char *)node->value, "%u.%u", &major, &minor);
7946             module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7947             ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7948                   module->mHalVersion, major, minor);
7949         }
7950         node = node->next;
7951     }
7952 }
7953 
loadAudioPolicyConfig(const char * path)7954 status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
7955 {
7956     cnode *root;
7957     char *data;
7958 
7959     data = (char *)load_file(path, NULL);
7960     if (data == NULL) {
7961         return -ENODEV;
7962     }
7963     root = config_node("", "");
7964     config_load(root, data);
7965 
7966     loadHwModules(root);
7967     // legacy audio_policy.conf files have one global_configuration section
7968     loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
7969     config_free(root);
7970     free(root);
7971     free(data);
7972 
7973     ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7974 
7975     return NO_ERROR;
7976 }
7977 
defaultAudioPolicyConfig(void)7978 void AudioPolicyManager::defaultAudioPolicyConfig(void)
7979 {
7980     sp<HwModule> module;
7981     sp<IOProfile> profile;
7982     sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7983                                                                    AUDIO_DEVICE_IN_BUILTIN_MIC);
7984     mAvailableOutputDevices.add(mDefaultOutputDevice);
7985     mAvailableInputDevices.add(defaultInputDevice);
7986 
7987     module = new HwModule("primary");
7988 
7989     profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
7990     profile->mSamplingRates.add(44100);
7991     profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7992     profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
7993     profile->mSupportedDevices.add(mDefaultOutputDevice);
7994     profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7995     module->mOutputProfiles.add(profile);
7996 
7997     profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
7998     profile->mSamplingRates.add(8000);
7999     profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
8000     profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
8001     profile->mSupportedDevices.add(defaultInputDevice);
8002     module->mInputProfiles.add(profile);
8003 
8004     mHwModules.add(module);
8005 }
8006 
streamTypefromAttributesInt(const audio_attributes_t * attr)8007 audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
8008 {
8009     // flags to stream type mapping
8010     if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
8011         return AUDIO_STREAM_ENFORCED_AUDIBLE;
8012     }
8013     if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
8014         return AUDIO_STREAM_BLUETOOTH_SCO;
8015     }
8016     if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
8017         return AUDIO_STREAM_TTS;
8018     }
8019 
8020     // usage to stream type mapping
8021     switch (attr->usage) {
8022     case AUDIO_USAGE_MEDIA:
8023     case AUDIO_USAGE_GAME:
8024     case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8025         return AUDIO_STREAM_MUSIC;
8026     case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8027         if (isStreamActive(AUDIO_STREAM_ALARM)) {
8028             return AUDIO_STREAM_ALARM;
8029         }
8030         if (isStreamActive(AUDIO_STREAM_RING)) {
8031             return AUDIO_STREAM_RING;
8032         }
8033         if (isInCall()) {
8034             return AUDIO_STREAM_VOICE_CALL;
8035         }
8036         return AUDIO_STREAM_ACCESSIBILITY;
8037     case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8038         return AUDIO_STREAM_SYSTEM;
8039     case AUDIO_USAGE_VOICE_COMMUNICATION:
8040         return AUDIO_STREAM_VOICE_CALL;
8041 
8042     case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8043         return AUDIO_STREAM_DTMF;
8044 
8045     case AUDIO_USAGE_ALARM:
8046         return AUDIO_STREAM_ALARM;
8047     case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8048         return AUDIO_STREAM_RING;
8049 
8050     case AUDIO_USAGE_NOTIFICATION:
8051     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8052     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8053     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8054     case AUDIO_USAGE_NOTIFICATION_EVENT:
8055         return AUDIO_STREAM_NOTIFICATION;
8056 
8057     case AUDIO_USAGE_UNKNOWN:
8058     default:
8059         return AUDIO_STREAM_MUSIC;
8060     }
8061 }
8062 
isValidAttributes(const audio_attributes_t * paa)8063 bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
8064     // has flags that map to a strategy?
8065     if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8066         return true;
8067     }
8068 
8069     // has known usage?
8070     switch (paa->usage) {
8071     case AUDIO_USAGE_UNKNOWN:
8072     case AUDIO_USAGE_MEDIA:
8073     case AUDIO_USAGE_VOICE_COMMUNICATION:
8074     case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8075     case AUDIO_USAGE_ALARM:
8076     case AUDIO_USAGE_NOTIFICATION:
8077     case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8078     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8079     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8080     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8081     case AUDIO_USAGE_NOTIFICATION_EVENT:
8082     case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8083     case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8084     case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8085     case AUDIO_USAGE_GAME:
8086     case AUDIO_USAGE_VIRTUAL_SOURCE:
8087         break;
8088     default:
8089         return false;
8090     }
8091     return true;
8092 }
8093 
8094 }; // namespace android
8095