blob: a71aa53ef91d0eecb653ea734df84f61f572e882 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
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
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#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()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// 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
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// 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)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct 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
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 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),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 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),
Eric Laurent1b776232014-05-19 17:26:41 -070087 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),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 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),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 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),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 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),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 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),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const 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),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 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),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 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),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const 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
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const 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
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_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
192const 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
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800218 return setDeviceConnectionStateInt(device, state, device_address);
219}
220
221status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
222 audio_policy_dev_state_t state,
223 const char *device_address)
224{
Eric Laurent22226012014-08-01 17:00:54 -0700225 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700226 // handle legacy remote submix case where the address was not always specified
227 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
228 address = String8("0");
229 }
Eric Laurente552edb2014-03-10 17:42:56 -0700230
Eric Laurent22226012014-08-01 17:00:54 -0700231 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
232 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700233
234 // connect/disconnect only 1 device at a time
235 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
236
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output devices
238 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700239 SortedVector <audio_io_handle_t> outputs;
240
Eric Laurent1afeecb2014-05-14 08:52:28 -0700241 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
242 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
244
Eric Laurente552edb2014-03-10 17:42:56 -0700245 // save a copy of the opened output descriptors before any output is opened or closed
246 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
247 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 switch (state)
249 {
250 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700251 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700253 ALOGW("setDeviceConnectionState() device already connected: %x", device);
254 return INVALID_OPERATION;
255 }
256 ALOGV("setDeviceConnectionState() connecting device %x", device);
257
Eric Laurente552edb2014-03-10 17:42:56 -0700258 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 index = mAvailableOutputDevices.add(devDesc);
260 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700261 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700262 if (module == 0) {
263 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
264 device);
265 mAvailableOutputDevices.remove(devDesc);
266 return INVALID_OPERATION;
267 }
268 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700269 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700270 } else {
271 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700272 }
273
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700274 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700275 mAvailableOutputDevices.remove(devDesc);
276 return INVALID_OPERATION;
277 }
278 // outputs should never be empty here
279 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
280 "checkOutputsForDevice() returned no outputs but status OK");
281 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
282 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700283 break;
284 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700285 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700287 ALOGW("setDeviceConnectionState() device not connected: %x", device);
288 return INVALID_OPERATION;
289 }
290
Paul McLean5c477aa2014-08-20 16:47:57 -0700291 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
292
293 // Set Disconnect to HALs
294 AudioParameter param = AudioParameter(address);
295 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
296 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
297
Eric Laurente552edb2014-03-10 17:42:56 -0700298 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700300
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700301 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700302 } break;
303
304 default:
305 ALOGE("setDeviceConnectionState() invalid state: %x", state);
306 return BAD_VALUE;
307 }
308
Eric Laurent3a4311c2014-03-17 12:00:47 -0700309 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
310 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700311 checkA2dpSuspend();
312 checkOutputForAllStrategies();
313 // outputs must be closed after checkOutputForAllStrategies() is executed
314 if (!outputs.isEmpty()) {
315 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700316 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 // close unused outputs after device disconnection or direct outputs that have been
318 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700319 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700320 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
321 (desc->mDirectOpenCount == 0))) {
322 closeOutput(outputs[i]);
323 }
324 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 // check again after closing A2DP output to reset mA2dpSuspended if needed
326 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700327 }
328
329 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 if (mPhoneState == AUDIO_MODE_IN_CALL) {
331 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
332 updateCallRouting(newDevice);
333 }
Eric Laurente552edb2014-03-10 17:42:56 -0700334 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700335 audio_io_handle_t output = mOutputs.keyAt(i);
336 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
337 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
338 true /*fromCache*/);
339 // do not force device change on duplicated output because if device is 0, it will
340 // also force a device 0 for the two outputs it is duplicated to which may override
341 // a valid device selection on those outputs.
342 bool force = !mOutputs.valueAt(i)->isDuplicated()
343 && (!deviceDistinguishesOnAddress(device)
344 // always force when disconnecting (a non-duplicated device)
345 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
346 setOutputDevice(output, newDevice, force, 0);
347 }
Eric Laurente552edb2014-03-10 17:42:56 -0700348 }
349
Eric Laurent72aa32f2014-05-30 18:51:48 -0700350 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700351 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700352 } // end if is output device
353
Eric Laurente552edb2014-03-10 17:42:56 -0700354 // handle input devices
355 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700356 SortedVector <audio_io_handle_t> inputs;
357
Eric Laurent1afeecb2014-05-14 08:52:28 -0700358 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
359 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700361 switch (state)
362 {
363 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700364 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700365 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700366 ALOGW("setDeviceConnectionState() device already connected: %d", device);
367 return INVALID_OPERATION;
368 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700369 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700370 if (module == NULL) {
371 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
372 device);
373 return INVALID_OPERATION;
374 }
Eric Laurentd4692962014-05-05 18:13:44 -0700375 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
376 return INVALID_OPERATION;
377 }
378
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 index = mAvailableInputDevices.add(devDesc);
380 if (index >= 0) {
381 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700382 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 } else {
384 return NO_MEMORY;
385 }
Eric Laurentd4692962014-05-05 18:13:44 -0700386 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700387
388 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700389 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700390 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700391 ALOGW("setDeviceConnectionState() device not connected: %d", device);
392 return INVALID_OPERATION;
393 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700394
395 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
396
397 // Set Disconnect to HALs
398 AudioParameter param = AudioParameter(address);
399 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
400 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700403 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 default:
408 ALOGE("setDeviceConnectionState() invalid state: %x", state);
409 return BAD_VALUE;
410 }
411
Eric Laurentd4692962014-05-05 18:13:44 -0700412 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700413
Eric Laurentc2730ba2014-07-20 15:47:07 -0700414 if (mPhoneState == AUDIO_MODE_IN_CALL) {
415 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
416 updateCallRouting(newDevice);
417 }
418
Eric Laurentb52c1522014-05-20 11:27:36 -0700419 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700420 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700421 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700422
423 ALOGW("setDeviceConnectionState() invalid device: %x", device);
424 return BAD_VALUE;
425}
426
Eric Laurente0720872014-03-11 09:30:41 -0700427audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700428 const char *device_address)
429{
Eric Laurent3b73df72014-03-11 09:06:29 -0700430 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700431 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700432 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700433 // handle legacy remote submix case where the address was not always specified
434 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
435 devDesc->mAddress = String8("0");
436 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700437 ssize_t index;
438 DeviceVector *deviceVector;
439
Eric Laurente552edb2014-03-10 17:42:56 -0700440 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700441 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700442 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700443 deviceVector = &mAvailableInputDevices;
444 } else {
445 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
446 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700447 }
448
Eric Laurent3a4311c2014-03-17 12:00:47 -0700449 index = deviceVector->indexOf(devDesc);
450 if (index >= 0) {
451 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
452 } else {
453 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
454 }
Eric Laurente552edb2014-03-10 17:42:56 -0700455}
456
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
458{
459 bool createTxPatch = false;
460 struct audio_patch patch;
461 patch.num_sources = 1;
462 patch.num_sinks = 1;
463 status_t status;
464 audio_patch_handle_t afPatchHandle;
465 DeviceVector deviceList;
466
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800467 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
469
470 // release existing RX patch if any
471 if (mCallRxPatch != 0) {
472 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
473 mCallRxPatch.clear();
474 }
475 // release TX patch if any
476 if (mCallTxPatch != 0) {
477 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
478 mCallTxPatch.clear();
479 }
480
481 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
482 // via setOutputDevice() on primary output.
483 // Otherwise, create two audio patches for TX and RX path.
484 if (availablePrimaryOutputDevices() & rxDevice) {
485 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
486 // If the TX device is also on the primary HW module, setOutputDevice() will take care
487 // of it due to legacy implementation. If not, create a patch.
488 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
489 == AUDIO_DEVICE_NONE) {
490 createTxPatch = true;
491 }
492 } else {
493 // create RX path audio patch
494 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
495 ALOG_ASSERT(!deviceList.isEmpty(),
496 "updateCallRouting() selected device not in output device list");
497 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
498 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
499 ALOG_ASSERT(!deviceList.isEmpty(),
500 "updateCallRouting() no telephony RX device");
501 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
502
503 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
504 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
505
506 // request to reuse existing output stream if one is already opened to reach the RX device
507 SortedVector<audio_io_handle_t> outputs =
508 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700509 audio_io_handle_t output = selectOutput(outputs,
510 AUDIO_OUTPUT_FLAG_NONE,
511 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700512 if (output != AUDIO_IO_HANDLE_NONE) {
513 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
514 ALOG_ASSERT(!outputDesc->isDuplicated(),
515 "updateCallRouting() RX device output is duplicated");
516 outputDesc->toAudioPortConfig(&patch.sources[1]);
517 patch.num_sources = 2;
518 }
519
520 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
521 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
522 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
523 status);
524 if (status == NO_ERROR) {
525 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
526 &patch, mUidCached);
527 mCallRxPatch->mAfPatchHandle = afPatchHandle;
528 mCallRxPatch->mUid = mUidCached;
529 }
530 createTxPatch = true;
531 }
532 if (createTxPatch) {
533
534 struct audio_patch patch;
535 patch.num_sources = 1;
536 patch.num_sinks = 1;
537 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
538 ALOG_ASSERT(!deviceList.isEmpty(),
539 "updateCallRouting() selected device not in input device list");
540 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
541 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
542 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
543 ALOG_ASSERT(!deviceList.isEmpty(),
544 "updateCallRouting() no telephony TX device");
545 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
546 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
547
548 SortedVector<audio_io_handle_t> outputs =
549 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700550 audio_io_handle_t output = selectOutput(outputs,
551 AUDIO_OUTPUT_FLAG_NONE,
552 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700553 // request to reuse existing output stream if one is already opened to reach the TX
554 // path output device
555 if (output != AUDIO_IO_HANDLE_NONE) {
556 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
557 ALOG_ASSERT(!outputDesc->isDuplicated(),
558 "updateCallRouting() RX device output is duplicated");
559 outputDesc->toAudioPortConfig(&patch.sources[1]);
560 patch.num_sources = 2;
561 }
562
563 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
564 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
565 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
566 status);
567 if (status == NO_ERROR) {
568 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
569 &patch, mUidCached);
570 mCallTxPatch->mAfPatchHandle = afPatchHandle;
571 mCallTxPatch->mUid = mUidCached;
572 }
573 }
574}
575
Eric Laurente0720872014-03-11 09:30:41 -0700576void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700577{
578 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700579 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700580 ALOGW("setPhoneState() invalid state %d", state);
581 return;
582 }
583
584 if (state == mPhoneState ) {
585 ALOGW("setPhoneState() setting same state %d", state);
586 return;
587 }
588
589 // if leaving call state, handle special case of active streams
590 // pertaining to sonification strategy see handleIncallSonification()
591 if (isInCall()) {
592 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700593 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800594 if (stream == AUDIO_STREAM_PATCH) {
595 continue;
596 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700597 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700598 }
599 }
600
601 // store previous phone state for management of sonification strategy below
602 int oldState = mPhoneState;
603 mPhoneState = state;
604 bool force = false;
605
606 // are we entering or starting a call
607 if (!isStateInCall(oldState) && isStateInCall(state)) {
608 ALOGV(" Entering call in setPhoneState()");
609 // force routing command to audio hardware when starting a call
610 // even if no device change is needed
611 force = true;
612 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
613 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
614 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
615 }
616 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
617 ALOGV(" Exiting call in setPhoneState()");
618 // force routing command to audio hardware when exiting a call
619 // even if no device change is needed
620 force = true;
621 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
622 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
623 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
624 }
625 } else if (isStateInCall(state) && (state != oldState)) {
626 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
627 // force routing command to audio hardware when switching between telephony and VoIP
628 // even if no device change is needed
629 force = true;
630 }
631
632 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700633 checkA2dpSuspend();
634 checkOutputForAllStrategies();
635 updateDevicesAndOutputs();
636
Eric Laurent1f2f2232014-06-02 12:01:23 -0700637 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700638
Eric Laurente552edb2014-03-10 17:42:56 -0700639 int delayMs = 0;
640 if (isStateInCall(state)) {
641 nsecs_t sysTime = systemTime();
642 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700643 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700644 // mute media and sonification strategies and delay device switch by the largest
645 // latency of any output where either strategy is active.
646 // This avoid sending the ring tone or music tail into the earpiece or headset.
647 if ((desc->isStrategyActive(STRATEGY_MEDIA,
648 SONIFICATION_HEADSET_MUSIC_DELAY,
649 sysTime) ||
650 desc->isStrategyActive(STRATEGY_SONIFICATION,
651 SONIFICATION_HEADSET_MUSIC_DELAY,
652 sysTime)) &&
653 (delayMs < (int)desc->mLatency*2)) {
654 delayMs = desc->mLatency*2;
655 }
656 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
657 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
658 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
659 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
660 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
661 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
662 }
663 }
664
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
666 // the device returned is not necessarily reachable via this output
667 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
668 // force routing command to audio hardware when ending call
669 // even if no device change is needed
670 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
671 rxDevice = hwOutputDesc->device();
672 }
Eric Laurente552edb2014-03-10 17:42:56 -0700673
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674 if (state == AUDIO_MODE_IN_CALL) {
675 updateCallRouting(rxDevice, delayMs);
676 } else if (oldState == AUDIO_MODE_IN_CALL) {
677 if (mCallRxPatch != 0) {
678 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
679 mCallRxPatch.clear();
680 }
681 if (mCallTxPatch != 0) {
682 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
683 mCallTxPatch.clear();
684 }
685 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
686 } else {
687 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
688 }
Eric Laurente552edb2014-03-10 17:42:56 -0700689 // if entering in call state, handle special case of active streams
690 // pertaining to sonification strategy see handleIncallSonification()
691 if (isStateInCall(state)) {
692 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700693 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800694 if (stream == AUDIO_STREAM_PATCH) {
695 continue;
696 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700697 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700698 }
699 }
700
701 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700702 if (state == AUDIO_MODE_RINGTONE &&
703 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700704 mLimitRingtoneVolume = true;
705 } else {
706 mLimitRingtoneVolume = false;
707 }
708}
709
Eric Laurente0720872014-03-11 09:30:41 -0700710void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700712{
713 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
714
715 bool forceVolumeReeval = false;
716 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700717 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
718 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
719 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700720 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
721 return;
722 }
723 forceVolumeReeval = true;
724 mForceUse[usage] = config;
725 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700726 case AUDIO_POLICY_FORCE_FOR_MEDIA:
727 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
728 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
729 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
730 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800731 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700732 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
733 return;
734 }
735 mForceUse[usage] = config;
736 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700737 case AUDIO_POLICY_FORCE_FOR_RECORD:
738 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
739 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700740 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
741 return;
742 }
743 mForceUse[usage] = config;
744 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700745 case AUDIO_POLICY_FORCE_FOR_DOCK:
746 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
747 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
748 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
749 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
750 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700751 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
752 }
753 forceVolumeReeval = true;
754 mForceUse[usage] = config;
755 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700756 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
757 if (config != AUDIO_POLICY_FORCE_NONE &&
758 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700759 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
760 }
761 forceVolumeReeval = true;
762 mForceUse[usage] = config;
763 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900764 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
765 if (config != AUDIO_POLICY_FORCE_NONE &&
766 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
767 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
768 }
769 mForceUse[usage] = config;
770 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700771 default:
772 ALOGW("setForceUse() invalid usage %d", usage);
773 break;
774 }
775
776 // check for device and output changes triggered by new force usage
777 checkA2dpSuspend();
778 checkOutputForAllStrategies();
779 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700780 if (mPhoneState == AUDIO_MODE_IN_CALL) {
781 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
782 updateCallRouting(newDevice);
783 }
Eric Laurente552edb2014-03-10 17:42:56 -0700784 for (size_t i = 0; i < mOutputs.size(); i++) {
785 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700786 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700787 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
788 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
789 }
Eric Laurente552edb2014-03-10 17:42:56 -0700790 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
791 applyStreamVolumes(output, newDevice, 0, true);
792 }
793 }
794
795 audio_io_handle_t activeInput = getActiveInput();
796 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700797 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700798 }
799
800}
801
Eric Laurente0720872014-03-11 09:30:41 -0700802audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700803{
804 return mForceUse[usage];
805}
806
Eric Laurente0720872014-03-11 09:30:41 -0700807void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700808{
809 ALOGV("setSystemProperty() property %s, value %s", property, value);
810}
811
812// Find a direct output profile compatible with the parameters passed, even if the input flags do
813// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700814sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700815 audio_devices_t device,
816 uint32_t samplingRate,
817 audio_format_t format,
818 audio_channel_mask_t channelMask,
819 audio_output_flags_t flags)
820{
821 for (size_t i = 0; i < mHwModules.size(); i++) {
822 if (mHwModules[i]->mHandle == 0) {
823 continue;
824 }
825 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700826 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800827 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700828 NULL /*updatedSamplingRate*/, format, channelMask,
829 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
830 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700831 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
832 return profile;
833 }
Eric Laurente552edb2014-03-10 17:42:56 -0700834 }
835 }
836 return 0;
837}
838
Eric Laurente0720872014-03-11 09:30:41 -0700839audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700840 uint32_t samplingRate,
841 audio_format_t format,
842 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700843 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700844 const audio_offload_info_t *offloadInfo)
845{
Eric Laurent3b73df72014-03-11 09:06:29 -0700846 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
848 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
849 device, stream, samplingRate, format, channelMask, flags);
850
Eric Laurente83b55d2014-11-14 10:06:21 -0800851 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
852 stream, samplingRate,format, channelMask,
853 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700854}
855
Eric Laurente83b55d2014-11-14 10:06:21 -0800856status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
857 audio_io_handle_t *output,
858 audio_session_t session,
859 audio_stream_type_t *stream,
860 uint32_t samplingRate,
861 audio_format_t format,
862 audio_channel_mask_t channelMask,
863 audio_output_flags_t flags,
864 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700865{
Eric Laurente83b55d2014-11-14 10:06:21 -0800866 audio_attributes_t attributes;
867 if (attr != NULL) {
868 if (!isValidAttributes(attr)) {
869 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
870 attr->usage, attr->content_type, attr->flags,
871 attr->tags);
872 return BAD_VALUE;
873 }
874 attributes = *attr;
875 } else {
876 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
877 ALOGE("getOutputForAttr(): invalid stream type");
878 return BAD_VALUE;
879 }
880 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700881 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800882
Eric Laurent275e8e92014-11-30 15:14:47 -0800883 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
884 sp<AudioOutputDescriptor> desc;
885 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
886 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
887 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
888 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
889 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
890 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
891 desc = mPolicyMixes[i]->mOutput;
892 break;
893 }
894 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
895 strncmp(attributes.tags + strlen("addr="),
896 mPolicyMixes[i]->mMix.mRegistrationId.string(),
897 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
898 desc = mPolicyMixes[i]->mOutput;
899 break;
900 }
901 }
902 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
903 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
904 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
905 strncmp(attributes.tags + strlen("addr="),
906 mPolicyMixes[i]->mMix.mRegistrationId.string(),
907 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
908 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800909 }
910 }
911 if (desc != 0) {
912 if (!audio_is_linear_pcm(format)) {
913 return BAD_VALUE;
914 }
Eric Laurentc722f302014-12-10 11:21:49 -0800915 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800916 *stream = streamTypefromAttributesInt(&attributes);
917 *output = desc->mIoHandle;
918 ALOGV("getOutputForAttr() returns output %d", *output);
919 return NO_ERROR;
920 }
921 }
922 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
923 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
924 return BAD_VALUE;
925 }
926
Eric Laurent93c3d412014-08-01 14:48:35 -0700927 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800928 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700929
Eric Laurente83b55d2014-11-14 10:06:21 -0800930 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700931 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700932
Eric Laurente83b55d2014-11-14 10:06:21 -0800933 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700934 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
935 }
936
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700937 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700938 device, samplingRate, format, channelMask, flags);
939
Eric Laurente83b55d2014-11-14 10:06:21 -0800940 *stream = streamTypefromAttributesInt(&attributes);
941 *output = getOutputForDevice(device, session, *stream,
942 samplingRate, format, channelMask,
943 flags, offloadInfo);
944 if (*output == AUDIO_IO_HANDLE_NONE) {
945 return INVALID_OPERATION;
946 }
947 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700948}
949
950audio_io_handle_t AudioPolicyManager::getOutputForDevice(
951 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800952 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700953 audio_stream_type_t stream,
954 uint32_t samplingRate,
955 audio_format_t format,
956 audio_channel_mask_t channelMask,
957 audio_output_flags_t flags,
958 const audio_offload_info_t *offloadInfo)
959{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700960 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700961 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700962 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700963
Eric Laurente552edb2014-03-10 17:42:56 -0700964#ifdef AUDIO_POLICY_TEST
965 if (mCurOutput != 0) {
966 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
967 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
968
969 if (mTestOutputs[mCurOutput] == 0) {
970 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700971 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700972 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700973 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700974 outputDesc->mFlags =
975 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700976 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700977 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
978 config.sample_rate = mTestSamplingRate;
979 config.channel_mask = mTestChannels;
980 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700981 if (offloadInfo != NULL) {
982 config.offload_info = *offloadInfo;
983 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700984 status = mpClientInterface->openOutput(0,
985 &mTestOutputs[mCurOutput],
986 &config,
987 &outputDesc->mDevice,
988 String8(""),
989 &outputDesc->mLatency,
990 outputDesc->mFlags);
991 if (status == NO_ERROR) {
992 outputDesc->mSamplingRate = config.sample_rate;
993 outputDesc->mFormat = config.format;
994 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700995 AudioParameter outputCmd = AudioParameter();
996 outputCmd.addInt(String8("set_id"),mCurOutput);
997 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
998 addOutput(mTestOutputs[mCurOutput], outputDesc);
999 }
1000 }
1001 return mTestOutputs[mCurOutput];
1002 }
1003#endif //AUDIO_POLICY_TEST
1004
1005 // open a direct output if required by specified parameters
1006 //force direct flag if offload flag is set: offloading implies a direct output stream
1007 // and all common behaviors are driven by checking only the direct flag
1008 // this should normally be set appropriately in the policy configuration file
1009 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001010 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001011 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001012 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1013 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1014 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001015 // only allow deep buffering for music stream type
1016 if (stream != AUDIO_STREAM_MUSIC) {
1017 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1018 }
Eric Laurente552edb2014-03-10 17:42:56 -07001019
Eric Laurentb732cf52014-09-24 19:08:21 -07001020 sp<IOProfile> profile;
1021
1022 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001023 // and not explicitly requested
1024 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1025 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001026 audio_channel_count_from_out_mask(channelMask) <= 2) {
1027 goto non_direct_output;
1028 }
1029
Eric Laurente552edb2014-03-10 17:42:56 -07001030 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1031 // creating an offloaded track and tearing it down immediately after start when audioflinger
1032 // detects there is an active non offloadable effect.
1033 // FIXME: We should check the audio session here but we do not have it in this context.
1034 // This may prevent offloading in rare situations where effects are left active by apps
1035 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001036
Eric Laurente552edb2014-03-10 17:42:56 -07001037 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1038 !isNonOffloadableEffectEnabled()) {
1039 profile = getProfileForDirectOutput(device,
1040 samplingRate,
1041 format,
1042 channelMask,
1043 (audio_output_flags_t)flags);
1044 }
1045
Eric Laurent1c333e22014-05-20 10:48:17 -07001046 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001047 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001048
1049 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001050 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001051 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1052 outputDesc = desc;
1053 // reuse direct output if currently open and configured with same parameters
1054 if ((samplingRate == outputDesc->mSamplingRate) &&
1055 (format == outputDesc->mFormat) &&
1056 (channelMask == outputDesc->mChannelMask)) {
1057 outputDesc->mDirectOpenCount++;
1058 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1059 return mOutputs.keyAt(i);
1060 }
1061 }
1062 }
1063 // close direct output if currently open and configured with different parameters
1064 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001065 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001066 }
1067 outputDesc = new AudioOutputDescriptor(profile);
1068 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001069 outputDesc->mLatency = 0;
1070 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001071 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1072 config.sample_rate = samplingRate;
1073 config.channel_mask = channelMask;
1074 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001075 if (offloadInfo != NULL) {
1076 config.offload_info = *offloadInfo;
1077 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001078 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1079 &output,
1080 &config,
1081 &outputDesc->mDevice,
1082 String8(""),
1083 &outputDesc->mLatency,
1084 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001085
1086 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001087 if (status != NO_ERROR ||
1088 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1089 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1090 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001091 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1092 "format %d %d, channelMask %04x %04x", output, samplingRate,
1093 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1094 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001095 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001096 mpClientInterface->closeOutput(output);
1097 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001098 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001099 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001100 outputDesc->mSamplingRate = config.sample_rate;
1101 outputDesc->mChannelMask = config.channel_mask;
1102 outputDesc->mFormat = config.format;
1103 outputDesc->mRefCount[stream] = 0;
1104 outputDesc->mStopTime[stream] = 0;
1105 outputDesc->mDirectOpenCount = 1;
1106
Eric Laurente552edb2014-03-10 17:42:56 -07001107 audio_io_handle_t srcOutput = getOutputForEffect();
1108 addOutput(output, outputDesc);
1109 audio_io_handle_t dstOutput = getOutputForEffect();
1110 if (dstOutput == output) {
1111 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1112 }
1113 mPreviousOutputs = mOutputs;
1114 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001115 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001116 return output;
1117 }
1118
Eric Laurentb732cf52014-09-24 19:08:21 -07001119non_direct_output:
1120
Eric Laurente552edb2014-03-10 17:42:56 -07001121 // ignoring channel mask due to downmix capability in mixer
1122
1123 // open a non direct output
1124
1125 // for non direct outputs, only PCM is supported
1126 if (audio_is_linear_pcm(format)) {
1127 // get which output is suitable for the specified stream. The actual
1128 // routing change will happen when startOutput() will be called
1129 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1130
Eric Laurent8838a382014-09-08 16:44:28 -07001131 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1132 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1133 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001134 }
1135 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1136 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1137
1138 ALOGV("getOutput() returns output %d", output);
1139
1140 return output;
1141}
1142
Eric Laurente0720872014-03-11 09:30:41 -07001143audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001144 audio_output_flags_t flags,
1145 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001146{
1147 // select one output among several that provide a path to a particular device or set of
1148 // devices (the list was previously build by getOutputsForDevice()).
1149 // The priority is as follows:
1150 // 1: the output with the highest number of requested policy flags
1151 // 2: the primary output
1152 // 3: the first output in the list
1153
1154 if (outputs.size() == 0) {
1155 return 0;
1156 }
1157 if (outputs.size() == 1) {
1158 return outputs[0];
1159 }
1160
1161 int maxCommonFlags = 0;
1162 audio_io_handle_t outputFlags = 0;
1163 audio_io_handle_t outputPrimary = 0;
1164
1165 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001166 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001167 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001168 // if a valid format is specified, skip output if not compatible
1169 if (format != AUDIO_FORMAT_INVALID) {
1170 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1171 if (format != outputDesc->mFormat) {
1172 continue;
1173 }
1174 } else if (!audio_is_linear_pcm(format)) {
1175 continue;
1176 }
1177 }
1178
Eric Laurent3b73df72014-03-11 09:06:29 -07001179 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001180 if (commonFlags > maxCommonFlags) {
1181 outputFlags = outputs[i];
1182 maxCommonFlags = commonFlags;
1183 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1184 }
1185 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1186 outputPrimary = outputs[i];
1187 }
1188 }
1189 }
1190
1191 if (outputFlags != 0) {
1192 return outputFlags;
1193 }
1194 if (outputPrimary != 0) {
1195 return outputPrimary;
1196 }
1197
1198 return outputs[0];
1199}
1200
Eric Laurente0720872014-03-11 09:30:41 -07001201status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001202 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001203 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001204{
1205 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1206 ssize_t index = mOutputs.indexOfKey(output);
1207 if (index < 0) {
1208 ALOGW("startOutput() unknown output %d", output);
1209 return BAD_VALUE;
1210 }
1211
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001212 // cannot start playback of STREAM_TTS if any other output is being used
1213 uint32_t beaconMuteLatency = 0;
1214 if (stream == AUDIO_STREAM_TTS) {
1215 ALOGV("\t found BEACON stream");
1216 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1217 return INVALID_OPERATION;
1218 } else {
1219 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1220 }
1221 } else {
1222 // some playback other than beacon starts
1223 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1224 }
1225
Eric Laurent1f2f2232014-06-02 12:01:23 -07001226 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001227
1228 // increment usage count for this stream on the requested output:
1229 // NOTE that the usage count is the same for duplicated output and hardware output which is
1230 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1231 outputDesc->changeRefCount(stream, 1);
1232
1233 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001234 // starting an output being rerouted?
1235 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001236 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001237 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1238 } else {
1239 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1240 }
Eric Laurente552edb2014-03-10 17:42:56 -07001241 routing_strategy strategy = getStrategy(stream);
1242 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001243 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1244 (beaconMuteLatency > 0);
1245 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001246 bool force = false;
1247 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001248 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 if (desc != outputDesc) {
1250 // force a device change if any other output is managed by the same hw
1251 // module and has a current device selection that differs from selected device.
1252 // In this case, the audio HAL must receive the new device selection so that it can
1253 // change the device currently selected by the other active output.
1254 if (outputDesc->sharesHwModuleWith(desc) &&
1255 desc->device() != newDevice) {
1256 force = true;
1257 }
1258 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001259 // a notification so that audio focus effect can propagate, or that a mute/unmute
1260 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001261 uint32_t latency = desc->latency();
1262 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1263 waitMs = latency;
1264 }
1265 }
1266 }
1267 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1268
1269 // handle special case for sonification while in call
1270 if (isInCall()) {
1271 handleIncallSonification(stream, true, false);
1272 }
1273
1274 // apply volume rules for current stream and device if necessary
1275 checkAndSetVolume(stream,
1276 mStreams[stream].getVolumeIndex(newDevice),
1277 output,
1278 newDevice);
1279
1280 // update the outputs if starting an output with a stream that can affect notification
1281 // routing
1282 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001283
1284 // Automatically enable the remote submix input when output is started on a re routing mix
1285 // of type MIX_TYPE_RECORDERS
1286 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1287 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001288 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001289 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1290 outputDesc->mPolicyMix->mRegistrationId);
1291 }
1292
Eric Laurente552edb2014-03-10 17:42:56 -07001293 if (waitMs > muteWaitMs) {
1294 usleep((waitMs - muteWaitMs) * 2 * 1000);
1295 }
1296 }
1297 return NO_ERROR;
1298}
1299
1300
Eric Laurente0720872014-03-11 09:30:41 -07001301status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001302 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001303 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001304{
1305 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1306 ssize_t index = mOutputs.indexOfKey(output);
1307 if (index < 0) {
1308 ALOGW("stopOutput() unknown output %d", output);
1309 return BAD_VALUE;
1310 }
1311
Eric Laurent1f2f2232014-06-02 12:01:23 -07001312 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001313
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001314 // always handle stream stop, check which stream type is stopping
1315 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1316
Eric Laurente552edb2014-03-10 17:42:56 -07001317 // handle special case for sonification while in call
1318 if (isInCall()) {
1319 handleIncallSonification(stream, false, false);
1320 }
1321
1322 if (outputDesc->mRefCount[stream] > 0) {
1323 // decrement usage count of this stream on the output
1324 outputDesc->changeRefCount(stream, -1);
1325 // store time at which the stream was stopped - see isStreamActive()
1326 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001327 // Automatically disable the remote submix input when output is stopped on a
1328 // re routing mix of type MIX_TYPE_RECORDERS
1329 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1330 outputDesc->mPolicyMix != NULL &&
1331 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001332 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001333 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1334 outputDesc->mPolicyMix->mRegistrationId);
1335 }
1336
Eric Laurente552edb2014-03-10 17:42:56 -07001337 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001338 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001339 // delay the device switch by twice the latency because stopOutput() is executed when
1340 // the track stop() command is received and at that time the audio track buffer can
1341 // still contain data that needs to be drained. The latency only covers the audio HAL
1342 // and kernel buffers. Also the latency does not always include additional delay in the
1343 // audio path (audio DSP, CODEC ...)
1344 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1345
1346 // force restoring the device selection on other active outputs if it differs from the
1347 // one being selected for this output
1348 for (size_t i = 0; i < mOutputs.size(); i++) {
1349 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001350 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001351 if (curOutput != output &&
1352 desc->isActive() &&
1353 outputDesc->sharesHwModuleWith(desc) &&
1354 (newDevice != desc->device())) {
1355 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001356 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001357 true,
1358 outputDesc->mLatency*2);
1359 }
1360 }
1361 // update the outputs if stopping one with a stream that can affect notification routing
1362 handleNotificationRoutingForStream(stream);
1363 }
1364 return NO_ERROR;
1365 } else {
1366 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1367 return INVALID_OPERATION;
1368 }
1369}
1370
Eric Laurente83b55d2014-11-14 10:06:21 -08001371void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001372 audio_stream_type_t stream __unused,
1373 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001374{
1375 ALOGV("releaseOutput() %d", output);
1376 ssize_t index = mOutputs.indexOfKey(output);
1377 if (index < 0) {
1378 ALOGW("releaseOutput() releasing unknown output %d", output);
1379 return;
1380 }
1381
1382#ifdef AUDIO_POLICY_TEST
1383 int testIndex = testOutputIndex(output);
1384 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001385 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001386 if (outputDesc->isActive()) {
1387 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001388 mOutputs.removeItem(output);
1389 mTestOutputs[testIndex] = 0;
1390 }
1391 return;
1392 }
1393#endif //AUDIO_POLICY_TEST
1394
Eric Laurent1f2f2232014-06-02 12:01:23 -07001395 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001396 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001397 if (desc->mDirectOpenCount <= 0) {
1398 ALOGW("releaseOutput() invalid open count %d for output %d",
1399 desc->mDirectOpenCount, output);
1400 return;
1401 }
1402 if (--desc->mDirectOpenCount == 0) {
1403 closeOutput(output);
1404 // If effects where present on the output, audioflinger moved them to the primary
1405 // output by default: move them back to the appropriate output.
1406 audio_io_handle_t dstOutput = getOutputForEffect();
1407 if (dstOutput != mPrimaryOutput) {
1408 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1409 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001410 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001411 }
1412 }
1413}
1414
1415
Eric Laurentcaf7f482014-11-25 17:50:47 -08001416status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1417 audio_io_handle_t *input,
1418 audio_session_t session,
1419 uint32_t samplingRate,
1420 audio_format_t format,
1421 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001422 audio_input_flags_t flags,
1423 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001424{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001425 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1426 "session %d, flags %#x",
1427 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001428
Eric Laurentcaf7f482014-11-25 17:50:47 -08001429 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001430 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001431 audio_devices_t device;
1432 // handle legacy remote submix case where the address was not always specified
1433 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001434 bool isSoundTrigger = false;
Eric Laurentcaf7f482014-11-25 17:50:47 -08001435 audio_source_t halInputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001436 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001437
1438 if (attr->source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1439 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1440 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1441 address = String8(attr->tags + strlen("addr="));
1442 ssize_t index = mPolicyMixes.indexOfKey(address);
1443 if (index < 0) {
1444 ALOGW("getInputForAttr() no policy for address %s", address.string());
1445 return BAD_VALUE;
1446 }
Eric Laurentc722f302014-12-10 11:21:49 -08001447 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1448 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1449 return BAD_VALUE;
1450 }
1451 policyMix = &mPolicyMixes[index]->mMix;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001452 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001453 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001454 device = getDeviceAndMixForInputSource(attr->source, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001455 if (device == AUDIO_DEVICE_NONE) {
1456 ALOGW("getInputForAttr() could not find device for source %d", attr->source);
1457 return BAD_VALUE;
1458 }
Eric Laurentc722f302014-12-10 11:21:49 -08001459 if (policyMix != NULL) {
1460 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001461 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1462 // there is an external policy, but this input is attached to a mix of recorders,
1463 // meaning it receives audio injected into the framework, so the recorder doesn't
1464 // know about it and is therefore considered "legacy"
1465 *inputType = API_INPUT_LEGACY;
1466 } else {
1467 // recording a mix of players defined by an external policy, we're rerouting for
1468 // an external policy
1469 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1470 }
Eric Laurentc722f302014-12-10 11:21:49 -08001471 } else if (audio_is_remote_submix_device(device)) {
1472 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001473 *inputType = API_INPUT_MIX_CAPTURE;
1474 } else {
1475 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001476 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001477 // adapt channel selection to input source
1478 switch (attr->source) {
1479 case AUDIO_SOURCE_VOICE_UPLINK:
1480 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1481 break;
1482 case AUDIO_SOURCE_VOICE_DOWNLINK:
1483 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1484 break;
1485 case AUDIO_SOURCE_VOICE_CALL:
1486 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1487 break;
1488 default:
1489 break;
1490 }
1491 if (attr->source == AUDIO_SOURCE_HOTWORD) {
1492 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1493 if (index >= 0) {
1494 *input = mSoundTriggerSessions.valueFor(session);
1495 isSoundTrigger = true;
1496 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1497 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1498 } else {
1499 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1500 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001501 }
1502 }
1503
Eric Laurent275e8e92014-11-30 15:14:47 -08001504 sp<IOProfile> profile = getInputProfile(device, address,
1505 samplingRate, format, channelMask,
1506 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001507 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001508 //retry without flags
1509 audio_input_flags_t log_flags = flags;
1510 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001511 profile = getInputProfile(device, address,
1512 samplingRate, format, channelMask,
1513 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001514 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001515 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1516 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001517 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001518 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001519 }
Eric Laurente552edb2014-03-10 17:42:56 -07001520 }
1521
1522 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001523 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1524 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001525 }
1526
1527 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1528 config.sample_rate = samplingRate;
1529 config.channel_mask = channelMask;
1530 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001531
Eric Laurentcf2c0212014-07-25 16:20:43 -07001532 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001533 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001534 &config,
1535 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001536 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001537 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001538 flags);
1539
1540 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001541 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001542 (samplingRate != config.sample_rate) ||
1543 (format != config.format) ||
1544 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001545 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001546 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001547 if (*input != AUDIO_IO_HANDLE_NONE) {
1548 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001549 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001550 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001551 }
1552
Eric Laurent1f2f2232014-06-02 12:01:23 -07001553 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001554 inputDesc->mInputSource = attr->source;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001555 inputDesc->mRefCount = 0;
1556 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001557 inputDesc->mSamplingRate = samplingRate;
1558 inputDesc->mFormat = format;
1559 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001560 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001561 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001562 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001563 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001564
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001565 ALOGV("getInputForAttr() returns input type = %d", inputType);
1566
Eric Laurentcaf7f482014-11-25 17:50:47 -08001567 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001568 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001569 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001570}
1571
Eric Laurent4dc68062014-07-28 17:26:49 -07001572status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1573 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001574{
1575 ALOGV("startInput() input %d", input);
1576 ssize_t index = mInputs.indexOfKey(input);
1577 if (index < 0) {
1578 ALOGW("startInput() unknown input %d", input);
1579 return BAD_VALUE;
1580 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001581 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001582
Eric Laurentc722f302014-12-10 11:21:49 -08001583 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001584 if (index < 0) {
1585 ALOGW("startInput() unknown session %d on input %d", session, input);
1586 return BAD_VALUE;
1587 }
1588
Glenn Kasten74a8e252014-07-24 14:09:55 -07001589 // virtual input devices are compatible with other input devices
1590 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1591
1592 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001593 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001594 if (activeInput != 0 && activeInput != input) {
1595
1596 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1597 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001598 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001599 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001600 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001601 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1602 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001603 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001604 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001605 return INVALID_OPERATION;
1606 }
1607 }
1608 }
1609
Glenn Kasten74a8e252014-07-24 14:09:55 -07001610 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001611 if (activeInputsCount() == 0) {
1612 SoundTrigger::setCaptureState(true);
1613 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001614 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001615
Eric Laurentc722f302014-12-10 11:21:49 -08001616 // automatically enable the remote submix output when input is started if not
1617 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001618 // For remote submix (a virtual device), we open only one input per capture request.
1619 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001620 String8 address = String8("");
1621 if (inputDesc->mPolicyMix == NULL) {
1622 address = String8("0");
1623 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1624 address = inputDesc->mPolicyMix->mRegistrationId;
1625 }
1626 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001627 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001628 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1629 address);
1630 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001631 }
Eric Laurente552edb2014-03-10 17:42:56 -07001632 }
1633
Eric Laurente552edb2014-03-10 17:42:56 -07001634 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1635
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001636 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001637 return NO_ERROR;
1638}
1639
Eric Laurent4dc68062014-07-28 17:26:49 -07001640status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1641 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001642{
1643 ALOGV("stopInput() input %d", input);
1644 ssize_t index = mInputs.indexOfKey(input);
1645 if (index < 0) {
1646 ALOGW("stopInput() unknown input %d", input);
1647 return BAD_VALUE;
1648 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001649 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001650
Eric Laurentc722f302014-12-10 11:21:49 -08001651 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001652 if (index < 0) {
1653 ALOGW("stopInput() unknown session %d on input %d", session, input);
1654 return BAD_VALUE;
1655 }
1656
Eric Laurente552edb2014-03-10 17:42:56 -07001657 if (inputDesc->mRefCount == 0) {
1658 ALOGW("stopInput() input %d already stopped", input);
1659 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001660 }
1661
1662 inputDesc->mRefCount--;
1663 if (inputDesc->mRefCount == 0) {
1664
Eric Laurentc722f302014-12-10 11:21:49 -08001665 // automatically disable the remote submix output when input is stopped if not
1666 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001667 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001668 String8 address = String8("");
1669 if (inputDesc->mPolicyMix == NULL) {
1670 address = String8("0");
1671 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1672 address = inputDesc->mPolicyMix->mRegistrationId;
1673 }
1674 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001675 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001676 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1677 address);
1678 }
Eric Laurente552edb2014-03-10 17:42:56 -07001679 }
1680
Eric Laurent1c333e22014-05-20 10:48:17 -07001681 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001682
1683 if (activeInputsCount() == 0) {
1684 SoundTrigger::setCaptureState(false);
1685 }
Eric Laurente552edb2014-03-10 17:42:56 -07001686 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001687 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001688}
1689
Eric Laurent4dc68062014-07-28 17:26:49 -07001690void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1691 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001692{
1693 ALOGV("releaseInput() %d", input);
1694 ssize_t index = mInputs.indexOfKey(input);
1695 if (index < 0) {
1696 ALOGW("releaseInput() releasing unknown input %d", input);
1697 return;
1698 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001699 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1700 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001701
Eric Laurentc722f302014-12-10 11:21:49 -08001702 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001703 if (index < 0) {
1704 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1705 return;
1706 }
Eric Laurentc722f302014-12-10 11:21:49 -08001707 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001708 if (inputDesc->mOpenRefCount == 0) {
1709 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1710 return;
1711 }
1712 inputDesc->mOpenRefCount--;
1713 if (inputDesc->mOpenRefCount > 0) {
1714 ALOGV("releaseInput() exit > 0");
1715 return;
1716 }
1717
Eric Laurent05b90f82014-08-27 15:32:29 -07001718 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001719 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001720 ALOGV("releaseInput() exit");
1721}
1722
Eric Laurentd4692962014-05-05 18:13:44 -07001723void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001724 bool patchRemoved = false;
1725
Eric Laurentd4692962014-05-05 18:13:44 -07001726 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001727 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1728 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1729 if (patch_index >= 0) {
1730 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1731 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1732 mAudioPatches.removeItemsAt(patch_index);
1733 patchRemoved = true;
1734 }
Eric Laurentd4692962014-05-05 18:13:44 -07001735 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1736 }
1737 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001738 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001739
1740 if (patchRemoved) {
1741 mpClientInterface->onAudioPatchListUpdate();
1742 }
Eric Laurentd4692962014-05-05 18:13:44 -07001743}
1744
Eric Laurente0720872014-03-11 09:30:41 -07001745void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001746 int indexMin,
1747 int indexMax)
1748{
1749 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1750 if (indexMin < 0 || indexMin >= indexMax) {
1751 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1752 return;
1753 }
1754 mStreams[stream].mIndexMin = indexMin;
1755 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001756 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1757 if (stream == AUDIO_STREAM_MUSIC) {
1758 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1759 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1760 }
Eric Laurente552edb2014-03-10 17:42:56 -07001761}
1762
Eric Laurente0720872014-03-11 09:30:41 -07001763status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001764 int index,
1765 audio_devices_t device)
1766{
1767
1768 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1769 return BAD_VALUE;
1770 }
1771 if (!audio_is_output_device(device)) {
1772 return BAD_VALUE;
1773 }
1774
1775 // Force max volume if stream cannot be muted
1776 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1777
1778 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1779 stream, device, index);
1780
1781 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1782 // clear all device specific values
1783 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1784 mStreams[stream].mIndexCur.clear();
1785 }
1786 mStreams[stream].mIndexCur.add(device, index);
1787
Eric Laurent31551f82014-10-10 18:21:56 -07001788 // update volume on all outputs whose current device is also selected by the same
1789 // strategy as the device specified by the caller
1790 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001791
1792
1793 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1794 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1795 if (stream == AUDIO_STREAM_MUSIC) {
1796 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1797 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1798 }
1799 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1800 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001801 return NO_ERROR;
1802 }
Eric Laurente552edb2014-03-10 17:42:56 -07001803 status_t status = NO_ERROR;
1804 for (size_t i = 0; i < mOutputs.size(); i++) {
1805 audio_devices_t curDevice =
1806 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001807 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001808 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1809 if (volStatus != NO_ERROR) {
1810 status = volStatus;
1811 }
1812 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001813 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1814 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1815 index, mOutputs.keyAt(i), curDevice);
1816 }
Eric Laurente552edb2014-03-10 17:42:56 -07001817 }
1818 return status;
1819}
1820
Eric Laurente0720872014-03-11 09:30:41 -07001821status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001822 int *index,
1823 audio_devices_t device)
1824{
1825 if (index == NULL) {
1826 return BAD_VALUE;
1827 }
1828 if (!audio_is_output_device(device)) {
1829 return BAD_VALUE;
1830 }
1831 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1832 // the strategy the stream belongs to.
1833 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1834 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1835 }
1836 device = getDeviceForVolume(device);
1837
1838 *index = mStreams[stream].getVolumeIndex(device);
1839 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1840 return NO_ERROR;
1841}
1842
Eric Laurente0720872014-03-11 09:30:41 -07001843audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001844 const SortedVector<audio_io_handle_t>& outputs)
1845{
1846 // select one output among several suitable for global effects.
1847 // The priority is as follows:
1848 // 1: An offloaded output. If the effect ends up not being offloadable,
1849 // AudioFlinger will invalidate the track and the offloaded output
1850 // will be closed causing the effect to be moved to a PCM output.
1851 // 2: A deep buffer output
1852 // 3: the first output in the list
1853
1854 if (outputs.size() == 0) {
1855 return 0;
1856 }
1857
1858 audio_io_handle_t outputOffloaded = 0;
1859 audio_io_handle_t outputDeepBuffer = 0;
1860
1861 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001862 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001863 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001864 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1865 outputOffloaded = outputs[i];
1866 }
1867 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1868 outputDeepBuffer = outputs[i];
1869 }
1870 }
1871
1872 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1873 outputOffloaded, outputDeepBuffer);
1874 if (outputOffloaded != 0) {
1875 return outputOffloaded;
1876 }
1877 if (outputDeepBuffer != 0) {
1878 return outputDeepBuffer;
1879 }
1880
1881 return outputs[0];
1882}
1883
Eric Laurente0720872014-03-11 09:30:41 -07001884audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001885{
1886 // apply simple rule where global effects are attached to the same output as MUSIC streams
1887
Eric Laurent3b73df72014-03-11 09:06:29 -07001888 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001889 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1890 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1891
1892 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1893 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1894 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1895
1896 return output;
1897}
1898
Eric Laurente0720872014-03-11 09:30:41 -07001899status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001900 audio_io_handle_t io,
1901 uint32_t strategy,
1902 int session,
1903 int id)
1904{
1905 ssize_t index = mOutputs.indexOfKey(io);
1906 if (index < 0) {
1907 index = mInputs.indexOfKey(io);
1908 if (index < 0) {
1909 ALOGW("registerEffect() unknown io %d", io);
1910 return INVALID_OPERATION;
1911 }
1912 }
1913
1914 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1915 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1916 desc->name, desc->memoryUsage);
1917 return INVALID_OPERATION;
1918 }
1919 mTotalEffectsMemory += desc->memoryUsage;
1920 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1921 desc->name, io, strategy, session, id);
1922 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1923
Eric Laurent1f2f2232014-06-02 12:01:23 -07001924 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1925 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1926 effectDesc->mIo = io;
1927 effectDesc->mStrategy = (routing_strategy)strategy;
1928 effectDesc->mSession = session;
1929 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001930
Eric Laurent1f2f2232014-06-02 12:01:23 -07001931 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001932
1933 return NO_ERROR;
1934}
1935
Eric Laurente0720872014-03-11 09:30:41 -07001936status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001937{
1938 ssize_t index = mEffects.indexOfKey(id);
1939 if (index < 0) {
1940 ALOGW("unregisterEffect() unknown effect ID %d", id);
1941 return INVALID_OPERATION;
1942 }
1943
Eric Laurent1f2f2232014-06-02 12:01:23 -07001944 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001945
Eric Laurent1f2f2232014-06-02 12:01:23 -07001946 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001947
Eric Laurent1f2f2232014-06-02 12:01:23 -07001948 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001949 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001950 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1951 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001952 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001953 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001954 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001955 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001956
1957 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001958
1959 return NO_ERROR;
1960}
1961
Eric Laurente0720872014-03-11 09:30:41 -07001962status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001963{
1964 ssize_t index = mEffects.indexOfKey(id);
1965 if (index < 0) {
1966 ALOGW("unregisterEffect() unknown effect ID %d", id);
1967 return INVALID_OPERATION;
1968 }
1969
1970 return setEffectEnabled(mEffects.valueAt(index), enabled);
1971}
1972
Eric Laurent1f2f2232014-06-02 12:01:23 -07001973status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001974{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001975 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001976 ALOGV("setEffectEnabled(%s) effect already %s",
1977 enabled?"true":"false", enabled?"enabled":"disabled");
1978 return INVALID_OPERATION;
1979 }
1980
1981 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001982 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001983 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001984 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001985 return INVALID_OPERATION;
1986 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001987 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001988 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1989 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001990 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001991 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001992 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1993 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001994 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001995 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001996 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1997 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001998 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001999 return NO_ERROR;
2000}
2001
Eric Laurente0720872014-03-11 09:30:41 -07002002bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07002003{
2004 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002005 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
2006 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
2007 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002008 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002009 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07002010 return true;
2011 }
2012 }
2013 return false;
2014}
2015
Eric Laurente0720872014-03-11 09:30:41 -07002016bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002017{
2018 nsecs_t sysTime = systemTime();
2019 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002020 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002021 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002022 return true;
2023 }
2024 }
2025 return false;
2026}
2027
Eric Laurente0720872014-03-11 09:30:41 -07002028bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002029 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002030{
2031 nsecs_t sysTime = systemTime();
2032 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002033 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002034 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002035 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002036 // do not consider re routing (when the output is going to a dynamic policy)
2037 // as "remote playback"
2038 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002039 return true;
2040 }
Eric Laurente552edb2014-03-10 17:42:56 -07002041 }
2042 }
2043 return false;
2044}
2045
Eric Laurente0720872014-03-11 09:30:41 -07002046bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002047{
2048 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002049 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002050 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002051 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07002052 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
2053 && (inputDescriptor->mRefCount > 0)) {
2054 return true;
2055 }
2056 }
2057 return false;
2058}
2059
Eric Laurent275e8e92014-11-30 15:14:47 -08002060// Register a list of custom mixes with their attributes and format.
2061// When a mix is registered, corresponding input and output profiles are
2062// added to the remote submix hw module. The profile contains only the
2063// parameters (sampling rate, format...) specified by the mix.
2064// The corresponding input remote submix device is also connected.
2065//
2066// When a remote submix device is connected, the address is checked to select the
2067// appropriate profile and the corresponding input or output stream is opened.
2068//
2069// When capture starts, getInputForAttr() will:
2070// - 1 look for a mix matching the address passed in attribtutes tags if any
2071// - 2 if none found, getDeviceForInputSource() will:
2072// - 2.1 look for a mix matching the attributes source
2073// - 2.2 if none found, default to device selection by policy rules
2074// At this time, the corresponding output remote submix device is also connected
2075// and active playback use cases can be transferred to this mix if needed when reconnecting
2076// after AudioTracks are invalidated
2077//
2078// When playback starts, getOutputForAttr() will:
2079// - 1 look for a mix matching the address passed in attribtutes tags if any
2080// - 2 if none found, look for a mix matching the attributes usage
2081// - 3 if none found, default to device and output selection by policy rules.
2082
2083status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2084{
2085 sp<HwModule> module;
2086 for (size_t i = 0; i < mHwModules.size(); i++) {
2087 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2088 mHwModules[i]->mHandle != 0) {
2089 module = mHwModules[i];
2090 break;
2091 }
2092 }
2093
2094 if (module == 0) {
2095 return INVALID_OPERATION;
2096 }
2097
2098 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2099
2100 for (size_t i = 0; i < mixes.size(); i++) {
2101 String8 address = mixes[i].mRegistrationId;
2102 ssize_t index = mPolicyMixes.indexOfKey(address);
2103 if (index >= 0) {
2104 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2105 continue;
2106 }
2107 audio_config_t outputConfig = mixes[i].mFormat;
2108 audio_config_t inputConfig = mixes[i].mFormat;
2109 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2110 // stereo and let audio flinger do the channel conversion if needed.
2111 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2112 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2113 module->addOutputProfile(address, &outputConfig,
2114 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2115 module->addInputProfile(address, &inputConfig,
2116 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2117 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2118 policyMix->mMix = mixes[i];
2119 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002120 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002121 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002122 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2123 address.string());
2124 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002125 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002126 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2127 address.string());
2128 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002129 }
2130 return NO_ERROR;
2131}
2132
2133status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2134{
2135 sp<HwModule> module;
2136 for (size_t i = 0; i < mHwModules.size(); i++) {
2137 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2138 mHwModules[i]->mHandle != 0) {
2139 module = mHwModules[i];
2140 break;
2141 }
2142 }
2143
2144 if (module == 0) {
2145 return INVALID_OPERATION;
2146 }
2147
2148 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2149
2150 for (size_t i = 0; i < mixes.size(); i++) {
2151 String8 address = mixes[i].mRegistrationId;
2152 ssize_t index = mPolicyMixes.indexOfKey(address);
2153 if (index < 0) {
2154 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2155 continue;
2156 }
2157
2158 mPolicyMixes.removeItemsAt(index);
2159
Eric Laurentc722f302014-12-10 11:21:49 -08002160 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2161 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2162 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002163 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002164 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2165 address.string());
2166 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002167
2168 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2169 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2170 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002171 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002172 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2173 address.string());
2174 }
2175 module->removeOutputProfile(address);
2176 module->removeInputProfile(address);
2177 }
2178 return NO_ERROR;
2179}
2180
Eric Laurente552edb2014-03-10 17:42:56 -07002181
Eric Laurente0720872014-03-11 09:30:41 -07002182status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002183{
2184 const size_t SIZE = 256;
2185 char buffer[SIZE];
2186 String8 result;
2187
2188 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2189 result.append(buffer);
2190
2191 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2192 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002193 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2194 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002195 snprintf(buffer, SIZE, " Force use for communications %d\n",
2196 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002197 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002198 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002199 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002200 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002201 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002202 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002203 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002204 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002205 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002206 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2207 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2208 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002209
Eric Laurent3a4311c2014-03-17 12:00:47 -07002210 snprintf(buffer, SIZE, " Available output devices:\n");
2211 result.append(buffer);
2212 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002213 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002214 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002215 }
2216 snprintf(buffer, SIZE, "\n Available input devices:\n");
2217 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002218 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002219 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002220 }
Eric Laurente552edb2014-03-10 17:42:56 -07002221
2222 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2223 write(fd, buffer, strlen(buffer));
2224 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002225 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002226 write(fd, buffer, strlen(buffer));
2227 mHwModules[i]->dump(fd);
2228 }
2229
2230 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2231 write(fd, buffer, strlen(buffer));
2232 for (size_t i = 0; i < mOutputs.size(); i++) {
2233 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2234 write(fd, buffer, strlen(buffer));
2235 mOutputs.valueAt(i)->dump(fd);
2236 }
2237
2238 snprintf(buffer, SIZE, "\nInputs dump:\n");
2239 write(fd, buffer, strlen(buffer));
2240 for (size_t i = 0; i < mInputs.size(); i++) {
2241 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2242 write(fd, buffer, strlen(buffer));
2243 mInputs.valueAt(i)->dump(fd);
2244 }
2245
2246 snprintf(buffer, SIZE, "\nStreams dump:\n");
2247 write(fd, buffer, strlen(buffer));
2248 snprintf(buffer, SIZE,
2249 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2250 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002251 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002252 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002253 write(fd, buffer, strlen(buffer));
2254 mStreams[i].dump(fd);
2255 }
2256
2257 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2258 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2259 write(fd, buffer, strlen(buffer));
2260
2261 snprintf(buffer, SIZE, "Registered effects:\n");
2262 write(fd, buffer, strlen(buffer));
2263 for (size_t i = 0; i < mEffects.size(); i++) {
2264 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2265 write(fd, buffer, strlen(buffer));
2266 mEffects.valueAt(i)->dump(fd);
2267 }
2268
Eric Laurent4d416952014-08-10 14:07:09 -07002269 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2270 write(fd, buffer, strlen(buffer));
2271 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2272 mAudioPatches[i]->dump(fd, 2, i);
2273 }
Eric Laurente552edb2014-03-10 17:42:56 -07002274
2275 return NO_ERROR;
2276}
2277
2278// This function checks for the parameters which can be offloaded.
2279// This can be enhanced depending on the capability of the DSP and policy
2280// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002281bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002282{
2283 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002284 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002285 offloadInfo.sample_rate, offloadInfo.channel_mask,
2286 offloadInfo.format,
2287 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2288 offloadInfo.has_video);
2289
2290 // Check if offload has been disabled
2291 char propValue[PROPERTY_VALUE_MAX];
2292 if (property_get("audio.offload.disable", propValue, "0")) {
2293 if (atoi(propValue) != 0) {
2294 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2295 return false;
2296 }
2297 }
2298
2299 // Check if stream type is music, then only allow offload as of now.
2300 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2301 {
2302 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2303 return false;
2304 }
2305
2306 //TODO: enable audio offloading with video when ready
2307 if (offloadInfo.has_video)
2308 {
2309 ALOGV("isOffloadSupported: has_video == true, returning false");
2310 return false;
2311 }
2312
2313 //If duration is less than minimum value defined in property, return false
2314 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2315 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2316 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2317 return false;
2318 }
2319 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2320 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2321 return false;
2322 }
2323
2324 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2325 // creating an offloaded track and tearing it down immediately after start when audioflinger
2326 // detects there is an active non offloadable effect.
2327 // FIXME: We should check the audio session here but we do not have it in this context.
2328 // This may prevent offloading in rare situations where effects are left active by apps
2329 // in the background.
2330 if (isNonOffloadableEffectEnabled()) {
2331 return false;
2332 }
2333
2334 // See if there is a profile to support this.
2335 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002336 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002337 offloadInfo.sample_rate,
2338 offloadInfo.format,
2339 offloadInfo.channel_mask,
2340 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002341 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2342 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002343}
2344
Eric Laurent6a94d692014-05-20 11:18:06 -07002345status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2346 audio_port_type_t type,
2347 unsigned int *num_ports,
2348 struct audio_port *ports,
2349 unsigned int *generation)
2350{
2351 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2352 generation == NULL) {
2353 return BAD_VALUE;
2354 }
2355 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2356 if (ports == NULL) {
2357 *num_ports = 0;
2358 }
2359
2360 size_t portsWritten = 0;
2361 size_t portsMax = *num_ports;
2362 *num_ports = 0;
2363 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2364 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2365 for (size_t i = 0;
2366 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2367 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2368 }
2369 *num_ports += mAvailableOutputDevices.size();
2370 }
2371 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2372 for (size_t i = 0;
2373 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2374 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2375 }
2376 *num_ports += mAvailableInputDevices.size();
2377 }
2378 }
2379 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2380 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2381 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2382 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2383 }
2384 *num_ports += mInputs.size();
2385 }
2386 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002387 size_t numOutputs = 0;
2388 for (size_t i = 0; i < mOutputs.size(); i++) {
2389 if (!mOutputs[i]->isDuplicated()) {
2390 numOutputs++;
2391 if (portsWritten < portsMax) {
2392 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2393 }
2394 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002395 }
Eric Laurent84c70242014-06-23 08:46:27 -07002396 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002397 }
2398 }
2399 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002400 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002401 return NO_ERROR;
2402}
2403
2404status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2405{
2406 return NO_ERROR;
2407}
2408
Eric Laurent1f2f2232014-06-02 12:01:23 -07002409sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002410 audio_port_handle_t id) const
2411{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002412 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002413 for (size_t i = 0; i < mOutputs.size(); i++) {
2414 outputDesc = mOutputs.valueAt(i);
2415 if (outputDesc->mId == id) {
2416 break;
2417 }
2418 }
2419 return outputDesc;
2420}
2421
Eric Laurent1f2f2232014-06-02 12:01:23 -07002422sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002423 audio_port_handle_t id) const
2424{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002425 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002426 for (size_t i = 0; i < mInputs.size(); i++) {
2427 inputDesc = mInputs.valueAt(i);
2428 if (inputDesc->mId == id) {
2429 break;
2430 }
2431 }
2432 return inputDesc;
2433}
2434
Eric Laurent1f2f2232014-06-02 12:01:23 -07002435sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2436 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002437{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002438 sp <HwModule> module;
2439
Eric Laurent6a94d692014-05-20 11:18:06 -07002440 for (size_t i = 0; i < mHwModules.size(); i++) {
2441 if (mHwModules[i]->mHandle == 0) {
2442 continue;
2443 }
2444 if (audio_is_output_device(device)) {
2445 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2446 {
2447 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2448 return mHwModules[i];
2449 }
2450 }
2451 } else {
2452 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2453 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2454 device & ~AUDIO_DEVICE_BIT_IN) {
2455 return mHwModules[i];
2456 }
2457 }
2458 }
2459 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002460 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002461}
2462
Eric Laurent1f2f2232014-06-02 12:01:23 -07002463sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002464{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002465 sp <HwModule> module;
2466
Eric Laurent1afeecb2014-05-14 08:52:28 -07002467 for (size_t i = 0; i < mHwModules.size(); i++)
2468 {
2469 if (strcmp(mHwModules[i]->mName, name) == 0) {
2470 return mHwModules[i];
2471 }
2472 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002473 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002474}
2475
Eric Laurentc2730ba2014-07-20 15:47:07 -07002476audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2477{
2478 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2479 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2480 return devices & mAvailableOutputDevices.types();
2481}
2482
2483audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2484{
2485 audio_module_handle_t primaryHandle =
2486 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2487 audio_devices_t devices = AUDIO_DEVICE_NONE;
2488 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2489 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2490 devices |= mAvailableInputDevices[i]->mDeviceType;
2491 }
2492 }
2493 return devices;
2494}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002495
Eric Laurent6a94d692014-05-20 11:18:06 -07002496status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2497 audio_patch_handle_t *handle,
2498 uid_t uid)
2499{
2500 ALOGV("createAudioPatch()");
2501
2502 if (handle == NULL || patch == NULL) {
2503 return BAD_VALUE;
2504 }
2505 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2506
Eric Laurent874c42872014-08-08 15:13:39 -07002507 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2508 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2509 return BAD_VALUE;
2510 }
2511 // only one source per audio patch supported for now
2512 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002513 return INVALID_OPERATION;
2514 }
Eric Laurent874c42872014-08-08 15:13:39 -07002515
2516 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002517 return INVALID_OPERATION;
2518 }
Eric Laurent874c42872014-08-08 15:13:39 -07002519 for (size_t i = 0; i < patch->num_sinks; i++) {
2520 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2521 return INVALID_OPERATION;
2522 }
2523 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002524
2525 sp<AudioPatch> patchDesc;
2526 ssize_t index = mAudioPatches.indexOfKey(*handle);
2527
Eric Laurent6a94d692014-05-20 11:18:06 -07002528 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2529 patch->sources[0].role,
2530 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002531#if LOG_NDEBUG == 0
2532 for (size_t i = 0; i < patch->num_sinks; i++) {
2533 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2534 patch->sinks[i].role,
2535 patch->sinks[i].type);
2536 }
2537#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002538
2539 if (index >= 0) {
2540 patchDesc = mAudioPatches.valueAt(index);
2541 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2542 mUidCached, patchDesc->mUid, uid);
2543 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2544 return INVALID_OPERATION;
2545 }
2546 } else {
2547 *handle = 0;
2548 }
2549
2550 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002551 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002552 if (outputDesc == NULL) {
2553 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2554 return BAD_VALUE;
2555 }
Eric Laurent84c70242014-06-23 08:46:27 -07002556 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2557 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002558 if (patchDesc != 0) {
2559 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2560 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2561 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2562 return BAD_VALUE;
2563 }
2564 }
Eric Laurent874c42872014-08-08 15:13:39 -07002565 DeviceVector devices;
2566 for (size_t i = 0; i < patch->num_sinks; i++) {
2567 // Only support mix to devices connection
2568 // TODO add support for mix to mix connection
2569 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2570 ALOGV("createAudioPatch() source mix but sink is not a device");
2571 return INVALID_OPERATION;
2572 }
2573 sp<DeviceDescriptor> devDesc =
2574 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2575 if (devDesc == 0) {
2576 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2577 return BAD_VALUE;
2578 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002579
Eric Laurent874c42872014-08-08 15:13:39 -07002580 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002581 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002582 patch->sources[0].sample_rate,
2583 NULL, // updatedSamplingRate
2584 patch->sources[0].format,
2585 patch->sources[0].channel_mask,
2586 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2587 ALOGV("createAudioPatch() profile not supported for device %08x",
2588 devDesc->mDeviceType);
2589 return INVALID_OPERATION;
2590 }
2591 devices.add(devDesc);
2592 }
2593 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002594 return INVALID_OPERATION;
2595 }
Eric Laurent874c42872014-08-08 15:13:39 -07002596
Eric Laurent6a94d692014-05-20 11:18:06 -07002597 // TODO: reconfigure output format and channels here
2598 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002599 devices.types(), outputDesc->mIoHandle);
2600 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002601 index = mAudioPatches.indexOfKey(*handle);
2602 if (index >= 0) {
2603 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2604 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2605 }
2606 patchDesc = mAudioPatches.valueAt(index);
2607 patchDesc->mUid = uid;
2608 ALOGV("createAudioPatch() success");
2609 } else {
2610 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2611 return INVALID_OPERATION;
2612 }
2613 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2614 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2615 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002616 // only one sink supported when connecting an input device to a mix
2617 if (patch->num_sinks > 1) {
2618 return INVALID_OPERATION;
2619 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002620 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002621 if (inputDesc == NULL) {
2622 return BAD_VALUE;
2623 }
2624 if (patchDesc != 0) {
2625 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2626 return BAD_VALUE;
2627 }
2628 }
2629 sp<DeviceDescriptor> devDesc =
2630 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2631 if (devDesc == 0) {
2632 return BAD_VALUE;
2633 }
2634
Eric Laurent84c70242014-06-23 08:46:27 -07002635 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002636 devDesc->mAddress,
2637 patch->sinks[0].sample_rate,
2638 NULL, /*updatedSampleRate*/
2639 patch->sinks[0].format,
2640 patch->sinks[0].channel_mask,
2641 // FIXME for the parameter type,
2642 // and the NONE
2643 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002644 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002645 return INVALID_OPERATION;
2646 }
2647 // TODO: reconfigure output format and channels here
2648 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002649 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002650 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002651 index = mAudioPatches.indexOfKey(*handle);
2652 if (index >= 0) {
2653 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2654 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2655 }
2656 patchDesc = mAudioPatches.valueAt(index);
2657 patchDesc->mUid = uid;
2658 ALOGV("createAudioPatch() success");
2659 } else {
2660 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2661 return INVALID_OPERATION;
2662 }
2663 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2664 // device to device connection
2665 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002666 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002667 return BAD_VALUE;
2668 }
2669 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002670 sp<DeviceDescriptor> srcDeviceDesc =
2671 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002672 if (srcDeviceDesc == 0) {
2673 return BAD_VALUE;
2674 }
Eric Laurent874c42872014-08-08 15:13:39 -07002675
Eric Laurent6a94d692014-05-20 11:18:06 -07002676 //update source and sink with our own data as the data passed in the patch may
2677 // be incomplete.
2678 struct audio_patch newPatch = *patch;
2679 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002680
Eric Laurent874c42872014-08-08 15:13:39 -07002681 for (size_t i = 0; i < patch->num_sinks; i++) {
2682 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2683 ALOGV("createAudioPatch() source device but one sink is not a device");
2684 return INVALID_OPERATION;
2685 }
2686
2687 sp<DeviceDescriptor> sinkDeviceDesc =
2688 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2689 if (sinkDeviceDesc == 0) {
2690 return BAD_VALUE;
2691 }
2692 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2693
2694 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2695 // only one sink supported when connected devices across HW modules
2696 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002697 return INVALID_OPERATION;
2698 }
Eric Laurent874c42872014-08-08 15:13:39 -07002699 SortedVector<audio_io_handle_t> outputs =
2700 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2701 mOutputs);
2702 // if the sink device is reachable via an opened output stream, request to go via
2703 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002704 audio_io_handle_t output = selectOutput(outputs,
2705 AUDIO_OUTPUT_FLAG_NONE,
2706 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002707 if (output != AUDIO_IO_HANDLE_NONE) {
2708 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2709 if (outputDesc->isDuplicated()) {
2710 return INVALID_OPERATION;
2711 }
2712 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2713 newPatch.num_sources = 2;
2714 }
Eric Laurent83b88082014-06-20 18:31:16 -07002715 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002716 }
2717 // TODO: check from routing capabilities in config file and other conflicting patches
2718
2719 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2720 if (index >= 0) {
2721 afPatchHandle = patchDesc->mAfPatchHandle;
2722 }
2723
2724 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2725 &afPatchHandle,
2726 0);
2727 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2728 status, afPatchHandle);
2729 if (status == NO_ERROR) {
2730 if (index < 0) {
2731 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2732 &newPatch, uid);
2733 addAudioPatch(patchDesc->mHandle, patchDesc);
2734 } else {
2735 patchDesc->mPatch = newPatch;
2736 }
2737 patchDesc->mAfPatchHandle = afPatchHandle;
2738 *handle = patchDesc->mHandle;
2739 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002740 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002741 } else {
2742 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2743 status);
2744 return INVALID_OPERATION;
2745 }
2746 } else {
2747 return BAD_VALUE;
2748 }
2749 } else {
2750 return BAD_VALUE;
2751 }
2752 return NO_ERROR;
2753}
2754
2755status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2756 uid_t uid)
2757{
2758 ALOGV("releaseAudioPatch() patch %d", handle);
2759
2760 ssize_t index = mAudioPatches.indexOfKey(handle);
2761
2762 if (index < 0) {
2763 return BAD_VALUE;
2764 }
2765 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2766 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2767 mUidCached, patchDesc->mUid, uid);
2768 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2769 return INVALID_OPERATION;
2770 }
2771
2772 struct audio_patch *patch = &patchDesc->mPatch;
2773 patchDesc->mUid = mUidCached;
2774 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002775 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002776 if (outputDesc == NULL) {
2777 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2778 return BAD_VALUE;
2779 }
2780
2781 setOutputDevice(outputDesc->mIoHandle,
2782 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2783 true,
2784 0,
2785 NULL);
2786 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2787 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002788 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002789 if (inputDesc == NULL) {
2790 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2791 return BAD_VALUE;
2792 }
2793 setInputDevice(inputDesc->mIoHandle,
2794 getNewInputDevice(inputDesc->mIoHandle),
2795 true,
2796 NULL);
2797 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2798 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2799 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2800 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2801 status, patchDesc->mAfPatchHandle);
2802 removeAudioPatch(patchDesc->mHandle);
2803 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002804 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002805 } else {
2806 return BAD_VALUE;
2807 }
2808 } else {
2809 return BAD_VALUE;
2810 }
2811 return NO_ERROR;
2812}
2813
2814status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2815 struct audio_patch *patches,
2816 unsigned int *generation)
2817{
2818 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2819 generation == NULL) {
2820 return BAD_VALUE;
2821 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002822 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002823 *num_patches, patches, mAudioPatches.size());
2824 if (patches == NULL) {
2825 *num_patches = 0;
2826 }
2827
2828 size_t patchesWritten = 0;
2829 size_t patchesMax = *num_patches;
2830 for (size_t i = 0;
2831 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2832 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2833 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002834 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2836 }
2837 *num_patches = mAudioPatches.size();
2838
2839 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002840 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002841 return NO_ERROR;
2842}
2843
Eric Laurente1715a42014-05-20 11:30:42 -07002844status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002845{
Eric Laurente1715a42014-05-20 11:30:42 -07002846 ALOGV("setAudioPortConfig()");
2847
2848 if (config == NULL) {
2849 return BAD_VALUE;
2850 }
2851 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2852 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002853 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2854 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002855 }
2856
Eric Laurenta121f902014-06-03 13:32:54 -07002857 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002858 if (config->type == AUDIO_PORT_TYPE_MIX) {
2859 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002860 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002861 if (outputDesc == NULL) {
2862 return BAD_VALUE;
2863 }
Eric Laurent84c70242014-06-23 08:46:27 -07002864 ALOG_ASSERT(!outputDesc->isDuplicated(),
2865 "setAudioPortConfig() called on duplicated output %d",
2866 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002867 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002868 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002869 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002870 if (inputDesc == NULL) {
2871 return BAD_VALUE;
2872 }
Eric Laurenta121f902014-06-03 13:32:54 -07002873 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002874 } else {
2875 return BAD_VALUE;
2876 }
2877 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2878 sp<DeviceDescriptor> deviceDesc;
2879 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2880 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2881 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2882 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2883 } else {
2884 return BAD_VALUE;
2885 }
2886 if (deviceDesc == NULL) {
2887 return BAD_VALUE;
2888 }
Eric Laurenta121f902014-06-03 13:32:54 -07002889 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002890 } else {
2891 return BAD_VALUE;
2892 }
2893
Eric Laurenta121f902014-06-03 13:32:54 -07002894 struct audio_port_config backupConfig;
2895 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2896 if (status == NO_ERROR) {
2897 struct audio_port_config newConfig;
2898 audioPortConfig->toAudioPortConfig(&newConfig, config);
2899 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002900 }
Eric Laurenta121f902014-06-03 13:32:54 -07002901 if (status != NO_ERROR) {
2902 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002903 }
Eric Laurente1715a42014-05-20 11:30:42 -07002904
2905 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002906}
2907
2908void AudioPolicyManager::clearAudioPatches(uid_t uid)
2909{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002910 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002911 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2912 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002913 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002914 }
2915 }
2916}
2917
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002918status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2919 audio_io_handle_t *ioHandle,
2920 audio_devices_t *device)
2921{
2922 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2923 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002924 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002925
2926 mSoundTriggerSessions.add(*session, *ioHandle);
2927
2928 return NO_ERROR;
2929}
2930
2931status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2932{
2933 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2934 if (index < 0) {
2935 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2936 return BAD_VALUE;
2937 }
2938
2939 mSoundTriggerSessions.removeItem(session);
2940 return NO_ERROR;
2941}
2942
Eric Laurent6a94d692014-05-20 11:18:06 -07002943status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2944 const sp<AudioPatch>& patch)
2945{
2946 ssize_t index = mAudioPatches.indexOfKey(handle);
2947
2948 if (index >= 0) {
2949 ALOGW("addAudioPatch() patch %d already in", handle);
2950 return ALREADY_EXISTS;
2951 }
2952 mAudioPatches.add(handle, patch);
2953 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2954 "sink handle %d",
2955 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2956 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2957 return NO_ERROR;
2958}
2959
2960status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2961{
2962 ssize_t index = mAudioPatches.indexOfKey(handle);
2963
2964 if (index < 0) {
2965 ALOGW("removeAudioPatch() patch %d not in", handle);
2966 return ALREADY_EXISTS;
2967 }
2968 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2969 mAudioPatches.valueAt(index)->mAfPatchHandle);
2970 mAudioPatches.removeItemsAt(index);
2971 return NO_ERROR;
2972}
2973
Eric Laurente552edb2014-03-10 17:42:56 -07002974// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002975// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002976// ----------------------------------------------------------------------------
2977
Eric Laurent3a4311c2014-03-17 12:00:47 -07002978uint32_t AudioPolicyManager::nextUniqueId()
2979{
2980 return android_atomic_inc(&mNextUniqueId);
2981}
2982
Eric Laurent6a94d692014-05-20 11:18:06 -07002983uint32_t AudioPolicyManager::nextAudioPortGeneration()
2984{
2985 return android_atomic_inc(&mAudioPortGeneration);
2986}
2987
Eric Laurente0720872014-03-11 09:30:41 -07002988AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002989 :
2990#ifdef AUDIO_POLICY_TEST
2991 Thread(false),
2992#endif //AUDIO_POLICY_TEST
2993 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002994 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002995 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2996 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002997 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002998 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002999 mAudioPortGeneration(1),
3000 mBeaconMuteRefCount(0),
3001 mBeaconPlayingRefCount(0),
3002 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003003{
Eric Laurent6a94d692014-05-20 11:18:06 -07003004 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003005 mpClientInterface = clientInterface;
3006
Eric Laurent3b73df72014-03-11 09:06:29 -07003007 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3008 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003009 }
3010
Eric Laurent1afeecb2014-05-14 08:52:28 -07003011 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07003012 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3013 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3014 ALOGE("could not load audio policy configuration file, setting defaults");
3015 defaultAudioPolicyConfig();
3016 }
3017 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003018 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003019
3020 // must be done after reading the policy
3021 initializeVolumeCurves();
3022
3023 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003024 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3025 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003026 for (size_t i = 0; i < mHwModules.size(); i++) {
3027 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3028 if (mHwModules[i]->mHandle == 0) {
3029 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3030 continue;
3031 }
3032 // open all output streams needed to access attached devices
3033 // except for direct output streams that are only opened when they are actually
3034 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003035 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003036 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3037 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003038 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003039
Eric Laurent3a4311c2014-03-17 12:00:47 -07003040 if (outProfile->mSupportedDevices.isEmpty()) {
3041 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3042 continue;
3043 }
3044
Eric Laurentd78f1532014-09-16 16:38:20 -07003045 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3046 continue;
3047 }
Eric Laurent83b88082014-06-20 18:31:16 -07003048 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3049 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3050 profileType = mDefaultOutputDevice->mDeviceType;
3051 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003052 // chose first device present in mSupportedDevices also part of
3053 // outputDeviceTypes
3054 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3055 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3056 if ((profileType & outputDeviceTypes) != 0) {
3057 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003058 }
Eric Laurente552edb2014-03-10 17:42:56 -07003059 }
3060 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003061 if ((profileType & outputDeviceTypes) == 0) {
3062 continue;
3063 }
3064 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3065
3066 outputDesc->mDevice = profileType;
3067 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3068 config.sample_rate = outputDesc->mSamplingRate;
3069 config.channel_mask = outputDesc->mChannelMask;
3070 config.format = outputDesc->mFormat;
3071 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3072 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3073 &output,
3074 &config,
3075 &outputDesc->mDevice,
3076 String8(""),
3077 &outputDesc->mLatency,
3078 outputDesc->mFlags);
3079
3080 if (status != NO_ERROR) {
3081 ALOGW("Cannot open output stream for device %08x on hw module %s",
3082 outputDesc->mDevice,
3083 mHwModules[i]->mName);
3084 } else {
3085 outputDesc->mSamplingRate = config.sample_rate;
3086 outputDesc->mChannelMask = config.channel_mask;
3087 outputDesc->mFormat = config.format;
3088
3089 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3090 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3091 ssize_t index =
3092 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3093 // give a valid ID to an attached device once confirmed it is reachable
3094 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3095 mAvailableOutputDevices[index]->mId = nextUniqueId();
3096 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3097 }
3098 }
3099 if (mPrimaryOutput == 0 &&
3100 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3101 mPrimaryOutput = output;
3102 }
3103 addOutput(output, outputDesc);
3104 setOutputDevice(output,
3105 outputDesc->mDevice,
3106 true);
3107 }
Eric Laurente552edb2014-03-10 17:42:56 -07003108 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003109 // open input streams needed to access attached devices to validate
3110 // mAvailableInputDevices list
3111 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3112 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003113 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003114
Eric Laurent3a4311c2014-03-17 12:00:47 -07003115 if (inProfile->mSupportedDevices.isEmpty()) {
3116 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3117 continue;
3118 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003119 // chose first device present in mSupportedDevices also part of
3120 // inputDeviceTypes
3121 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3122 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3123 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3124 if (profileType & inputDeviceTypes) {
3125 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003126 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003127 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003128 if ((profileType & inputDeviceTypes) == 0) {
3129 continue;
3130 }
3131 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3132
3133 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3134 inputDesc->mDevice = profileType;
3135
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003136 // find the address
3137 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3138 // the inputs vector must be of size 1, but we don't want to crash here
3139 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3140 : String8("");
3141 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3142 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3143
Eric Laurentd78f1532014-09-16 16:38:20 -07003144 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3145 config.sample_rate = inputDesc->mSamplingRate;
3146 config.channel_mask = inputDesc->mChannelMask;
3147 config.format = inputDesc->mFormat;
3148 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3149 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3150 &input,
3151 &config,
3152 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003153 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003154 AUDIO_SOURCE_MIC,
3155 AUDIO_INPUT_FLAG_NONE);
3156
3157 if (status == NO_ERROR) {
3158 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3159 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3160 ssize_t index =
3161 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3162 // give a valid ID to an attached device once confirmed it is reachable
3163 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3164 mAvailableInputDevices[index]->mId = nextUniqueId();
3165 mAvailableInputDevices[index]->mModule = mHwModules[i];
3166 }
3167 }
3168 mpClientInterface->closeInput(input);
3169 } else {
3170 ALOGW("Cannot open input stream for device %08x on hw module %s",
3171 inputDesc->mDevice,
3172 mHwModules[i]->mName);
3173 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003174 }
3175 }
3176 // make sure all attached devices have been allocated a unique ID
3177 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3178 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003179 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003180 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3181 continue;
3182 }
3183 i++;
3184 }
3185 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3186 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003187 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003188 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3189 continue;
3190 }
3191 i++;
3192 }
3193 // make sure default device is reachable
3194 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003195 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003196 }
Eric Laurente552edb2014-03-10 17:42:56 -07003197
3198 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3199
3200 updateDevicesAndOutputs();
3201
3202#ifdef AUDIO_POLICY_TEST
3203 if (mPrimaryOutput != 0) {
3204 AudioParameter outputCmd = AudioParameter();
3205 outputCmd.addInt(String8("set_id"), 0);
3206 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3207
3208 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3209 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003210 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3211 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003212 mTestLatencyMs = 0;
3213 mCurOutput = 0;
3214 mDirectOutput = false;
3215 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3216 mTestOutputs[i] = 0;
3217 }
3218
3219 const size_t SIZE = 256;
3220 char buffer[SIZE];
3221 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3222 run(buffer, ANDROID_PRIORITY_AUDIO);
3223 }
3224#endif //AUDIO_POLICY_TEST
3225}
3226
Eric Laurente0720872014-03-11 09:30:41 -07003227AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003228{
3229#ifdef AUDIO_POLICY_TEST
3230 exit();
3231#endif //AUDIO_POLICY_TEST
3232 for (size_t i = 0; i < mOutputs.size(); i++) {
3233 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003234 }
3235 for (size_t i = 0; i < mInputs.size(); i++) {
3236 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003237 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003238 mAvailableOutputDevices.clear();
3239 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003240 mOutputs.clear();
3241 mInputs.clear();
3242 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003243}
3244
Eric Laurente0720872014-03-11 09:30:41 -07003245status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003246{
3247 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3248}
3249
3250#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003251bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003252{
3253 ALOGV("entering threadLoop()");
3254 while (!exitPending())
3255 {
3256 String8 command;
3257 int valueInt;
3258 String8 value;
3259
3260 Mutex::Autolock _l(mLock);
3261 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3262
3263 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3264 AudioParameter param = AudioParameter(command);
3265
3266 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3267 valueInt != 0) {
3268 ALOGV("Test command %s received", command.string());
3269 String8 target;
3270 if (param.get(String8("target"), target) != NO_ERROR) {
3271 target = "Manager";
3272 }
3273 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3274 param.remove(String8("test_cmd_policy_output"));
3275 mCurOutput = valueInt;
3276 }
3277 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3278 param.remove(String8("test_cmd_policy_direct"));
3279 if (value == "false") {
3280 mDirectOutput = false;
3281 } else if (value == "true") {
3282 mDirectOutput = true;
3283 }
3284 }
3285 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3286 param.remove(String8("test_cmd_policy_input"));
3287 mTestInput = valueInt;
3288 }
3289
3290 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3291 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003292 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003293 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003294 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003295 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003296 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003297 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003298 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003299 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003300 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003301 if (target == "Manager") {
3302 mTestFormat = format;
3303 } else if (mTestOutputs[mCurOutput] != 0) {
3304 AudioParameter outputParam = AudioParameter();
3305 outputParam.addInt(String8("format"), format);
3306 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3307 }
3308 }
3309 }
3310 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3311 param.remove(String8("test_cmd_policy_channels"));
3312 int channels = 0;
3313
3314 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003315 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003316 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003317 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003318 }
3319 if (channels != 0) {
3320 if (target == "Manager") {
3321 mTestChannels = channels;
3322 } else if (mTestOutputs[mCurOutput] != 0) {
3323 AudioParameter outputParam = AudioParameter();
3324 outputParam.addInt(String8("channels"), channels);
3325 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3326 }
3327 }
3328 }
3329 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3330 param.remove(String8("test_cmd_policy_sampleRate"));
3331 if (valueInt >= 0 && valueInt <= 96000) {
3332 int samplingRate = valueInt;
3333 if (target == "Manager") {
3334 mTestSamplingRate = samplingRate;
3335 } else if (mTestOutputs[mCurOutput] != 0) {
3336 AudioParameter outputParam = AudioParameter();
3337 outputParam.addInt(String8("sampling_rate"), samplingRate);
3338 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3339 }
3340 }
3341 }
3342
3343 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3344 param.remove(String8("test_cmd_policy_reopen"));
3345
Eric Laurent1f2f2232014-06-02 12:01:23 -07003346 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003347 mpClientInterface->closeOutput(mPrimaryOutput);
3348
3349 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3350
Eric Laurente552edb2014-03-10 17:42:56 -07003351 mOutputs.removeItem(mPrimaryOutput);
3352
Eric Laurent1f2f2232014-06-02 12:01:23 -07003353 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003354 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003355 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3356 config.sample_rate = outputDesc->mSamplingRate;
3357 config.channel_mask = outputDesc->mChannelMask;
3358 config.format = outputDesc->mFormat;
3359 status_t status = mpClientInterface->openOutput(moduleHandle,
3360 &mPrimaryOutput,
3361 &config,
3362 &outputDesc->mDevice,
3363 String8(""),
3364 &outputDesc->mLatency,
3365 outputDesc->mFlags);
3366 if (status != NO_ERROR) {
3367 ALOGE("Failed to reopen hardware output stream, "
3368 "samplingRate: %d, format %d, channels %d",
3369 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003370 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003371 outputDesc->mSamplingRate = config.sample_rate;
3372 outputDesc->mChannelMask = config.channel_mask;
3373 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003374 AudioParameter outputCmd = AudioParameter();
3375 outputCmd.addInt(String8("set_id"), 0);
3376 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3377 addOutput(mPrimaryOutput, outputDesc);
3378 }
3379 }
3380
3381
3382 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3383 }
3384 }
3385 return false;
3386}
3387
Eric Laurente0720872014-03-11 09:30:41 -07003388void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003389{
3390 {
3391 AutoMutex _l(mLock);
3392 requestExit();
3393 mWaitWorkCV.signal();
3394 }
3395 requestExitAndWait();
3396}
3397
Eric Laurente0720872014-03-11 09:30:41 -07003398int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003399{
3400 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3401 if (output == mTestOutputs[i]) return i;
3402 }
3403 return 0;
3404}
3405#endif //AUDIO_POLICY_TEST
3406
3407// ---
3408
Eric Laurent1f2f2232014-06-02 12:01:23 -07003409void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003410{
Eric Laurent1c333e22014-05-20 10:48:17 -07003411 outputDesc->mIoHandle = output;
3412 outputDesc->mId = nextUniqueId();
3413 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003414 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003415}
3416
Eric Laurent1f2f2232014-06-02 12:01:23 -07003417void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003418{
Eric Laurent1c333e22014-05-20 10:48:17 -07003419 inputDesc->mIoHandle = input;
3420 inputDesc->mId = nextUniqueId();
3421 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003422 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003423}
Eric Laurente552edb2014-03-10 17:42:56 -07003424
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003425void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3426 const String8 address /*in*/,
3427 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3428 // look for a match on the given address on the addresses of the outputs:
3429 // find the address by finding the patch that maps to this output
3430 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3431 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3432 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3433 if (patchIdx >= 0) {
3434 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3435 const int numSinks = patchDesc->mPatch.num_sinks;
3436 for (ssize_t j=0; j < numSinks; j++) {
3437 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3438 const char* patchAddr =
3439 patchDesc->mPatch.sinks[j].ext.device.address;
3440 if (strncmp(patchAddr,
3441 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003442 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003443 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3444 outputs.add(desc->mIoHandle);
3445 break;
3446 }
3447 }
3448 }
3449 }
3450}
3451
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003452status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003453 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003454 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003455 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003456{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003457 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003458 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003459 // erase all current sample rates, formats and channel masks
3460 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003461
Eric Laurent3b73df72014-03-11 09:06:29 -07003462 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003463 // first list already open outputs that can be routed to this device
3464 for (size_t i = 0; i < mOutputs.size(); i++) {
3465 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003466 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003467 if (!deviceDistinguishesOnAddress(device)) {
3468 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3469 outputs.add(mOutputs.keyAt(i));
3470 } else {
3471 ALOGV(" checking address match due to device 0x%x", device);
3472 findIoHandlesByAddress(desc, address, outputs);
3473 }
Eric Laurente552edb2014-03-10 17:42:56 -07003474 }
3475 }
3476 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003477 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003478 for (size_t i = 0; i < mHwModules.size(); i++)
3479 {
3480 if (mHwModules[i]->mHandle == 0) {
3481 continue;
3482 }
3483 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3484 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003485 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3486 if (profile->mSupportedDevices.types() & device) {
3487 if (!deviceDistinguishesOnAddress(device) ||
3488 address == profile->mSupportedDevices[0]->mAddress) {
3489 profiles.add(profile);
3490 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3491 }
Eric Laurente552edb2014-03-10 17:42:56 -07003492 }
3493 }
3494 }
3495
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003496 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3497
Eric Laurente552edb2014-03-10 17:42:56 -07003498 if (profiles.isEmpty() && outputs.isEmpty()) {
3499 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3500 return BAD_VALUE;
3501 }
3502
3503 // open outputs for matching profiles if needed. Direct outputs are also opened to
3504 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3505 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003506 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003507
3508 // nothing to do if one output is already opened for this profile
3509 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003510 for (j = 0; j < outputs.size(); j++) {
3511 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003512 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003513 // matching profile: save the sample rates, format and channel masks supported
3514 // by the profile in our device descriptor
3515 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003516 break;
3517 }
3518 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003519 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003520 continue;
3521 }
3522
Eric Laurent83b88082014-06-20 18:31:16 -07003523 ALOGV("opening output for device %08x with params %s profile %p",
3524 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003525 desc = new AudioOutputDescriptor(profile);
3526 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003527 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3528 config.sample_rate = desc->mSamplingRate;
3529 config.channel_mask = desc->mChannelMask;
3530 config.format = desc->mFormat;
3531 config.offload_info.sample_rate = desc->mSamplingRate;
3532 config.offload_info.channel_mask = desc->mChannelMask;
3533 config.offload_info.format = desc->mFormat;
3534 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3535 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3536 &output,
3537 &config,
3538 &desc->mDevice,
3539 address,
3540 &desc->mLatency,
3541 desc->mFlags);
3542 if (status == NO_ERROR) {
3543 desc->mSamplingRate = config.sample_rate;
3544 desc->mChannelMask = config.channel_mask;
3545 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003546
Eric Laurentd4692962014-05-05 18:13:44 -07003547 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003548 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003549 char *param = audio_device_address_to_parameter(device, address);
3550 mpClientInterface->setParameters(output, String8(param));
3551 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003552 }
3553
Eric Laurentd4692962014-05-05 18:13:44 -07003554 // Here is where we step through and resolve any "dynamic" fields
3555 String8 reply;
3556 char *value;
3557 if (profile->mSamplingRates[0] == 0) {
3558 reply = mpClientInterface->getParameters(output,
3559 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003560 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003561 reply.string());
3562 value = strpbrk((char *)reply.string(), "=");
3563 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003564 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003565 }
Eric Laurentd4692962014-05-05 18:13:44 -07003566 }
3567 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3568 reply = mpClientInterface->getParameters(output,
3569 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003570 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003571 reply.string());
3572 value = strpbrk((char *)reply.string(), "=");
3573 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003574 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003575 }
Eric Laurentd4692962014-05-05 18:13:44 -07003576 }
3577 if (profile->mChannelMasks[0] == 0) {
3578 reply = mpClientInterface->getParameters(output,
3579 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003580 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003581 reply.string());
3582 value = strpbrk((char *)reply.string(), "=");
3583 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003584 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003585 }
Eric Laurentd4692962014-05-05 18:13:44 -07003586 }
3587 if (((profile->mSamplingRates[0] == 0) &&
3588 (profile->mSamplingRates.size() < 2)) ||
3589 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3590 (profile->mFormats.size() < 2)) ||
3591 ((profile->mChannelMasks[0] == 0) &&
3592 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003593 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003594 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003595 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003596 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3597 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003598 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003599 config.sample_rate = profile->pickSamplingRate();
3600 config.channel_mask = profile->pickChannelMask();
3601 config.format = profile->pickFormat();
3602 config.offload_info.sample_rate = config.sample_rate;
3603 config.offload_info.channel_mask = config.channel_mask;
3604 config.offload_info.format = config.format;
3605 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3606 &output,
3607 &config,
3608 &desc->mDevice,
3609 address,
3610 &desc->mLatency,
3611 desc->mFlags);
3612 if (status == NO_ERROR) {
3613 desc->mSamplingRate = config.sample_rate;
3614 desc->mChannelMask = config.channel_mask;
3615 desc->mFormat = config.format;
3616 } else {
3617 output = AUDIO_IO_HANDLE_NONE;
3618 }
Eric Laurentd4692962014-05-05 18:13:44 -07003619 }
3620
Eric Laurentcf2c0212014-07-25 16:20:43 -07003621 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003622 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003623 if (deviceDistinguishesOnAddress(device) && address != "0") {
3624 ssize_t index = mPolicyMixes.indexOfKey(address);
3625 if (index >= 0) {
3626 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003627 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003628 } else {
3629 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3630 address.string());
3631 }
Eric Laurentc722f302014-12-10 11:21:49 -08003632 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3633 // no duplicated output for direct outputs and
3634 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003635 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003636
Eric Laurentd4692962014-05-05 18:13:44 -07003637 // set initial stream volume for device
3638 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003639
Eric Laurentd4692962014-05-05 18:13:44 -07003640 //TODO: configure audio effect output stage here
3641
3642 // open a duplicating output thread for the new output and the primary output
3643 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3644 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003645 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003646 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003647 sp<AudioOutputDescriptor> dupOutputDesc =
3648 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003649 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3650 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3651 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3652 dupOutputDesc->mFormat = desc->mFormat;
3653 dupOutputDesc->mChannelMask = desc->mChannelMask;
3654 dupOutputDesc->mLatency = desc->mLatency;
3655 addOutput(duplicatedOutput, dupOutputDesc);
3656 applyStreamVolumes(duplicatedOutput, device, 0, true);
3657 } else {
3658 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3659 mPrimaryOutput, output);
3660 mpClientInterface->closeOutput(output);
3661 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003662 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003663 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003664 }
Eric Laurente552edb2014-03-10 17:42:56 -07003665 }
3666 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003667 } else {
3668 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003669 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003670 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003671 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003672 profiles.removeAt(profile_index);
3673 profile_index--;
3674 } else {
3675 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003676 devDesc->importAudioPort(profile);
3677
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003678 if (deviceDistinguishesOnAddress(device)) {
3679 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3680 device, address.string());
3681 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3682 NULL/*patch handle*/, address.string());
3683 }
Eric Laurente552edb2014-03-10 17:42:56 -07003684 ALOGV("checkOutputsForDevice(): adding output %d", output);
3685 }
3686 }
3687
3688 if (profiles.isEmpty()) {
3689 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3690 return BAD_VALUE;
3691 }
Eric Laurentd4692962014-05-05 18:13:44 -07003692 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003693 // check if one opened output is not needed any more after disconnecting one device
3694 for (size_t i = 0; i < mOutputs.size(); i++) {
3695 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003696 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003697 // exact match on device
3698 if (deviceDistinguishesOnAddress(device) &&
3699 (desc->mProfile->mSupportedDevices.types() == device)) {
3700 findIoHandlesByAddress(desc, address, outputs);
3701 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003702 & mAvailableOutputDevices.types())) {
3703 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3704 mOutputs.keyAt(i));
3705 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003706 }
Eric Laurente552edb2014-03-10 17:42:56 -07003707 }
3708 }
Eric Laurentd4692962014-05-05 18:13:44 -07003709 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003710 for (size_t i = 0; i < mHwModules.size(); i++)
3711 {
3712 if (mHwModules[i]->mHandle == 0) {
3713 continue;
3714 }
3715 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3716 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003717 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003718 if (profile->mSupportedDevices.types() & device) {
3719 ALOGV("checkOutputsForDevice(): "
3720 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003721 if (profile->mSamplingRates[0] == 0) {
3722 profile->mSamplingRates.clear();
3723 profile->mSamplingRates.add(0);
3724 }
3725 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3726 profile->mFormats.clear();
3727 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3728 }
3729 if (profile->mChannelMasks[0] == 0) {
3730 profile->mChannelMasks.clear();
3731 profile->mChannelMasks.add(0);
3732 }
3733 }
3734 }
3735 }
3736 }
3737 return NO_ERROR;
3738}
3739
Eric Laurentd4692962014-05-05 18:13:44 -07003740status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3741 audio_policy_dev_state_t state,
3742 SortedVector<audio_io_handle_t>& inputs,
3743 const String8 address)
3744{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003745 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003746 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3747 // first list already open inputs that can be routed to this device
3748 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3749 desc = mInputs.valueAt(input_index);
3750 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3751 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3752 inputs.add(mInputs.keyAt(input_index));
3753 }
3754 }
3755
3756 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003757 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003758 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3759 {
3760 if (mHwModules[module_idx]->mHandle == 0) {
3761 continue;
3762 }
3763 for (size_t profile_index = 0;
3764 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3765 profile_index++)
3766 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003767 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3768
3769 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3770 if (!deviceDistinguishesOnAddress(device) ||
3771 address == profile->mSupportedDevices[0]->mAddress) {
3772 profiles.add(profile);
3773 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3774 profile_index, module_idx);
3775 }
Eric Laurentd4692962014-05-05 18:13:44 -07003776 }
3777 }
3778 }
3779
3780 if (profiles.isEmpty() && inputs.isEmpty()) {
3781 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3782 return BAD_VALUE;
3783 }
3784
3785 // open inputs for matching profiles if needed. Direct inputs are also opened to
3786 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3787 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3788
Eric Laurent1c333e22014-05-20 10:48:17 -07003789 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003790 // nothing to do if one input is already opened for this profile
3791 size_t input_index;
3792 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3793 desc = mInputs.valueAt(input_index);
3794 if (desc->mProfile == profile) {
3795 break;
3796 }
3797 }
3798 if (input_index != mInputs.size()) {
3799 continue;
3800 }
3801
3802 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3803 desc = new AudioInputDescriptor(profile);
3804 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003805 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3806 config.sample_rate = desc->mSamplingRate;
3807 config.channel_mask = desc->mChannelMask;
3808 config.format = desc->mFormat;
3809 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3810 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3811 &input,
3812 &config,
3813 &desc->mDevice,
3814 address,
3815 AUDIO_SOURCE_MIC,
3816 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003817
Eric Laurentcf2c0212014-07-25 16:20:43 -07003818 if (status == NO_ERROR) {
3819 desc->mSamplingRate = config.sample_rate;
3820 desc->mChannelMask = config.channel_mask;
3821 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003822
Eric Laurentd4692962014-05-05 18:13:44 -07003823 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003824 char *param = audio_device_address_to_parameter(device, address);
3825 mpClientInterface->setParameters(input, String8(param));
3826 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003827 }
3828
3829 // Here is where we step through and resolve any "dynamic" fields
3830 String8 reply;
3831 char *value;
3832 if (profile->mSamplingRates[0] == 0) {
3833 reply = mpClientInterface->getParameters(input,
3834 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3835 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3836 reply.string());
3837 value = strpbrk((char *)reply.string(), "=");
3838 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003839 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003840 }
3841 }
3842 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3843 reply = mpClientInterface->getParameters(input,
3844 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3845 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3846 value = strpbrk((char *)reply.string(), "=");
3847 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003848 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003849 }
3850 }
3851 if (profile->mChannelMasks[0] == 0) {
3852 reply = mpClientInterface->getParameters(input,
3853 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3854 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3855 reply.string());
3856 value = strpbrk((char *)reply.string(), "=");
3857 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003858 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003859 }
3860 }
3861 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3862 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3863 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3864 ALOGW("checkInputsForDevice() direct input missing param");
3865 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003866 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003867 }
3868
3869 if (input != 0) {
3870 addInput(input, desc);
3871 }
3872 } // endif input != 0
3873
Eric Laurentcf2c0212014-07-25 16:20:43 -07003874 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003875 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003876 profiles.removeAt(profile_index);
3877 profile_index--;
3878 } else {
3879 inputs.add(input);
3880 ALOGV("checkInputsForDevice(): adding input %d", input);
3881 }
3882 } // end scan profiles
3883
3884 if (profiles.isEmpty()) {
3885 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3886 return BAD_VALUE;
3887 }
3888 } else {
3889 // Disconnect
3890 // check if one opened input is not needed any more after disconnecting one device
3891 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3892 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003893 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3894 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003895 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3896 mInputs.keyAt(input_index));
3897 inputs.add(mInputs.keyAt(input_index));
3898 }
3899 }
3900 // Clear any profiles associated with the disconnected device.
3901 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3902 if (mHwModules[module_index]->mHandle == 0) {
3903 continue;
3904 }
3905 for (size_t profile_index = 0;
3906 profile_index < mHwModules[module_index]->mInputProfiles.size();
3907 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003908 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003909 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003910 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003911 profile_index, module_index);
3912 if (profile->mSamplingRates[0] == 0) {
3913 profile->mSamplingRates.clear();
3914 profile->mSamplingRates.add(0);
3915 }
3916 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3917 profile->mFormats.clear();
3918 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3919 }
3920 if (profile->mChannelMasks[0] == 0) {
3921 profile->mChannelMasks.clear();
3922 profile->mChannelMasks.add(0);
3923 }
3924 }
3925 }
3926 }
3927 } // end disconnect
3928
3929 return NO_ERROR;
3930}
3931
3932
Eric Laurente0720872014-03-11 09:30:41 -07003933void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003934{
3935 ALOGV("closeOutput(%d)", output);
3936
Eric Laurent1f2f2232014-06-02 12:01:23 -07003937 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003938 if (outputDesc == NULL) {
3939 ALOGW("closeOutput() unknown output %d", output);
3940 return;
3941 }
3942
Eric Laurent275e8e92014-11-30 15:14:47 -08003943 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3944 if (mPolicyMixes[i]->mOutput == outputDesc) {
3945 mPolicyMixes[i]->mOutput.clear();
3946 }
3947 }
3948
Eric Laurente552edb2014-03-10 17:42:56 -07003949 // look for duplicated outputs connected to the output being removed.
3950 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003951 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003952 if (dupOutputDesc->isDuplicated() &&
3953 (dupOutputDesc->mOutput1 == outputDesc ||
3954 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003955 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003956 if (dupOutputDesc->mOutput1 == outputDesc) {
3957 outputDesc2 = dupOutputDesc->mOutput2;
3958 } else {
3959 outputDesc2 = dupOutputDesc->mOutput1;
3960 }
3961 // As all active tracks on duplicated output will be deleted,
3962 // and as they were also referenced on the other output, the reference
3963 // count for their stream type must be adjusted accordingly on
3964 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003965 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003966 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003967 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003968 }
3969 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3970 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3971
3972 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003973 mOutputs.removeItem(duplicatedOutput);
3974 }
3975 }
3976
Eric Laurent05b90f82014-08-27 15:32:29 -07003977 nextAudioPortGeneration();
3978
3979 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3980 if (index >= 0) {
3981 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3982 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3983 mAudioPatches.removeItemsAt(index);
3984 mpClientInterface->onAudioPatchListUpdate();
3985 }
3986
Eric Laurente552edb2014-03-10 17:42:56 -07003987 AudioParameter param;
3988 param.add(String8("closing"), String8("true"));
3989 mpClientInterface->setParameters(output, param.toString());
3990
3991 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003992 mOutputs.removeItem(output);
3993 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003994}
3995
3996void AudioPolicyManager::closeInput(audio_io_handle_t input)
3997{
3998 ALOGV("closeInput(%d)", input);
3999
4000 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4001 if (inputDesc == NULL) {
4002 ALOGW("closeInput() unknown input %d", input);
4003 return;
4004 }
4005
Eric Laurent6a94d692014-05-20 11:18:06 -07004006 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004007
4008 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4009 if (index >= 0) {
4010 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4011 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4012 mAudioPatches.removeItemsAt(index);
4013 mpClientInterface->onAudioPatchListUpdate();
4014 }
4015
4016 mpClientInterface->closeInput(input);
4017 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004018}
4019
Eric Laurente0720872014-03-11 09:30:41 -07004020SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004021 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004022{
4023 SortedVector<audio_io_handle_t> outputs;
4024
4025 ALOGVV("getOutputsForDevice() device %04x", device);
4026 for (size_t i = 0; i < openOutputs.size(); i++) {
4027 ALOGVV("output %d isDuplicated=%d device=%04x",
4028 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4029 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4030 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4031 outputs.add(openOutputs.keyAt(i));
4032 }
4033 }
4034 return outputs;
4035}
4036
Eric Laurente0720872014-03-11 09:30:41 -07004037bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004038 SortedVector<audio_io_handle_t>& outputs2)
4039{
4040 if (outputs1.size() != outputs2.size()) {
4041 return false;
4042 }
4043 for (size_t i = 0; i < outputs1.size(); i++) {
4044 if (outputs1[i] != outputs2[i]) {
4045 return false;
4046 }
4047 }
4048 return true;
4049}
4050
Eric Laurente0720872014-03-11 09:30:41 -07004051void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004052{
4053 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4054 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4055 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4056 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4057
4058 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4059 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4060 strategy, srcOutputs[0], dstOutputs[0]);
4061 // mute strategy while moving tracks from one output to another
4062 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004063 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004064 if (desc->isStrategyActive(strategy)) {
4065 setStrategyMute(strategy, true, srcOutputs[i]);
4066 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4067 }
4068 }
4069
4070 // Move effects associated to this strategy from previous output to new output
4071 if (strategy == STRATEGY_MEDIA) {
4072 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4073 SortedVector<audio_io_handle_t> moved;
4074 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004075 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4076 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4077 effectDesc->mIo != fxOutput) {
4078 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004079 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4080 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004081 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004082 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004083 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004084 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004085 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004086 }
4087 }
4088 }
4089 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004090 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004091 if (i == AUDIO_STREAM_PATCH) {
4092 continue;
4093 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004094 if (getStrategy((audio_stream_type_t)i) == strategy) {
4095 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004096 }
4097 }
4098 }
4099}
4100
Eric Laurente0720872014-03-11 09:30:41 -07004101void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004102{
Jon Eklund966095e2014-09-09 15:39:49 -05004103 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4104 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004105 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004106 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4107 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004108 checkOutputForStrategy(STRATEGY_SONIFICATION);
4109 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004110 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004111 checkOutputForStrategy(STRATEGY_MEDIA);
4112 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004113 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004114}
4115
Eric Laurente0720872014-03-11 09:30:41 -07004116audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004117{
Eric Laurente552edb2014-03-10 17:42:56 -07004118 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004119 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004120 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4121 return mOutputs.keyAt(i);
4122 }
4123 }
4124
4125 return 0;
4126}
4127
Eric Laurente0720872014-03-11 09:30:41 -07004128void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004129{
Eric Laurente552edb2014-03-10 17:42:56 -07004130 audio_io_handle_t a2dpOutput = getA2dpOutput();
4131 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004132 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004133 return;
4134 }
4135
Eric Laurent3a4311c2014-03-17 12:00:47 -07004136 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004137 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4138 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4139 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004140 // suspend A2DP output if:
4141 // (NOT already suspended) &&
4142 // ((SCO device is connected &&
4143 // (forced usage for communication || for record is SCO))) ||
4144 // (phone state is ringing || in call)
4145 //
4146 // restore A2DP output if:
4147 // (Already suspended) &&
4148 // ((SCO device is NOT connected ||
4149 // (forced usage NOT for communication && NOT for record is SCO))) &&
4150 // (phone state is NOT ringing && NOT in call)
4151 //
4152 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004153 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004154 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4155 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4156 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4157 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004158
4159 mpClientInterface->restoreOutput(a2dpOutput);
4160 mA2dpSuspended = false;
4161 }
4162 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004163 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004164 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4165 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4166 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4167 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004168
4169 mpClientInterface->suspendOutput(a2dpOutput);
4170 mA2dpSuspended = true;
4171 }
4172 }
4173}
4174
Eric Laurent1c333e22014-05-20 10:48:17 -07004175audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004176{
4177 audio_devices_t device = AUDIO_DEVICE_NONE;
4178
Eric Laurent1f2f2232014-06-02 12:01:23 -07004179 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004180
4181 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4182 if (index >= 0) {
4183 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4184 if (patchDesc->mUid != mUidCached) {
4185 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4186 outputDesc->device(), outputDesc->mPatchHandle);
4187 return outputDesc->device();
4188 }
4189 }
4190
Eric Laurente552edb2014-03-10 17:42:56 -07004191 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004192 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004193 // use device for strategy enforced audible
4194 // 2: we are in call or the strategy phone is active on the output:
4195 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004196 // 3: the strategy for enforced audible is active but not enforced on the output:
4197 // use the device for strategy enforced audible
4198 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004199 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004200 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004201 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004202 // 6: the strategy accessibility is active on the output:
4203 // use device for strategy accessibility
4204 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004205 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004206 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004207 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004208 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004209 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004210 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4211 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004212 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4213 } else if (isInCall() ||
4214 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4215 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004216 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4217 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004218 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4219 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4220 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4221 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004222 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4223 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004224 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4225 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4226 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4227 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004228 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4229 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004230 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4231 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004232 }
4233
Eric Laurent1c333e22014-05-20 10:48:17 -07004234 ALOGV("getNewOutputDevice() selected device %x", device);
4235 return device;
4236}
4237
4238audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4239{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004240 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004241
4242 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4243 if (index >= 0) {
4244 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4245 if (patchDesc->mUid != mUidCached) {
4246 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4247 inputDesc->mDevice, inputDesc->mPatchHandle);
4248 return inputDesc->mDevice;
4249 }
4250 }
4251
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004252 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004253
4254 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004255 return device;
4256}
4257
Eric Laurente0720872014-03-11 09:30:41 -07004258uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004259 return (uint32_t)getStrategy(stream);
4260}
4261
Eric Laurente0720872014-03-11 09:30:41 -07004262audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004263 // By checking the range of stream before calling getStrategy, we avoid
4264 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4265 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004266 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004267 return AUDIO_DEVICE_NONE;
4268 }
4269 audio_devices_t devices;
4270 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4271 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4272 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4273 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004274 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004275 if (outputDesc->isStrategyActive(strategy)) {
4276 devices = outputDesc->device();
4277 break;
4278 }
Eric Laurente552edb2014-03-10 17:42:56 -07004279 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004280
4281 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4282 and doesn't really need to.*/
4283 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4284 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4285 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4286 }
4287
Eric Laurente552edb2014-03-10 17:42:56 -07004288 return devices;
4289}
4290
Eric Laurente0720872014-03-11 09:30:41 -07004291AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004292 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004293
4294 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4295
Eric Laurente552edb2014-03-10 17:42:56 -07004296 // stream to strategy mapping
4297 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004298 case AUDIO_STREAM_VOICE_CALL:
4299 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004300 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004301 case AUDIO_STREAM_RING:
4302 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004303 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004304 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004305 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004306 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004307 return STRATEGY_DTMF;
4308 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004309 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004310 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004311 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4312 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004313 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004314 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004315 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004316 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004317 case AUDIO_STREAM_TTS:
4318 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004319 case AUDIO_STREAM_ACCESSIBILITY:
4320 return STRATEGY_ACCESSIBILITY;
4321 case AUDIO_STREAM_REROUTING:
4322 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004323 }
4324}
4325
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004326uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4327 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004328 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4329 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4330 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004331 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4332 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4333 }
4334
4335 // usage to strategy mapping
4336 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004337 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4338 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4339 return (uint32_t) STRATEGY_SONIFICATION;
4340 }
4341 if (isInCall()) {
4342 return (uint32_t) STRATEGY_PHONE;
4343 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004344 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004345
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004346 case AUDIO_USAGE_MEDIA:
4347 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004348 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4349 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4350 return (uint32_t) STRATEGY_MEDIA;
4351
4352 case AUDIO_USAGE_VOICE_COMMUNICATION:
4353 return (uint32_t) STRATEGY_PHONE;
4354
4355 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4356 return (uint32_t) STRATEGY_DTMF;
4357
4358 case AUDIO_USAGE_ALARM:
4359 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4360 return (uint32_t) STRATEGY_SONIFICATION;
4361
4362 case AUDIO_USAGE_NOTIFICATION:
4363 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4364 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4365 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4366 case AUDIO_USAGE_NOTIFICATION_EVENT:
4367 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4368
4369 case AUDIO_USAGE_UNKNOWN:
4370 default:
4371 return (uint32_t) STRATEGY_MEDIA;
4372 }
4373}
4374
Eric Laurente0720872014-03-11 09:30:41 -07004375void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004376 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004377 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004378 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4379 updateDevicesAndOutputs();
4380 break;
4381 default:
4382 break;
4383 }
4384}
4385
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004386bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4387 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4388 if (s == (size_t) streamToIgnore) {
4389 continue;
4390 }
4391 for (size_t i = 0; i < mOutputs.size(); i++) {
4392 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4393 if (outputDesc->mRefCount[s] != 0) {
4394 return true;
4395 }
4396 }
4397 }
4398 return false;
4399}
4400
4401uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4402 switch(event) {
4403 case STARTING_OUTPUT:
4404 mBeaconMuteRefCount++;
4405 break;
4406 case STOPPING_OUTPUT:
4407 if (mBeaconMuteRefCount > 0) {
4408 mBeaconMuteRefCount--;
4409 }
4410 break;
4411 case STARTING_BEACON:
4412 mBeaconPlayingRefCount++;
4413 break;
4414 case STOPPING_BEACON:
4415 if (mBeaconPlayingRefCount > 0) {
4416 mBeaconPlayingRefCount--;
4417 }
4418 break;
4419 }
4420
4421 if (mBeaconMuteRefCount > 0) {
4422 // any playback causes beacon to be muted
4423 return setBeaconMute(true);
4424 } else {
4425 // no other playback: unmute when beacon starts playing, mute when it stops
4426 return setBeaconMute(mBeaconPlayingRefCount == 0);
4427 }
4428}
4429
4430uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4431 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4432 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4433 // keep track of muted state to avoid repeating mute/unmute operations
4434 if (mBeaconMuted != mute) {
4435 // mute/unmute AUDIO_STREAM_TTS on all outputs
4436 ALOGV("\t muting %d", mute);
4437 uint32_t maxLatency = 0;
4438 for (size_t i = 0; i < mOutputs.size(); i++) {
4439 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4440 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4441 desc->mIoHandle,
4442 0 /*delay*/, AUDIO_DEVICE_NONE);
4443 const uint32_t latency = desc->latency() * 2;
4444 if (latency > maxLatency) {
4445 maxLatency = latency;
4446 }
4447 }
4448 mBeaconMuted = mute;
4449 return maxLatency;
4450 }
4451 return 0;
4452}
4453
Eric Laurente0720872014-03-11 09:30:41 -07004454audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004455 bool fromCache)
4456{
4457 uint32_t device = AUDIO_DEVICE_NONE;
4458
4459 if (fromCache) {
4460 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4461 strategy, mDeviceForStrategy[strategy]);
4462 return mDeviceForStrategy[strategy];
4463 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004464 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004465 switch (strategy) {
4466
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004467 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4468 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4469 if (!device) {
4470 ALOGE("getDeviceForStrategy() no device found for "\
4471 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4472 }
4473 break;
4474
Eric Laurente552edb2014-03-10 17:42:56 -07004475 case STRATEGY_SONIFICATION_RESPECTFUL:
4476 if (isInCall()) {
4477 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004478 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004479 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4480 // while media is playing on a remote device, use the the sonification behavior.
4481 // Note that we test this usecase before testing if media is playing because
4482 // the isStreamActive() method only informs about the activity of a stream, not
4483 // if it's for local playback. Note also that we use the same delay between both tests
4484 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004485 //user "safe" speaker if available instead of normal speaker to avoid triggering
4486 //other acoustic safety mechanisms for notification
4487 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4488 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004489 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004490 // while media is playing (or has recently played), use the same device
4491 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4492 } else {
4493 // when media is not playing anymore, fall back on the sonification behavior
4494 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004495 //user "safe" speaker if available instead of normal speaker to avoid triggering
4496 //other acoustic safety mechanisms for notification
4497 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4498 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004499 }
4500
4501 break;
4502
4503 case STRATEGY_DTMF:
4504 if (!isInCall()) {
4505 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4506 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4507 break;
4508 }
4509 // when in call, DTMF and PHONE strategies follow the same rules
4510 // FALL THROUGH
4511
4512 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004513 // Force use of only devices on primary output if:
4514 // - in call AND
4515 // - cannot route from voice call RX OR
4516 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4517 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004518 audio_devices_t txDevice =
4519 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004520 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4521 if (((mAvailableInputDevices.types() &
4522 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4523 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004524 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004525 AUDIO_DEVICE_API_VERSION_3_0))) {
4526 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4527 }
4528 }
Eric Laurente552edb2014-03-10 17:42:56 -07004529 // for phone strategy, we first consider the forced use and then the available devices by order
4530 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004531 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4532 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004533 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004534 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004535 if (device) break;
4536 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004537 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004538 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004539 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004540 if (device) break;
4541 // if SCO device is requested but no SCO device is available, fall back to default case
4542 // FALL THROUGH
4543
4544 default: // FORCE_NONE
4545 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004546 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004547 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004548 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004549 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004550 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004551 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004552 if (device) break;
4553 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004554 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004555 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004556 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004557 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004558 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4559 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004560 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004561 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004562 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004563 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004564 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004565 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004566 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004567 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004568 if (device) break;
4569 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004570 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004571 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004572 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004573 if (device == AUDIO_DEVICE_NONE) {
4574 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4575 }
4576 break;
4577
Eric Laurent3b73df72014-03-11 09:06:29 -07004578 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004579 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4580 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004581 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004582 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004583 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004584 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004585 if (device) break;
4586 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004587 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004588 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004589 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004590 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004591 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004592 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004593 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004594 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004595 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004596 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004597 if (device) break;
4598 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004599 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4600 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004601 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004602 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004603 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004604 if (device == AUDIO_DEVICE_NONE) {
4605 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4606 }
4607 break;
4608 }
4609 break;
4610
4611 case STRATEGY_SONIFICATION:
4612
4613 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4614 // handleIncallSonification().
4615 if (isInCall()) {
4616 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4617 break;
4618 }
4619 // FALL THROUGH
4620
4621 case STRATEGY_ENFORCED_AUDIBLE:
4622 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4623 // except:
4624 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4625 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4626
4627 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004628 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004629 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004630 if (device == AUDIO_DEVICE_NONE) {
4631 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4632 }
4633 }
4634 // The second device used for sonification is the same as the device used by media strategy
4635 // FALL THROUGH
4636
Eric Laurent223fd5c2014-11-11 13:43:36 -08004637 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4638 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004639 if (strategy == STRATEGY_ACCESSIBILITY) {
4640 // do not route accessibility prompts to a digital output currently configured with a
4641 // compressed format as they would likely not be mixed and dropped.
4642 for (size_t i = 0; i < mOutputs.size(); i++) {
4643 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4644 audio_devices_t devices = desc->device() &
4645 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4646 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4647 devices != AUDIO_DEVICE_NONE) {
4648 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4649 }
4650 }
4651 }
4652 // FALL THROUGH
4653
Eric Laurent223fd5c2014-11-11 13:43:36 -08004654 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004655 case STRATEGY_MEDIA: {
4656 uint32_t device2 = AUDIO_DEVICE_NONE;
4657 if (strategy != STRATEGY_SONIFICATION) {
4658 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004659 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4660 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4661 }
Eric Laurente552edb2014-03-10 17:42:56 -07004662 }
4663 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004664 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004665 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004666 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004667 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004668 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004669 }
4670 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004671 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004672 }
4673 }
Hochi Huang327cb702014-09-21 09:47:31 +08004674 if ((device2 == AUDIO_DEVICE_NONE) &&
4675 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4676 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4677 }
Eric Laurente552edb2014-03-10 17:42:56 -07004678 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004679 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004680 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004681 if ((device2 == AUDIO_DEVICE_NONE)) {
4682 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4683 }
Eric Laurente552edb2014-03-10 17:42:56 -07004684 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004685 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004686 }
4687 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004688 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004689 }
4690 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004691 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004692 }
4693 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004694 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004695 }
4696 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4697 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004698 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004699 }
4700 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004701 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004702 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004703 }
4704 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004705 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004706 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004707 int device3 = AUDIO_DEVICE_NONE;
4708 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004709 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004710 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4711 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004712 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004713 }
Eric Laurente552edb2014-03-10 17:42:56 -07004714
Jungshik Jang839e4f32014-06-26 17:23:40 +09004715 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004716 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4717 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4718 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004719
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004720 // If hdmi system audio mode is on, remove speaker out of output list.
4721 if ((strategy == STRATEGY_MEDIA) &&
4722 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4723 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4724 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4725 }
4726
Eric Laurente552edb2014-03-10 17:42:56 -07004727 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004728 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004729 if (device == AUDIO_DEVICE_NONE) {
4730 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4731 }
4732 } break;
4733
4734 default:
4735 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4736 break;
4737 }
4738
4739 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4740 return device;
4741}
4742
Eric Laurente0720872014-03-11 09:30:41 -07004743void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004744{
4745 for (int i = 0; i < NUM_STRATEGIES; i++) {
4746 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4747 }
4748 mPreviousOutputs = mOutputs;
4749}
4750
Eric Laurent1f2f2232014-06-02 12:01:23 -07004751uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004752 audio_devices_t prevDevice,
4753 uint32_t delayMs)
4754{
4755 // mute/unmute strategies using an incompatible device combination
4756 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4757 // if unmuting, unmute only after the specified delay
4758 if (outputDesc->isDuplicated()) {
4759 return 0;
4760 }
4761
4762 uint32_t muteWaitMs = 0;
4763 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004764 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004765
4766 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4767 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004768 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004769 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4770 bool doMute = false;
4771
4772 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4773 doMute = true;
4774 outputDesc->mStrategyMutedByDevice[i] = true;
4775 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4776 doMute = true;
4777 outputDesc->mStrategyMutedByDevice[i] = false;
4778 }
Eric Laurent99401132014-05-07 19:48:15 -07004779 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004780 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004781 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004782 // skip output if it does not share any device with current output
4783 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4784 == AUDIO_DEVICE_NONE) {
4785 continue;
4786 }
4787 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4788 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4789 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4790 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4791 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004792 if (mute) {
4793 // FIXME: should not need to double latency if volume could be applied
4794 // immediately by the audioflinger mixer. We must account for the delay
4795 // between now and the next time the audioflinger thread for this output
4796 // will process a buffer (which corresponds to one buffer size,
4797 // usually 1/2 or 1/4 of the latency).
4798 if (muteWaitMs < desc->latency() * 2) {
4799 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004800 }
4801 }
4802 }
4803 }
4804 }
4805 }
4806
Eric Laurent99401132014-05-07 19:48:15 -07004807 // temporary mute output if device selection changes to avoid volume bursts due to
4808 // different per device volumes
4809 if (outputDesc->isActive() && (device != prevDevice)) {
4810 if (muteWaitMs < outputDesc->latency() * 2) {
4811 muteWaitMs = outputDesc->latency() * 2;
4812 }
4813 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4814 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004815 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004816 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004817 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004818 muteWaitMs *2, device);
4819 }
4820 }
4821 }
4822
Eric Laurente552edb2014-03-10 17:42:56 -07004823 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4824 if (muteWaitMs > delayMs) {
4825 muteWaitMs -= delayMs;
4826 usleep(muteWaitMs * 1000);
4827 return muteWaitMs;
4828 }
4829 return 0;
4830}
4831
Eric Laurente0720872014-03-11 09:30:41 -07004832uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004833 audio_devices_t device,
4834 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004835 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004836 audio_patch_handle_t *patchHandle,
4837 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004838{
4839 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004840 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004841 AudioParameter param;
4842 uint32_t muteWaitMs;
4843
4844 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004845 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4846 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004847 return muteWaitMs;
4848 }
4849 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4850 // output profile
4851 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004852 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004853 return 0;
4854 }
4855
4856 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004857 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004858
4859 audio_devices_t prevDevice = outputDesc->mDevice;
4860
4861 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4862
4863 if (device != AUDIO_DEVICE_NONE) {
4864 outputDesc->mDevice = device;
4865 }
4866 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4867
4868 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004869 // the requested device is AUDIO_DEVICE_NONE
4870 // OR the requested device is the same as current device
4871 // AND force is not specified
4872 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004873 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004874 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4875 outputDesc->mPatchHandle != 0) {
4876 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4877 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004878 return muteWaitMs;
4879 }
4880
4881 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004882
Eric Laurente552edb2014-03-10 17:42:56 -07004883 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004884 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004886 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004887 DeviceVector deviceList = (address == NULL) ?
4888 mAvailableOutputDevices.getDevicesFromType(device)
4889 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004890 if (!deviceList.isEmpty()) {
4891 struct audio_patch patch;
4892 outputDesc->toAudioPortConfig(&patch.sources[0]);
4893 patch.num_sources = 1;
4894 patch.num_sinks = 0;
4895 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4896 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004897 patch.num_sinks++;
4898 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 ssize_t index;
4900 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4901 index = mAudioPatches.indexOfKey(*patchHandle);
4902 } else {
4903 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4904 }
4905 sp< AudioPatch> patchDesc;
4906 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4907 if (index >= 0) {
4908 patchDesc = mAudioPatches.valueAt(index);
4909 afPatchHandle = patchDesc->mAfPatchHandle;
4910 }
4911
Eric Laurent1c333e22014-05-20 10:48:17 -07004912 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 &afPatchHandle,
4914 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004915 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4916 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004917 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004918 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004919 if (index < 0) {
4920 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4921 &patch, mUidCached);
4922 addAudioPatch(patchDesc->mHandle, patchDesc);
4923 } else {
4924 patchDesc->mPatch = patch;
4925 }
4926 patchDesc->mAfPatchHandle = afPatchHandle;
4927 patchDesc->mUid = mUidCached;
4928 if (patchHandle) {
4929 *patchHandle = patchDesc->mHandle;
4930 }
4931 outputDesc->mPatchHandle = patchDesc->mHandle;
4932 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004933 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004934 }
4935 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004936
4937 // inform all input as well
4938 for (size_t i = 0; i < mInputs.size(); i++) {
4939 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4940 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4941 AudioParameter inputCmd = AudioParameter();
4942 ALOGV("%s: inform input %d of device:%d", __func__,
4943 inputDescriptor->mIoHandle, device);
4944 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4945 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4946 inputCmd.toString(),
4947 delayMs);
4948 }
4949 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004950 }
Eric Laurente552edb2014-03-10 17:42:56 -07004951
4952 // update stream volumes according to new device
4953 applyStreamVolumes(output, device, delayMs);
4954
4955 return muteWaitMs;
4956}
4957
Eric Laurent1c333e22014-05-20 10:48:17 -07004958status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 int delayMs,
4960 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004961{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004962 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 ssize_t index;
4964 if (patchHandle) {
4965 index = mAudioPatches.indexOfKey(*patchHandle);
4966 } else {
4967 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4968 }
4969 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004970 return INVALID_OPERATION;
4971 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4973 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004974 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4975 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 removeAudioPatch(patchDesc->mHandle);
4977 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004978 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004979 return status;
4980}
4981
4982status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4983 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 bool force,
4985 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004986{
4987 status_t status = NO_ERROR;
4988
Eric Laurent1f2f2232014-06-02 12:01:23 -07004989 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004990 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4991 inputDesc->mDevice = device;
4992
4993 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4994 if (!deviceList.isEmpty()) {
4995 struct audio_patch patch;
4996 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004997 // AUDIO_SOURCE_HOTWORD is for internal use only:
4998 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004999 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5000 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005001 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5002 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005003 patch.num_sinks = 1;
5004 //only one input device for now
5005 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005006 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 ssize_t index;
5008 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5009 index = mAudioPatches.indexOfKey(*patchHandle);
5010 } else {
5011 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5012 }
5013 sp< AudioPatch> patchDesc;
5014 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5015 if (index >= 0) {
5016 patchDesc = mAudioPatches.valueAt(index);
5017 afPatchHandle = patchDesc->mAfPatchHandle;
5018 }
5019
Eric Laurent1c333e22014-05-20 10:48:17 -07005020 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005022 0);
5023 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005025 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005026 if (index < 0) {
5027 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5028 &patch, mUidCached);
5029 addAudioPatch(patchDesc->mHandle, patchDesc);
5030 } else {
5031 patchDesc->mPatch = patch;
5032 }
5033 patchDesc->mAfPatchHandle = afPatchHandle;
5034 patchDesc->mUid = mUidCached;
5035 if (patchHandle) {
5036 *patchHandle = patchDesc->mHandle;
5037 }
5038 inputDesc->mPatchHandle = patchDesc->mHandle;
5039 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005040 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005041 }
5042 }
5043 }
5044 return status;
5045}
5046
Eric Laurent6a94d692014-05-20 11:18:06 -07005047status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5048 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005049{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005050 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 ssize_t index;
5052 if (patchHandle) {
5053 index = mAudioPatches.indexOfKey(*patchHandle);
5054 } else {
5055 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5056 }
5057 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005058 return INVALID_OPERATION;
5059 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5061 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005062 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5063 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 removeAudioPatch(patchDesc->mHandle);
5065 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005066 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005067 return status;
5068}
5069
5070sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005071 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005072 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005073 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005074 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005075 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005076{
5077 // Choose an input profile based on the requested capture parameters: select the first available
5078 // profile supporting all requested parameters.
5079
5080 for (size_t i = 0; i < mHwModules.size(); i++)
5081 {
5082 if (mHwModules[i]->mHandle == 0) {
5083 continue;
5084 }
5085 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5086 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005087 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005088 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005089 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005090 &samplingRate /*updatedSamplingRate*/,
5091 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005092
Eric Laurente552edb2014-03-10 17:42:56 -07005093 return profile;
5094 }
5095 }
5096 }
5097 return NULL;
5098}
5099
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005100
5101audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005102 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005103{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005104 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5105 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005106
5107 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5108 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5109 continue;
5110 }
5111 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5112 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5113 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5114 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5115 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5116 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005117 if (policyMix != NULL) {
5118 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005119 }
5120 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5121 }
5122 break;
5123 }
5124 }
5125 }
5126
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005127 return getDeviceForInputSource(inputSource);
5128}
5129
5130audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5131{
5132 uint32_t device = AUDIO_DEVICE_NONE;
5133 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5134 ~AUDIO_DEVICE_BIT_IN;
5135
Eric Laurente552edb2014-03-10 17:42:56 -07005136 switch (inputSource) {
5137 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005138 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005139 device = AUDIO_DEVICE_IN_VOICE_CALL;
5140 break;
5141 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005142 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005143
5144 case AUDIO_SOURCE_DEFAULT:
5145 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005146 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5147 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005148 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5149 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5150 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5151 device = AUDIO_DEVICE_IN_USB_DEVICE;
5152 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5153 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005154 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005155 break;
5156
5157 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5158 // Allow only use of devices on primary input if in call and HAL does not support routing
5159 // to voice call path.
5160 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5161 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5162 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5163 }
5164
5165 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5166 case AUDIO_POLICY_FORCE_BT_SCO:
5167 // if SCO device is requested but no SCO device is available, fall back to default case
5168 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5169 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5170 break;
5171 }
5172 // FALL THROUGH
5173
5174 default: // FORCE_NONE
5175 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5176 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5177 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5178 device = AUDIO_DEVICE_IN_USB_DEVICE;
5179 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5180 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5181 }
5182 break;
5183
5184 case AUDIO_POLICY_FORCE_SPEAKER:
5185 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5186 device = AUDIO_DEVICE_IN_BACK_MIC;
5187 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5188 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5189 }
5190 break;
5191 }
5192 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005193
Eric Laurente552edb2014-03-10 17:42:56 -07005194 case AUDIO_SOURCE_VOICE_RECOGNITION:
5195 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005196 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005197 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005198 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005199 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005200 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005201 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5202 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005203 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005204 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5205 }
5206 break;
5207 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005208 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005209 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005210 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005211 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5212 }
5213 break;
5214 case AUDIO_SOURCE_VOICE_DOWNLINK:
5215 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005216 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005217 device = AUDIO_DEVICE_IN_VOICE_CALL;
5218 }
5219 break;
5220 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005221 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005222 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5223 }
5224 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005225 case AUDIO_SOURCE_FM_TUNER:
5226 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5227 device = AUDIO_DEVICE_IN_FM_TUNER;
5228 }
5229 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005230 default:
5231 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5232 break;
5233 }
5234 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5235 return device;
5236}
5237
Eric Laurente0720872014-03-11 09:30:41 -07005238bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005239{
5240 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5241 device &= ~AUDIO_DEVICE_BIT_IN;
5242 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5243 return true;
5244 }
5245 return false;
5246}
5247
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005248bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005249 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005250}
5251
Eric Laurente0720872014-03-11 09:30:41 -07005252audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005253{
5254 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005255 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005256 if ((input_descriptor->mRefCount > 0)
5257 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5258 return mInputs.keyAt(i);
5259 }
5260 }
5261 return 0;
5262}
5263
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005264uint32_t AudioPolicyManager::activeInputsCount() const
5265{
5266 uint32_t count = 0;
5267 for (size_t i = 0; i < mInputs.size(); i++) {
5268 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5269 if (desc->mRefCount > 0) {
5270 return count++;
5271 }
5272 }
5273 return count;
5274}
5275
Eric Laurente552edb2014-03-10 17:42:56 -07005276
Eric Laurente0720872014-03-11 09:30:41 -07005277audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005278{
5279 if (device == AUDIO_DEVICE_NONE) {
5280 // this happens when forcing a route update and no track is active on an output.
5281 // In this case the returned category is not important.
5282 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005283 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005284 // Multiple device selection is either:
5285 // - speaker + one other device: give priority to speaker in this case.
5286 // - one A2DP device + another device: happens with duplicated output. In this case
5287 // retain the device on the A2DP output as the other must not correspond to an active
5288 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005289 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005290 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5291 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005292 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5293 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5294 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5295 device = AUDIO_DEVICE_OUT_AUX_LINE;
5296 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5297 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005298 } else {
5299 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5300 }
5301 }
5302
Jon Eklund11c9fb12014-06-23 14:47:03 -05005303 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5304 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5305 device = AUDIO_DEVICE_OUT_SPEAKER;
5306
Eric Laurent3b73df72014-03-11 09:06:29 -07005307 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005308 "getDeviceForVolume() invalid device combination: %08x",
5309 device);
5310
5311 return device;
5312}
5313
Eric Laurente0720872014-03-11 09:30:41 -07005314AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005315{
5316 switch(getDeviceForVolume(device)) {
5317 case AUDIO_DEVICE_OUT_EARPIECE:
5318 return DEVICE_CATEGORY_EARPIECE;
5319 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5320 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5321 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5322 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5323 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5324 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5325 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005326 case AUDIO_DEVICE_OUT_LINE:
5327 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5328 /*USB? Remote submix?*/
5329 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005330 case AUDIO_DEVICE_OUT_SPEAKER:
5331 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5332 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005333 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5334 case AUDIO_DEVICE_OUT_USB_DEVICE:
5335 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5336 default:
5337 return DEVICE_CATEGORY_SPEAKER;
5338 }
5339}
5340
Eric Laurent223fd5c2014-11-11 13:43:36 -08005341/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005342float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005343 int indexInUi)
5344{
5345 device_category deviceCategory = getDeviceCategory(device);
5346 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5347
5348 // the volume index in the UI is relative to the min and max volume indices for this stream type
5349 int nbSteps = 1 + curve[VOLMAX].mIndex -
5350 curve[VOLMIN].mIndex;
5351 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5352 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5353
5354 // find what part of the curve this index volume belongs to, or if it's out of bounds
5355 int segment = 0;
5356 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5357 return 0.0f;
5358 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5359 segment = 0;
5360 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5361 segment = 1;
5362 } else if (volIdx <= curve[VOLMAX].mIndex) {
5363 segment = 2;
5364 } else { // out of bounds
5365 return 1.0f;
5366 }
5367
5368 // linear interpolation in the attenuation table in dB
5369 float decibels = curve[segment].mDBAttenuation +
5370 ((float)(volIdx - curve[segment].mIndex)) *
5371 ( (curve[segment+1].mDBAttenuation -
5372 curve[segment].mDBAttenuation) /
5373 ((float)(curve[segment+1].mIndex -
5374 curve[segment].mIndex)) );
5375
5376 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5377
5378 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5379 curve[segment].mIndex, volIdx,
5380 curve[segment+1].mIndex,
5381 curve[segment].mDBAttenuation,
5382 decibels,
5383 curve[segment+1].mDBAttenuation,
5384 amplification);
5385
5386 return amplification;
5387}
5388
Eric Laurente0720872014-03-11 09:30:41 -07005389const AudioPolicyManager::VolumeCurvePoint
5390 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005391 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5392};
5393
Eric Laurente0720872014-03-11 09:30:41 -07005394const AudioPolicyManager::VolumeCurvePoint
5395 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005396 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5397};
5398
Eric Laurente0720872014-03-11 09:30:41 -07005399const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005400 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5401 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5402};
5403
5404const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005405 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005406 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5407};
5408
Eric Laurente0720872014-03-11 09:30:41 -07005409const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005410 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005411 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005412};
5413
5414const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005415 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005416 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5417};
5418
Eric Laurente0720872014-03-11 09:30:41 -07005419const AudioPolicyManager::VolumeCurvePoint
5420 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005421 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5422};
5423
5424// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5425// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5426// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5427// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5428
Eric Laurente0720872014-03-11 09:30:41 -07005429const AudioPolicyManager::VolumeCurvePoint
5430 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005431 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5432};
5433
Eric Laurente0720872014-03-11 09:30:41 -07005434const AudioPolicyManager::VolumeCurvePoint
5435 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005436 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5437};
5438
Eric Laurente0720872014-03-11 09:30:41 -07005439const AudioPolicyManager::VolumeCurvePoint
5440 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005441 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5442};
5443
Eric Laurente0720872014-03-11 09:30:41 -07005444const AudioPolicyManager::VolumeCurvePoint
5445 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005446 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5447};
5448
Eric Laurente0720872014-03-11 09:30:41 -07005449const AudioPolicyManager::VolumeCurvePoint
5450 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005451 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5452};
5453
Eric Laurente0720872014-03-11 09:30:41 -07005454const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005455 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5456 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5457};
5458
5459const AudioPolicyManager::VolumeCurvePoint
5460 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5461 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5462};
5463
5464const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005465 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5466 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5467};
5468
5469const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005470 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5471 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005472 { // AUDIO_STREAM_VOICE_CALL
5473 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5474 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005475 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5476 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005477 },
5478 { // AUDIO_STREAM_SYSTEM
5479 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5480 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005481 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5482 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005483 },
5484 { // AUDIO_STREAM_RING
5485 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5486 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005487 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5488 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005489 },
5490 { // AUDIO_STREAM_MUSIC
5491 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5492 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005493 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5494 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005495 },
5496 { // AUDIO_STREAM_ALARM
5497 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5498 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005499 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5500 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005501 },
5502 { // AUDIO_STREAM_NOTIFICATION
5503 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5504 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005505 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5506 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005507 },
5508 { // AUDIO_STREAM_BLUETOOTH_SCO
5509 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5510 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005511 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5512 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005513 },
5514 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5515 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5516 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005517 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5518 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005519 },
5520 { // AUDIO_STREAM_DTMF
5521 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5522 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005523 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5524 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005525 },
5526 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005527 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5528 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5529 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5530 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5531 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005532 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005533 { // AUDIO_STREAM_ACCESSIBILITY
5534 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5535 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5536 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5537 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5538 },
5539 { // AUDIO_STREAM_REROUTING
5540 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5541 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5542 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5543 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5544 },
5545 { // AUDIO_STREAM_PATCH
5546 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5547 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5548 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5549 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5550 },
Eric Laurente552edb2014-03-10 17:42:56 -07005551};
5552
Eric Laurente0720872014-03-11 09:30:41 -07005553void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005554{
5555 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5556 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5557 mStreams[i].mVolumeCurve[j] =
5558 sVolumeProfiles[i][j];
5559 }
5560 }
5561
5562 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5563 if (mSpeakerDrcEnabled) {
5564 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5565 sDefaultSystemVolumeCurveDrc;
5566 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5567 sSpeakerSonificationVolumeCurveDrc;
5568 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5569 sSpeakerSonificationVolumeCurveDrc;
5570 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5571 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005572 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5573 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005574 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5575 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005576 }
5577}
5578
Eric Laurente0720872014-03-11 09:30:41 -07005579float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005580 int index,
5581 audio_io_handle_t output,
5582 audio_devices_t device)
5583{
5584 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005585 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005586 StreamDescriptor &streamDesc = mStreams[stream];
5587
5588 if (device == AUDIO_DEVICE_NONE) {
5589 device = outputDesc->device();
5590 }
5591
Eric Laurente552edb2014-03-10 17:42:56 -07005592 volume = volIndexToAmpl(device, streamDesc, index);
5593
5594 // if a headset is connected, apply the following rules to ring tones and notifications
5595 // to avoid sound level bursts in user's ears:
5596 // - always attenuate ring tones and notifications volume by 6dB
5597 // - if music is playing, always limit the volume to current music volume,
5598 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005600 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5601 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5602 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5603 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5604 ((stream_strategy == STRATEGY_SONIFICATION)
5605 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005606 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005607 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005608 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005609 streamDesc.mCanBeMuted) {
5610 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5611 // when the phone is ringing we must consider that music could have been paused just before
5612 // by the music application and behave as if music was active if the last music track was
5613 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005614 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005615 mLimitRingtoneVolume) {
5616 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005617 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5618 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005619 output,
5620 musicDevice);
5621 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5622 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5623 if (volume > minVol) {
5624 volume = minVol;
5625 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5626 }
5627 }
5628 }
5629
5630 return volume;
5631}
5632
Eric Laurente0720872014-03-11 09:30:41 -07005633status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005634 int index,
5635 audio_io_handle_t output,
5636 audio_devices_t device,
5637 int delayMs,
5638 bool force)
5639{
5640
5641 // do not change actual stream volume if the stream is muted
5642 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5643 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5644 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5645 return NO_ERROR;
5646 }
5647
5648 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005649 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5650 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5651 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5652 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005653 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005654 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005655 return INVALID_OPERATION;
5656 }
5657
5658 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005659 // unit gain if rerouting to external policy
5660 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5661 ssize_t index = mOutputs.indexOfKey(output);
5662 if (index >= 0) {
5663 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005664 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005665 ALOGV("max gain when rerouting for output=%d", output);
5666 volume = 1.0f;
5667 }
5668 }
5669
5670 }
Eric Laurente552edb2014-03-10 17:42:56 -07005671 // We actually change the volume if:
5672 // - the float value returned by computeVolume() changed
5673 // - the force flag is set
5674 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5675 force) {
5676 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5677 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5678 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5679 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005680 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5681 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005682 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005683 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005684 }
5685
Eric Laurent3b73df72014-03-11 09:06:29 -07005686 if (stream == AUDIO_STREAM_VOICE_CALL ||
5687 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005688 float voiceVolume;
5689 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005690 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005691 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5692 } else {
5693 voiceVolume = 1.0;
5694 }
5695
5696 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5697 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5698 mLastVoiceVolume = voiceVolume;
5699 }
5700 }
5701
5702 return NO_ERROR;
5703}
5704
Eric Laurente0720872014-03-11 09:30:41 -07005705void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005706 audio_devices_t device,
5707 int delayMs,
5708 bool force)
5709{
5710 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5711
Eric Laurent3b73df72014-03-11 09:06:29 -07005712 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005713 if (stream == AUDIO_STREAM_PATCH) {
5714 continue;
5715 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005716 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005717 mStreams[stream].getVolumeIndex(device),
5718 output,
5719 device,
5720 delayMs,
5721 force);
5722 }
5723}
5724
Eric Laurente0720872014-03-11 09:30:41 -07005725void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005726 bool on,
5727 audio_io_handle_t output,
5728 int delayMs,
5729 audio_devices_t device)
5730{
5731 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005732 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005733 if (stream == AUDIO_STREAM_PATCH) {
5734 continue;
5735 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005736 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5737 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005738 }
5739 }
5740}
5741
Eric Laurente0720872014-03-11 09:30:41 -07005742void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005743 bool on,
5744 audio_io_handle_t output,
5745 int delayMs,
5746 audio_devices_t device)
5747{
5748 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005749 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005750 if (device == AUDIO_DEVICE_NONE) {
5751 device = outputDesc->device();
5752 }
5753
5754 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5755 stream, on, output, outputDesc->mMuteCount[stream], device);
5756
5757 if (on) {
5758 if (outputDesc->mMuteCount[stream] == 0) {
5759 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005760 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5761 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005762 checkAndSetVolume(stream, 0, output, device, delayMs);
5763 }
5764 }
5765 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5766 outputDesc->mMuteCount[stream]++;
5767 } else {
5768 if (outputDesc->mMuteCount[stream] == 0) {
5769 ALOGV("setStreamMute() unmuting non muted stream!");
5770 return;
5771 }
5772 if (--outputDesc->mMuteCount[stream] == 0) {
5773 checkAndSetVolume(stream,
5774 streamDesc.getVolumeIndex(device),
5775 output,
5776 device,
5777 delayMs);
5778 }
5779 }
5780}
5781
Eric Laurente0720872014-03-11 09:30:41 -07005782void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005783 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005784{
5785 // if the stream pertains to sonification strategy and we are in call we must
5786 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5787 // in the device used for phone strategy and play the tone if the selected device does not
5788 // interfere with the device used for phone strategy
5789 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5790 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005791 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005792 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5793 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005794 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005795 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5796 stream, starting, outputDesc->mDevice, stateChange);
5797 if (outputDesc->mRefCount[stream]) {
5798 int muteCount = 1;
5799 if (stateChange) {
5800 muteCount = outputDesc->mRefCount[stream];
5801 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005802 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005803 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5804 for (int i = 0; i < muteCount; i++) {
5805 setStreamMute(stream, starting, mPrimaryOutput);
5806 }
5807 } else {
5808 ALOGV("handleIncallSonification() high visibility");
5809 if (outputDesc->device() &
5810 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5811 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5812 for (int i = 0; i < muteCount; i++) {
5813 setStreamMute(stream, starting, mPrimaryOutput);
5814 }
5815 }
5816 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005817 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5818 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005819 } else {
5820 mpClientInterface->stopTone();
5821 }
5822 }
5823 }
5824 }
5825}
5826
Eric Laurente0720872014-03-11 09:30:41 -07005827bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005828{
5829 return isStateInCall(mPhoneState);
5830}
5831
Eric Laurente0720872014-03-11 09:30:41 -07005832bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005833 return ((state == AUDIO_MODE_IN_CALL) ||
5834 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005835}
5836
Eric Laurente0720872014-03-11 09:30:41 -07005837uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005838{
5839 return MAX_EFFECTS_CPU_LOAD;
5840}
5841
Eric Laurente0720872014-03-11 09:30:41 -07005842uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005843{
5844 return MAX_EFFECTS_MEMORY;
5845}
5846
Eric Laurent6a94d692014-05-20 11:18:06 -07005847
Eric Laurente552edb2014-03-10 17:42:56 -07005848// --- AudioOutputDescriptor class implementation
5849
Eric Laurente0720872014-03-11 09:30:41 -07005850AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005851 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005852 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005853 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005854 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005855 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5856{
5857 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005858 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005859 mRefCount[i] = 0;
5860 mCurVolume[i] = -1.0;
5861 mMuteCount[i] = 0;
5862 mStopTime[i] = 0;
5863 }
5864 for (int i = 0; i < NUM_STRATEGIES; i++) {
5865 mStrategyMutedByDevice[i] = false;
5866 }
5867 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005868 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005869 mSamplingRate = profile->pickSamplingRate();
5870 mFormat = profile->pickFormat();
5871 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005872 if (profile->mGains.size() > 0) {
5873 profile->mGains[0]->getDefaultConfig(&mGain);
5874 }
Eric Laurente552edb2014-03-10 17:42:56 -07005875 }
5876}
5877
Eric Laurente0720872014-03-11 09:30:41 -07005878audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005879{
5880 if (isDuplicated()) {
5881 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5882 } else {
5883 return mDevice;
5884 }
5885}
5886
Eric Laurente0720872014-03-11 09:30:41 -07005887uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005888{
5889 if (isDuplicated()) {
5890 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5891 } else {
5892 return mLatency;
5893 }
5894}
5895
Eric Laurente0720872014-03-11 09:30:41 -07005896bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005897 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005898{
5899 if (isDuplicated()) {
5900 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5901 } else if (outputDesc->isDuplicated()){
5902 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5903 } else {
5904 return (mProfile->mModule == outputDesc->mProfile->mModule);
5905 }
5906}
5907
Eric Laurente0720872014-03-11 09:30:41 -07005908void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005909 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005910{
5911 // forward usage count change to attached outputs
5912 if (isDuplicated()) {
5913 mOutput1->changeRefCount(stream, delta);
5914 mOutput2->changeRefCount(stream, delta);
5915 }
5916 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005917 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5918 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005919 mRefCount[stream] = 0;
5920 return;
5921 }
5922 mRefCount[stream] += delta;
5923 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5924}
5925
Eric Laurente0720872014-03-11 09:30:41 -07005926audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005927{
5928 if (isDuplicated()) {
5929 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5930 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005931 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005932 }
5933}
5934
Eric Laurente0720872014-03-11 09:30:41 -07005935bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005936{
5937 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5938}
5939
Eric Laurente0720872014-03-11 09:30:41 -07005940bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005941 uint32_t inPastMs,
5942 nsecs_t sysTime) const
5943{
5944 if ((sysTime == 0) && (inPastMs != 0)) {
5945 sysTime = systemTime();
5946 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005947 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005948 if (i == AUDIO_STREAM_PATCH) {
5949 continue;
5950 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005951 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005952 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005953 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005954 return true;
5955 }
5956 }
5957 return false;
5958}
5959
Eric Laurente0720872014-03-11 09:30:41 -07005960bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005961 uint32_t inPastMs,
5962 nsecs_t sysTime) const
5963{
5964 if (mRefCount[stream] != 0) {
5965 return true;
5966 }
5967 if (inPastMs == 0) {
5968 return false;
5969 }
5970 if (sysTime == 0) {
5971 sysTime = systemTime();
5972 }
5973 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5974 return true;
5975 }
5976 return false;
5977}
5978
Eric Laurent1c333e22014-05-20 10:48:17 -07005979void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005980 struct audio_port_config *dstConfig,
5981 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005982{
Eric Laurent84c70242014-06-23 08:46:27 -07005983 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5984
Eric Laurent1f2f2232014-06-02 12:01:23 -07005985 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5986 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5987 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005988 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005989 }
5990 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5991
Eric Laurent6a94d692014-05-20 11:18:06 -07005992 dstConfig->id = mId;
5993 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5994 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005995 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5996 dstConfig->ext.mix.handle = mIoHandle;
5997 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005998}
5999
6000void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6001 struct audio_port *port) const
6002{
Eric Laurent84c70242014-06-23 08:46:27 -07006003 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07006004 mProfile->toAudioPort(port);
6005 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006006 toAudioPortConfig(&port->active_config);
6007 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006008 port->ext.mix.handle = mIoHandle;
6009 port->ext.mix.latency_class =
6010 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6011}
Eric Laurente552edb2014-03-10 17:42:56 -07006012
Eric Laurente0720872014-03-11 09:30:41 -07006013status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006014{
6015 const size_t SIZE = 256;
6016 char buffer[SIZE];
6017 String8 result;
6018
Eric Laurent4d416952014-08-10 14:07:09 -07006019 snprintf(buffer, SIZE, " ID: %d\n", mId);
6020 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006021 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6022 result.append(buffer);
6023 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6024 result.append(buffer);
6025 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6026 result.append(buffer);
6027 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6028 result.append(buffer);
6029 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6030 result.append(buffer);
6031 snprintf(buffer, SIZE, " Devices %08x\n", device());
6032 result.append(buffer);
6033 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6034 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006035 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6036 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6037 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006038 result.append(buffer);
6039 }
6040 write(fd, result.string(), result.size());
6041
6042 return NO_ERROR;
6043}
6044
6045// --- AudioInputDescriptor class implementation
6046
Eric Laurent1c333e22014-05-20 10:48:17 -07006047AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006048 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006049 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006050 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006051{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006052 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006053 mSamplingRate = profile->pickSamplingRate();
6054 mFormat = profile->pickFormat();
6055 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006056 if (profile->mGains.size() > 0) {
6057 profile->mGains[0]->getDefaultConfig(&mGain);
6058 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006059 }
Eric Laurente552edb2014-03-10 17:42:56 -07006060}
6061
Eric Laurent1c333e22014-05-20 10:48:17 -07006062void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006063 struct audio_port_config *dstConfig,
6064 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006065{
Eric Laurent84c70242014-06-23 08:46:27 -07006066 ALOG_ASSERT(mProfile != 0,
6067 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006068 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6069 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6070 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006071 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006072 }
6073
6074 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6075
Eric Laurent6a94d692014-05-20 11:18:06 -07006076 dstConfig->id = mId;
6077 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6078 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006079 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6080 dstConfig->ext.mix.handle = mIoHandle;
6081 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006082}
6083
6084void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6085 struct audio_port *port) const
6086{
Eric Laurent84c70242014-06-23 08:46:27 -07006087 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6088
Eric Laurent1c333e22014-05-20 10:48:17 -07006089 mProfile->toAudioPort(port);
6090 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006091 toAudioPortConfig(&port->active_config);
6092 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006093 port->ext.mix.handle = mIoHandle;
6094 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6095}
6096
Eric Laurente0720872014-03-11 09:30:41 -07006097status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006098{
6099 const size_t SIZE = 256;
6100 char buffer[SIZE];
6101 String8 result;
6102
Eric Laurent4d416952014-08-10 14:07:09 -07006103 snprintf(buffer, SIZE, " ID: %d\n", mId);
6104 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006105 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6106 result.append(buffer);
6107 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6108 result.append(buffer);
6109 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6110 result.append(buffer);
6111 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6112 result.append(buffer);
6113 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6114 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006115 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6116 result.append(buffer);
6117
Eric Laurente552edb2014-03-10 17:42:56 -07006118 write(fd, result.string(), result.size());
6119
6120 return NO_ERROR;
6121}
6122
6123// --- StreamDescriptor class implementation
6124
Eric Laurente0720872014-03-11 09:30:41 -07006125AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006126 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6127{
6128 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6129}
6130
Eric Laurente0720872014-03-11 09:30:41 -07006131int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006132{
Eric Laurente0720872014-03-11 09:30:41 -07006133 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006134 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6135 if (mIndexCur.indexOfKey(device) < 0) {
6136 device = AUDIO_DEVICE_OUT_DEFAULT;
6137 }
6138 return mIndexCur.valueFor(device);
6139}
6140
Eric Laurente0720872014-03-11 09:30:41 -07006141void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006142{
6143 const size_t SIZE = 256;
6144 char buffer[SIZE];
6145 String8 result;
6146
6147 snprintf(buffer, SIZE, "%s %02d %02d ",
6148 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6149 result.append(buffer);
6150 for (size_t i = 0; i < mIndexCur.size(); i++) {
6151 snprintf(buffer, SIZE, "%04x : %02d, ",
6152 mIndexCur.keyAt(i),
6153 mIndexCur.valueAt(i));
6154 result.append(buffer);
6155 }
6156 result.append("\n");
6157
6158 write(fd, result.string(), result.size());
6159}
6160
6161// --- EffectDescriptor class implementation
6162
Eric Laurente0720872014-03-11 09:30:41 -07006163status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006164{
6165 const size_t SIZE = 256;
6166 char buffer[SIZE];
6167 String8 result;
6168
6169 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6170 result.append(buffer);
6171 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6172 result.append(buffer);
6173 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6174 result.append(buffer);
6175 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6176 result.append(buffer);
6177 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6178 result.append(buffer);
6179 write(fd, result.string(), result.size());
6180
6181 return NO_ERROR;
6182}
6183
Eric Laurent1c333e22014-05-20 10:48:17 -07006184// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006185
Eric Laurente0720872014-03-11 09:30:41 -07006186AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006187 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6188 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006189{
6190}
6191
Eric Laurente0720872014-03-11 09:30:41 -07006192AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006193{
6194 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006195 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006196 }
6197 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006198 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006199 }
6200 free((void *)mName);
6201}
6202
Eric Laurent1afeecb2014-05-14 08:52:28 -07006203status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6204{
6205 cnode *node = root->first_child;
6206
6207 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6208
6209 while (node) {
6210 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6211 profile->loadSamplingRates((char *)node->value);
6212 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6213 profile->loadFormats((char *)node->value);
6214 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6215 profile->loadInChannels((char *)node->value);
6216 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6217 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6218 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006219 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6220 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006221 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6222 profile->loadGains(node);
6223 }
6224 node = node->next;
6225 }
6226 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6227 "loadInput() invalid supported devices");
6228 ALOGW_IF(profile->mChannelMasks.size() == 0,
6229 "loadInput() invalid supported channel masks");
6230 ALOGW_IF(profile->mSamplingRates.size() == 0,
6231 "loadInput() invalid supported sampling rates");
6232 ALOGW_IF(profile->mFormats.size() == 0,
6233 "loadInput() invalid supported formats");
6234 if (!profile->mSupportedDevices.isEmpty() &&
6235 (profile->mChannelMasks.size() != 0) &&
6236 (profile->mSamplingRates.size() != 0) &&
6237 (profile->mFormats.size() != 0)) {
6238
6239 ALOGV("loadInput() adding input Supported Devices %04x",
6240 profile->mSupportedDevices.types());
6241
6242 mInputProfiles.add(profile);
6243 return NO_ERROR;
6244 } else {
6245 return BAD_VALUE;
6246 }
6247}
6248
6249status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6250{
6251 cnode *node = root->first_child;
6252
6253 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6254
6255 while (node) {
6256 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6257 profile->loadSamplingRates((char *)node->value);
6258 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6259 profile->loadFormats((char *)node->value);
6260 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6261 profile->loadOutChannels((char *)node->value);
6262 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6263 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6264 mDeclaredDevices);
6265 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006266 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006267 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6268 profile->loadGains(node);
6269 }
6270 node = node->next;
6271 }
6272 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6273 "loadOutput() invalid supported devices");
6274 ALOGW_IF(profile->mChannelMasks.size() == 0,
6275 "loadOutput() invalid supported channel masks");
6276 ALOGW_IF(profile->mSamplingRates.size() == 0,
6277 "loadOutput() invalid supported sampling rates");
6278 ALOGW_IF(profile->mFormats.size() == 0,
6279 "loadOutput() invalid supported formats");
6280 if (!profile->mSupportedDevices.isEmpty() &&
6281 (profile->mChannelMasks.size() != 0) &&
6282 (profile->mSamplingRates.size() != 0) &&
6283 (profile->mFormats.size() != 0)) {
6284
6285 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6286 profile->mSupportedDevices.types(), profile->mFlags);
6287
6288 mOutputProfiles.add(profile);
6289 return NO_ERROR;
6290 } else {
6291 return BAD_VALUE;
6292 }
6293}
6294
6295status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6296{
6297 cnode *node = root->first_child;
6298
6299 audio_devices_t type = AUDIO_DEVICE_NONE;
6300 while (node) {
6301 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6302 type = parseDeviceNames((char *)node->value);
6303 break;
6304 }
6305 node = node->next;
6306 }
6307 if (type == AUDIO_DEVICE_NONE ||
6308 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6309 ALOGW("loadDevice() bad type %08x", type);
6310 return BAD_VALUE;
6311 }
6312 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6313 deviceDesc->mModule = this;
6314
6315 node = root->first_child;
6316 while (node) {
6317 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6318 deviceDesc->mAddress = String8((char *)node->value);
6319 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6320 if (audio_is_input_device(type)) {
6321 deviceDesc->loadInChannels((char *)node->value);
6322 } else {
6323 deviceDesc->loadOutChannels((char *)node->value);
6324 }
6325 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6326 deviceDesc->loadGains(node);
6327 }
6328 node = node->next;
6329 }
6330
6331 ALOGV("loadDevice() adding device name %s type %08x address %s",
6332 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6333
6334 mDeclaredDevices.add(deviceDesc);
6335
6336 return NO_ERROR;
6337}
6338
Eric Laurent275e8e92014-11-30 15:14:47 -08006339status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6340 audio_devices_t device, String8 address)
6341{
6342 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6343
6344 profile->mSamplingRates.add(config->sample_rate);
6345 profile->mChannelMasks.add(config->channel_mask);
6346 profile->mFormats.add(config->format);
6347
6348 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6349 devDesc->mAddress = address;
6350 profile->mSupportedDevices.add(devDesc);
6351
6352 mOutputProfiles.add(profile);
6353
6354 return NO_ERROR;
6355}
6356
6357status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6358{
6359 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6360 if (mOutputProfiles[i]->mName == name) {
6361 mOutputProfiles.removeAt(i);
6362 break;
6363 }
6364 }
6365
6366 return NO_ERROR;
6367}
6368
6369status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6370 audio_devices_t device, String8 address)
6371{
6372 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6373
6374 profile->mSamplingRates.add(config->sample_rate);
6375 profile->mChannelMasks.add(config->channel_mask);
6376 profile->mFormats.add(config->format);
6377
6378 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6379 devDesc->mAddress = address;
6380 profile->mSupportedDevices.add(devDesc);
6381
6382 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6383
6384 mInputProfiles.add(profile);
6385
6386 return NO_ERROR;
6387}
6388
6389status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6390{
6391 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6392 if (mInputProfiles[i]->mName == name) {
6393 mInputProfiles.removeAt(i);
6394 break;
6395 }
6396 }
6397
6398 return NO_ERROR;
6399}
6400
6401
Eric Laurente0720872014-03-11 09:30:41 -07006402void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006403{
6404 const size_t SIZE = 256;
6405 char buffer[SIZE];
6406 String8 result;
6407
6408 snprintf(buffer, SIZE, " - name: %s\n", mName);
6409 result.append(buffer);
6410 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6411 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006412 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6413 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006414 write(fd, result.string(), result.size());
6415 if (mOutputProfiles.size()) {
6416 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6417 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006418 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006419 write(fd, buffer, strlen(buffer));
6420 mOutputProfiles[i]->dump(fd);
6421 }
6422 }
6423 if (mInputProfiles.size()) {
6424 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6425 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006426 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006427 write(fd, buffer, strlen(buffer));
6428 mInputProfiles[i]->dump(fd);
6429 }
6430 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006431 if (mDeclaredDevices.size()) {
6432 write(fd, " - devices:\n", strlen(" - devices:\n"));
6433 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6434 mDeclaredDevices[i]->dump(fd, 4, i);
6435 }
6436 }
Eric Laurente552edb2014-03-10 17:42:56 -07006437}
6438
Eric Laurent1c333e22014-05-20 10:48:17 -07006439// --- AudioPort class implementation
6440
Eric Laurenta121f902014-06-03 13:32:54 -07006441
6442AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6443 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006444 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006445{
6446 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6447 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6448}
6449
Eric Laurent1c333e22014-05-20 10:48:17 -07006450void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6451{
6452 port->role = mRole;
6453 port->type = mType;
6454 unsigned int i;
6455 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006456 if (mSamplingRates[i] != 0) {
6457 port->sample_rates[i] = mSamplingRates[i];
6458 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006459 }
6460 port->num_sample_rates = i;
6461 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006462 if (mChannelMasks[i] != 0) {
6463 port->channel_masks[i] = mChannelMasks[i];
6464 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006465 }
6466 port->num_channel_masks = i;
6467 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006468 if (mFormats[i] != 0) {
6469 port->formats[i] = mFormats[i];
6470 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006471 }
6472 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006473
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006474 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006475
6476 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6477 port->gains[i] = mGains[i]->mGain;
6478 }
6479 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006480}
6481
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006482void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6483 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6484 const uint32_t rate = port->mSamplingRates.itemAt(k);
6485 if (rate != 0) { // skip "dynamic" rates
6486 bool hasRate = false;
6487 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6488 if (rate == mSamplingRates.itemAt(l)) {
6489 hasRate = true;
6490 break;
6491 }
6492 }
6493 if (!hasRate) { // never import a sampling rate twice
6494 mSamplingRates.add(rate);
6495 }
6496 }
6497 }
6498 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6499 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6500 if (mask != 0) { // skip "dynamic" masks
6501 bool hasMask = false;
6502 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6503 if (mask == mChannelMasks.itemAt(l)) {
6504 hasMask = true;
6505 break;
6506 }
6507 }
6508 if (!hasMask) { // never import a channel mask twice
6509 mChannelMasks.add(mask);
6510 }
6511 }
6512 }
6513 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6514 const audio_format_t format = port->mFormats.itemAt(k);
6515 if (format != 0) { // skip "dynamic" formats
6516 bool hasFormat = false;
6517 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6518 if (format == mFormats.itemAt(l)) {
6519 hasFormat = true;
6520 break;
6521 }
6522 }
6523 if (!hasFormat) { // never import a channel mask twice
6524 mFormats.add(format);
6525 }
6526 }
6527 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006528 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6529 sp<AudioGain> gain = port->mGains.itemAt(k);
6530 if (gain != 0) {
6531 bool hasGain = false;
6532 for (size_t l = 0 ; l < mGains.size() ; l++) {
6533 if (gain == mGains.itemAt(l)) {
6534 hasGain = true;
6535 break;
6536 }
6537 }
6538 if (!hasGain) { // never import a gain twice
6539 mGains.add(gain);
6540 }
6541 }
6542 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006543}
6544
6545void AudioPolicyManager::AudioPort::clearCapabilities() {
6546 mChannelMasks.clear();
6547 mFormats.clear();
6548 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006549 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006550}
Eric Laurent1c333e22014-05-20 10:48:17 -07006551
6552void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6553{
6554 char *str = strtok(name, "|");
6555
6556 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6557 // rates should be read from the output stream after it is opened for the first time
6558 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6559 mSamplingRates.add(0);
6560 return;
6561 }
6562
6563 while (str != NULL) {
6564 uint32_t rate = atoi(str);
6565 if (rate != 0) {
6566 ALOGV("loadSamplingRates() adding rate %d", rate);
6567 mSamplingRates.add(rate);
6568 }
6569 str = strtok(NULL, "|");
6570 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006571}
6572
6573void AudioPolicyManager::AudioPort::loadFormats(char *name)
6574{
6575 char *str = strtok(name, "|");
6576
6577 // by convention, "0' in the first entry in mFormats indicates the supported formats
6578 // should be read from the output stream after it is opened for the first time
6579 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6580 mFormats.add(AUDIO_FORMAT_DEFAULT);
6581 return;
6582 }
6583
6584 while (str != NULL) {
6585 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6586 ARRAY_SIZE(sFormatNameToEnumTable),
6587 str);
6588 if (format != AUDIO_FORMAT_DEFAULT) {
6589 mFormats.add(format);
6590 }
6591 str = strtok(NULL, "|");
6592 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006593}
6594
6595void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6596{
6597 const char *str = strtok(name, "|");
6598
6599 ALOGV("loadInChannels() %s", name);
6600
6601 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6602 mChannelMasks.add(0);
6603 return;
6604 }
6605
6606 while (str != NULL) {
6607 audio_channel_mask_t channelMask =
6608 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6609 ARRAY_SIZE(sInChannelsNameToEnumTable),
6610 str);
6611 if (channelMask != 0) {
6612 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6613 mChannelMasks.add(channelMask);
6614 }
6615 str = strtok(NULL, "|");
6616 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006617}
6618
6619void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6620{
6621 const char *str = strtok(name, "|");
6622
6623 ALOGV("loadOutChannels() %s", name);
6624
6625 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6626 // masks should be read from the output stream after it is opened for the first time
6627 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6628 mChannelMasks.add(0);
6629 return;
6630 }
6631
6632 while (str != NULL) {
6633 audio_channel_mask_t channelMask =
6634 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6635 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6636 str);
6637 if (channelMask != 0) {
6638 mChannelMasks.add(channelMask);
6639 }
6640 str = strtok(NULL, "|");
6641 }
6642 return;
6643}
6644
Eric Laurent1afeecb2014-05-14 08:52:28 -07006645audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6646{
6647 const char *str = strtok(name, "|");
6648
6649 ALOGV("loadGainMode() %s", name);
6650 audio_gain_mode_t mode = 0;
6651 while (str != NULL) {
6652 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6653 ARRAY_SIZE(sGainModeNameToEnumTable),
6654 str);
6655 str = strtok(NULL, "|");
6656 }
6657 return mode;
6658}
6659
Eric Laurenta121f902014-06-03 13:32:54 -07006660void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006661{
6662 cnode *node = root->first_child;
6663
Eric Laurenta121f902014-06-03 13:32:54 -07006664 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006665
6666 while (node) {
6667 if (strcmp(node->name, GAIN_MODE) == 0) {
6668 gain->mGain.mode = loadGainMode((char *)node->value);
6669 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006670 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006671 gain->mGain.channel_mask =
6672 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6673 ARRAY_SIZE(sInChannelsNameToEnumTable),
6674 (char *)node->value);
6675 } else {
6676 gain->mGain.channel_mask =
6677 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6678 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6679 (char *)node->value);
6680 }
6681 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6682 gain->mGain.min_value = atoi((char *)node->value);
6683 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6684 gain->mGain.max_value = atoi((char *)node->value);
6685 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6686 gain->mGain.default_value = atoi((char *)node->value);
6687 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6688 gain->mGain.step_value = atoi((char *)node->value);
6689 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6690 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6691 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6692 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6693 }
6694 node = node->next;
6695 }
6696
6697 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6698 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6699
6700 if (gain->mGain.mode == 0) {
6701 return;
6702 }
6703 mGains.add(gain);
6704}
6705
6706void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6707{
6708 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006709 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006710 while (node) {
6711 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006712 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006713 node = node->next;
6714 }
6715}
6716
Glenn Kastencbd48022014-07-24 13:46:44 -07006717status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006718{
Eric Laurent0daea392014-12-04 19:14:54 -08006719 if (mSamplingRates.isEmpty()) {
6720 return NO_ERROR;
6721 }
6722
Eric Laurenta121f902014-06-03 13:32:54 -07006723 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6724 if (mSamplingRates[i] == samplingRate) {
6725 return NO_ERROR;
6726 }
6727 }
6728 return BAD_VALUE;
6729}
6730
Glenn Kastencbd48022014-07-24 13:46:44 -07006731status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6732 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006733{
Eric Laurent0daea392014-12-04 19:14:54 -08006734 if (mSamplingRates.isEmpty()) {
6735 return NO_ERROR;
6736 }
6737
Glenn Kastencbd48022014-07-24 13:46:44 -07006738 // Search for the closest supported sampling rate that is above (preferred)
6739 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6740 // The sampling rates do not need to be sorted in ascending order.
6741 ssize_t maxBelow = -1;
6742 ssize_t minAbove = -1;
6743 uint32_t candidate;
6744 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6745 candidate = mSamplingRates[i];
6746 if (candidate == samplingRate) {
6747 if (updatedSamplingRate != NULL) {
6748 *updatedSamplingRate = candidate;
6749 }
6750 return NO_ERROR;
6751 }
6752 // candidate < desired
6753 if (candidate < samplingRate) {
6754 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6755 maxBelow = i;
6756 }
6757 // candidate > desired
6758 } else {
6759 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6760 minAbove = i;
6761 }
6762 }
6763 }
6764 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6765 // TODO Move these assumptions out.
6766 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6767 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6768 // due to approximation by an int32_t of the
6769 // phase increments
6770 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6771 if (minAbove >= 0) {
6772 candidate = mSamplingRates[minAbove];
6773 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6774 if (updatedSamplingRate != NULL) {
6775 *updatedSamplingRate = candidate;
6776 }
6777 return NO_ERROR;
6778 }
6779 }
6780 // But if we have to up-sample from a lower sampling rate, that's OK.
6781 if (maxBelow >= 0) {
6782 candidate = mSamplingRates[maxBelow];
6783 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6784 if (updatedSamplingRate != NULL) {
6785 *updatedSamplingRate = candidate;
6786 }
6787 return NO_ERROR;
6788 }
6789 }
6790 // leave updatedSamplingRate unmodified
6791 return BAD_VALUE;
6792}
6793
6794status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6795{
Eric Laurent0daea392014-12-04 19:14:54 -08006796 if (mChannelMasks.isEmpty()) {
6797 return NO_ERROR;
6798 }
6799
Glenn Kastencbd48022014-07-24 13:46:44 -07006800 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006801 if (mChannelMasks[i] == channelMask) {
6802 return NO_ERROR;
6803 }
6804 }
6805 return BAD_VALUE;
6806}
6807
Glenn Kastencbd48022014-07-24 13:46:44 -07006808status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6809 const
6810{
Eric Laurent0daea392014-12-04 19:14:54 -08006811 if (mChannelMasks.isEmpty()) {
6812 return NO_ERROR;
6813 }
6814
Glenn Kastencbd48022014-07-24 13:46:44 -07006815 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6816 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6817 // FIXME Does not handle multi-channel automatic conversions yet
6818 audio_channel_mask_t supported = mChannelMasks[i];
6819 if (supported == channelMask) {
6820 return NO_ERROR;
6821 }
6822 if (isRecordThread) {
6823 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6824 // FIXME Abstract this out to a table.
6825 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6826 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6827 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6828 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6829 return NO_ERROR;
6830 }
6831 }
6832 }
6833 return BAD_VALUE;
6834}
6835
Eric Laurenta121f902014-06-03 13:32:54 -07006836status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6837{
Eric Laurent0daea392014-12-04 19:14:54 -08006838 if (mFormats.isEmpty()) {
6839 return NO_ERROR;
6840 }
6841
Eric Laurenta121f902014-06-03 13:32:54 -07006842 for (size_t i = 0; i < mFormats.size(); i ++) {
6843 if (mFormats[i] == format) {
6844 return NO_ERROR;
6845 }
6846 }
6847 return BAD_VALUE;
6848}
6849
Eric Laurent1e693b52014-07-09 15:03:28 -07006850
6851uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6852{
6853 // special case for uninitialized dynamic profile
6854 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6855 return 0;
6856 }
6857
Eric Laurent828bcff2014-09-07 12:26:06 -07006858 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6859 // channel count / sampling rate combination chosen will be supported by the connected
6860 // sink
6861 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6862 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6863 uint32_t samplingRate = UINT_MAX;
6864 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6865 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6866 samplingRate = mSamplingRates[i];
6867 }
6868 }
6869 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6870 }
6871
Eric Laurent1e693b52014-07-09 15:03:28 -07006872 uint32_t samplingRate = 0;
6873 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6874
6875 // For mixed output and inputs, use max mixer sampling rates. Do not
6876 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006877 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006878 maxRate = UINT_MAX;
6879 }
6880 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6881 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6882 samplingRate = mSamplingRates[i];
6883 }
6884 }
6885 return samplingRate;
6886}
6887
6888audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6889{
6890 // special case for uninitialized dynamic profile
6891 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6892 return AUDIO_CHANNEL_NONE;
6893 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006894 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006895
6896 // For direct outputs, pick minimum channel count: this helps ensuring that the
6897 // channel count / sampling rate combination chosen will be supported by the connected
6898 // sink
6899 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6900 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6901 uint32_t channelCount = UINT_MAX;
6902 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6903 uint32_t cnlCount;
6904 if (mUseInChannelMask) {
6905 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6906 } else {
6907 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6908 }
6909 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6910 channelMask = mChannelMasks[i];
6911 channelCount = cnlCount;
6912 }
6913 }
6914 return channelMask;
6915 }
6916
Eric Laurent1e693b52014-07-09 15:03:28 -07006917 uint32_t channelCount = 0;
6918 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6919
6920 // For mixed output and inputs, use max mixer channel count. Do not
6921 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006922 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006923 maxCount = UINT_MAX;
6924 }
6925 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6926 uint32_t cnlCount;
6927 if (mUseInChannelMask) {
6928 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6929 } else {
6930 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6931 }
6932 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6933 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006934 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006935 }
6936 }
6937 return channelMask;
6938}
6939
Andy Hung9a605382014-07-28 16:16:31 -07006940/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006941const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6942 AUDIO_FORMAT_DEFAULT,
6943 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006944 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006945 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006946 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006947 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006948};
6949
6950int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6951 audio_format_t format2)
6952{
6953 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6954 // compressed format and better than any PCM format. This is by design of pickFormat()
6955 if (!audio_is_linear_pcm(format1)) {
6956 if (!audio_is_linear_pcm(format2)) {
6957 return 0;
6958 }
6959 return 1;
6960 }
6961 if (!audio_is_linear_pcm(format2)) {
6962 return -1;
6963 }
6964
6965 int index1 = -1, index2 = -1;
6966 for (size_t i = 0;
6967 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6968 i ++) {
6969 if (sPcmFormatCompareTable[i] == format1) {
6970 index1 = i;
6971 }
6972 if (sPcmFormatCompareTable[i] == format2) {
6973 index2 = i;
6974 }
6975 }
6976 // format1 not found => index1 < 0 => format2 > format1
6977 // format2 not found => index2 < 0 => format2 < format1
6978 return index1 - index2;
6979}
6980
6981audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6982{
6983 // special case for uninitialized dynamic profile
6984 if (mFormats.size() == 1 && mFormats[0] == 0) {
6985 return AUDIO_FORMAT_DEFAULT;
6986 }
6987
6988 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006989 audio_format_t bestFormat =
6990 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6991 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006992 // For mixed output and inputs, use best mixer output format. Do not
6993 // limit format otherwise
6994 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6995 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006996 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006997 bestFormat = AUDIO_FORMAT_INVALID;
6998 }
6999
7000 for (size_t i = 0; i < mFormats.size(); i ++) {
7001 if ((compareFormats(mFormats[i], format) > 0) &&
7002 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7003 format = mFormats[i];
7004 }
7005 }
7006 return format;
7007}
7008
Eric Laurenta121f902014-06-03 13:32:54 -07007009status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7010 int index) const
7011{
7012 if (index < 0 || (size_t)index >= mGains.size()) {
7013 return BAD_VALUE;
7014 }
7015 return mGains[index]->checkConfig(gainConfig);
7016}
7017
Eric Laurent1afeecb2014-05-14 08:52:28 -07007018void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7019{
7020 const size_t SIZE = 256;
7021 char buffer[SIZE];
7022 String8 result;
7023
7024 if (mName.size() != 0) {
7025 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7026 result.append(buffer);
7027 }
7028
7029 if (mSamplingRates.size() != 0) {
7030 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7031 result.append(buffer);
7032 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007033 if (i == 0 && mSamplingRates[i] == 0) {
7034 snprintf(buffer, SIZE, "Dynamic");
7035 } else {
7036 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7037 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007038 result.append(buffer);
7039 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7040 }
7041 result.append("\n");
7042 }
7043
7044 if (mChannelMasks.size() != 0) {
7045 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7046 result.append(buffer);
7047 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007048 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7049
7050 if (i == 0 && mChannelMasks[i] == 0) {
7051 snprintf(buffer, SIZE, "Dynamic");
7052 } else {
7053 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7054 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007055 result.append(buffer);
7056 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7057 }
7058 result.append("\n");
7059 }
7060
7061 if (mFormats.size() != 0) {
7062 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7063 result.append(buffer);
7064 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007065 const char *formatStr = enumToString(sFormatNameToEnumTable,
7066 ARRAY_SIZE(sFormatNameToEnumTable),
7067 mFormats[i]);
7068 if (i == 0 && strcmp(formatStr, "") == 0) {
7069 snprintf(buffer, SIZE, "Dynamic");
7070 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007071 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007072 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007073 result.append(buffer);
7074 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7075 }
7076 result.append("\n");
7077 }
7078 write(fd, result.string(), result.size());
7079 if (mGains.size() != 0) {
7080 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7081 write(fd, buffer, strlen(buffer) + 1);
7082 result.append(buffer);
7083 for (size_t i = 0; i < mGains.size(); i++) {
7084 mGains[i]->dump(fd, spaces + 2, i);
7085 }
7086 }
7087}
7088
7089// --- AudioGain class implementation
7090
Eric Laurenta121f902014-06-03 13:32:54 -07007091AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007092{
Eric Laurenta121f902014-06-03 13:32:54 -07007093 mIndex = index;
7094 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007095 memset(&mGain, 0, sizeof(struct audio_gain));
7096}
7097
Eric Laurenta121f902014-06-03 13:32:54 -07007098void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7099{
7100 config->index = mIndex;
7101 config->mode = mGain.mode;
7102 config->channel_mask = mGain.channel_mask;
7103 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7104 config->values[0] = mGain.default_value;
7105 } else {
7106 uint32_t numValues;
7107 if (mUseInChannelMask) {
7108 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7109 } else {
7110 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7111 }
7112 for (size_t i = 0; i < numValues; i++) {
7113 config->values[i] = mGain.default_value;
7114 }
7115 }
7116 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7117 config->ramp_duration_ms = mGain.min_ramp_ms;
7118 }
7119}
7120
7121status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7122{
7123 if ((config->mode & ~mGain.mode) != 0) {
7124 return BAD_VALUE;
7125 }
7126 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7127 if ((config->values[0] < mGain.min_value) ||
7128 (config->values[0] > mGain.max_value)) {
7129 return BAD_VALUE;
7130 }
7131 } else {
7132 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7133 return BAD_VALUE;
7134 }
7135 uint32_t numValues;
7136 if (mUseInChannelMask) {
7137 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7138 } else {
7139 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7140 }
7141 for (size_t i = 0; i < numValues; i++) {
7142 if ((config->values[i] < mGain.min_value) ||
7143 (config->values[i] > mGain.max_value)) {
7144 return BAD_VALUE;
7145 }
7146 }
7147 }
7148 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7149 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7150 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7151 return BAD_VALUE;
7152 }
7153 }
7154 return NO_ERROR;
7155}
7156
Eric Laurent1afeecb2014-05-14 08:52:28 -07007157void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7158{
7159 const size_t SIZE = 256;
7160 char buffer[SIZE];
7161 String8 result;
7162
7163 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7164 result.append(buffer);
7165 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7166 result.append(buffer);
7167 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7168 result.append(buffer);
7169 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7170 result.append(buffer);
7171 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7172 result.append(buffer);
7173 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7174 result.append(buffer);
7175 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7176 result.append(buffer);
7177 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7178 result.append(buffer);
7179 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7180 result.append(buffer);
7181
7182 write(fd, result.string(), result.size());
7183}
7184
Eric Laurent1f2f2232014-06-02 12:01:23 -07007185// --- AudioPortConfig class implementation
7186
7187AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7188{
7189 mSamplingRate = 0;
7190 mChannelMask = AUDIO_CHANNEL_NONE;
7191 mFormat = AUDIO_FORMAT_INVALID;
7192 mGain.index = -1;
7193}
7194
Eric Laurenta121f902014-06-03 13:32:54 -07007195status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7196 const struct audio_port_config *config,
7197 struct audio_port_config *backupConfig)
7198{
7199 struct audio_port_config localBackupConfig;
7200 status_t status = NO_ERROR;
7201
7202 localBackupConfig.config_mask = config->config_mask;
7203 toAudioPortConfig(&localBackupConfig);
7204
Marco Nelissen961ec212014-08-25 15:58:39 -07007205 sp<AudioPort> audioport = getAudioPort();
7206 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007207 status = NO_INIT;
7208 goto exit;
7209 }
7210 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007211 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007212 if (status != NO_ERROR) {
7213 goto exit;
7214 }
7215 mSamplingRate = config->sample_rate;
7216 }
7217 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007218 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007219 if (status != NO_ERROR) {
7220 goto exit;
7221 }
7222 mChannelMask = config->channel_mask;
7223 }
7224 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007225 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007226 if (status != NO_ERROR) {
7227 goto exit;
7228 }
7229 mFormat = config->format;
7230 }
7231 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007232 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007233 if (status != NO_ERROR) {
7234 goto exit;
7235 }
7236 mGain = config->gain;
7237 }
7238
7239exit:
7240 if (status != NO_ERROR) {
7241 applyAudioPortConfig(&localBackupConfig);
7242 }
7243 if (backupConfig != NULL) {
7244 *backupConfig = localBackupConfig;
7245 }
7246 return status;
7247}
7248
Eric Laurent1f2f2232014-06-02 12:01:23 -07007249void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7250 struct audio_port_config *dstConfig,
7251 const struct audio_port_config *srcConfig) const
7252{
7253 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7254 dstConfig->sample_rate = mSamplingRate;
7255 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7256 dstConfig->sample_rate = srcConfig->sample_rate;
7257 }
7258 } else {
7259 dstConfig->sample_rate = 0;
7260 }
7261 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7262 dstConfig->channel_mask = mChannelMask;
7263 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7264 dstConfig->channel_mask = srcConfig->channel_mask;
7265 }
7266 } else {
7267 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7268 }
7269 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7270 dstConfig->format = mFormat;
7271 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7272 dstConfig->format = srcConfig->format;
7273 }
7274 } else {
7275 dstConfig->format = AUDIO_FORMAT_INVALID;
7276 }
7277 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7278 dstConfig->gain = mGain;
7279 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7280 dstConfig->gain = srcConfig->gain;
7281 }
7282 } else {
7283 dstConfig->gain.index = -1;
7284 }
7285 if (dstConfig->gain.index != -1) {
7286 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7287 } else {
7288 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7289 }
7290}
7291
Eric Laurent1c333e22014-05-20 10:48:17 -07007292// --- IOProfile class implementation
7293
Eric Laurent1afeecb2014-05-14 08:52:28 -07007294AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007295 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007296 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007297{
7298}
7299
Eric Laurente0720872014-03-11 09:30:41 -07007300AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007301{
7302}
7303
7304// checks if the IO profile is compatible with specified parameters.
7305// Sampling rate, format and channel mask must be specified in order to
7306// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007307bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007308 String8 address,
7309 uint32_t samplingRate,
7310 uint32_t *updatedSamplingRate,
7311 audio_format_t format,
7312 audio_channel_mask_t channelMask,
7313 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007314{
Glenn Kastencbd48022014-07-24 13:46:44 -07007315 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7316 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7317 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007318
Eric Laurent275e8e92014-11-30 15:14:47 -08007319 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007320 return false;
7321 }
7322
7323 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007324 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007325 }
7326 uint32_t myUpdatedSamplingRate = samplingRate;
7327 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007328 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007329 }
7330 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7331 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007332 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007333 }
7334
7335 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7336 return false;
7337 }
7338
7339 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7340 checkExactChannelMask(channelMask) != NO_ERROR)) {
7341 return false;
7342 }
7343 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7344 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7345 return false;
7346 }
7347
7348 if (isPlaybackThread && (mFlags & flags) != flags) {
7349 return false;
7350 }
7351 // The only input flag that is allowed to be different is the fast flag.
7352 // An existing fast stream is compatible with a normal track request.
7353 // An existing normal stream is compatible with a fast track request,
7354 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007355 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007356 ~AUDIO_INPUT_FLAG_FAST)) {
7357 return false;
7358 }
7359
7360 if (updatedSamplingRate != NULL) {
7361 *updatedSamplingRate = myUpdatedSamplingRate;
7362 }
7363 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007364}
7365
Eric Laurente0720872014-03-11 09:30:41 -07007366void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007367{
7368 const size_t SIZE = 256;
7369 char buffer[SIZE];
7370 String8 result;
7371
Eric Laurent1afeecb2014-05-14 08:52:28 -07007372 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007373
Eric Laurente552edb2014-03-10 17:42:56 -07007374 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7375 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007376 snprintf(buffer, SIZE, " - devices:\n");
7377 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007378 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007379 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7380 mSupportedDevices[i]->dump(fd, 6, i);
7381 }
Eric Laurente552edb2014-03-10 17:42:56 -07007382}
7383
Eric Laurentd4692962014-05-05 18:13:44 -07007384void AudioPolicyManager::IOProfile::log()
7385{
7386 const size_t SIZE = 256;
7387 char buffer[SIZE];
7388 String8 result;
7389
7390 ALOGV(" - sampling rates: ");
7391 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7392 ALOGV(" %d", mSamplingRates[i]);
7393 }
7394
7395 ALOGV(" - channel masks: ");
7396 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7397 ALOGV(" 0x%04x", mChannelMasks[i]);
7398 }
7399
7400 ALOGV(" - formats: ");
7401 for (size_t i = 0; i < mFormats.size(); i++) {
7402 ALOGV(" 0x%08x", mFormats[i]);
7403 }
7404
7405 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7406 ALOGV(" - flags: 0x%04x\n", mFlags);
7407}
7408
7409
Eric Laurent3a4311c2014-03-17 12:00:47 -07007410// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007411
Eric Laurent1f2f2232014-06-02 12:01:23 -07007412
7413AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7414 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7415 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7416 AUDIO_PORT_ROLE_SOURCE,
7417 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007418 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007419{
Eric Laurenta121f902014-06-03 13:32:54 -07007420 if (mGains.size() > 0) {
7421 mGains[0]->getDefaultConfig(&mGain);
7422 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007423}
7424
Eric Laurent3a4311c2014-03-17 12:00:47 -07007425bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007426{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007427 // Devices are considered equal if they:
7428 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7429 // - have the same address or one device does not specify the address
7430 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007431 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007432 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007433 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007434 mChannelMask == other->mChannelMask);
7435}
7436
7437void AudioPolicyManager::DeviceVector::refreshTypes()
7438{
Eric Laurent1c333e22014-05-20 10:48:17 -07007439 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007440 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007441 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007442 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007443 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007444}
7445
7446ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7447{
7448 for(size_t i = 0; i < size(); i++) {
7449 if (item->equals(itemAt(i))) {
7450 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007451 }
7452 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007453 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007454}
7455
Eric Laurent3a4311c2014-03-17 12:00:47 -07007456ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007457{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007458 ssize_t ret = indexOf(item);
7459
7460 if (ret < 0) {
7461 ret = SortedVector::add(item);
7462 if (ret >= 0) {
7463 refreshTypes();
7464 }
7465 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007466 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007467 ret = -1;
7468 }
7469 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007470}
7471
Eric Laurent3a4311c2014-03-17 12:00:47 -07007472ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7473{
7474 size_t i;
7475 ssize_t ret = indexOf(item);
7476
7477 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007478 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007479 } else {
7480 ret = SortedVector::removeAt(ret);
7481 if (ret >= 0) {
7482 refreshTypes();
7483 }
7484 }
7485 return ret;
7486}
7487
7488void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7489{
7490 DeviceVector deviceList;
7491
7492 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7493 types &= ~role_bit;
7494
7495 while (types) {
7496 uint32_t i = 31 - __builtin_clz(types);
7497 uint32_t type = 1 << i;
7498 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007499 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007500 }
7501}
7502
Eric Laurent1afeecb2014-05-14 08:52:28 -07007503void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7504 const DeviceVector& declaredDevices)
7505{
7506 char *devName = strtok(name, "|");
7507 while (devName != NULL) {
7508 if (strlen(devName) != 0) {
7509 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7510 ARRAY_SIZE(sDeviceNameToEnumTable),
7511 devName);
7512 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007513 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007514 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7515 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007516 dev->mAddress = String8("0");
7517 }
7518 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007519 } else {
7520 sp<DeviceDescriptor> deviceDesc =
7521 declaredDevices.getDeviceFromName(String8(devName));
7522 if (deviceDesc != 0) {
7523 add(deviceDesc);
7524 }
7525 }
7526 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007527 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007528 }
7529}
7530
Eric Laurent1c333e22014-05-20 10:48:17 -07007531sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7532 audio_devices_t type, String8 address) const
7533{
7534 sp<DeviceDescriptor> device;
7535 for (size_t i = 0; i < size(); i++) {
7536 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007537 if (address == "" || itemAt(i)->mAddress == address) {
7538 device = itemAt(i);
7539 if (itemAt(i)->mAddress == address) {
7540 break;
7541 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007542 }
7543 }
7544 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007545 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007546 type, address.string(), device.get());
7547 return device;
7548}
7549
Eric Laurent6a94d692014-05-20 11:18:06 -07007550sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7551 audio_port_handle_t id) const
7552{
7553 sp<DeviceDescriptor> device;
7554 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007555 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007556 if (itemAt(i)->mId == id) {
7557 device = itemAt(i);
7558 break;
7559 }
7560 }
7561 return device;
7562}
7563
Eric Laurent1c333e22014-05-20 10:48:17 -07007564AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7565 audio_devices_t type) const
7566{
7567 DeviceVector devices;
7568 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7569 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7570 devices.add(itemAt(i));
7571 type &= ~itemAt(i)->mDeviceType;
7572 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7573 itemAt(i)->mDeviceType, itemAt(i).get());
7574 }
7575 }
7576 return devices;
7577}
7578
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007579AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7580 audio_devices_t type, String8 address) const
7581{
7582 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007583 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007584 if (itemAt(i)->mDeviceType == type) {
7585 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007586 devices.add(itemAt(i));
7587 }
7588 }
7589 }
7590 return devices;
7591}
7592
Eric Laurent1afeecb2014-05-14 08:52:28 -07007593sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7594 const String8& name) const
7595{
7596 sp<DeviceDescriptor> device;
7597 for (size_t i = 0; i < size(); i++) {
7598 if (itemAt(i)->mName == name) {
7599 device = itemAt(i);
7600 break;
7601 }
7602 }
7603 return device;
7604}
7605
Eric Laurent6a94d692014-05-20 11:18:06 -07007606void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7607 struct audio_port_config *dstConfig,
7608 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007609{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007610 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7611 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007612 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007613 }
7614
7615 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7616
Eric Laurent6a94d692014-05-20 11:18:06 -07007617 dstConfig->id = mId;
7618 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007619 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007620 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007621 dstConfig->ext.device.type = mDeviceType;
7622 dstConfig->ext.device.hw_module = mModule->mHandle;
7623 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007624}
7625
7626void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7627{
Eric Laurent83b88082014-06-20 18:31:16 -07007628 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007629 AudioPort::toAudioPort(port);
7630 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007631 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007632 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007633 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007634 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7635}
7636
Eric Laurent1afeecb2014-05-14 08:52:28 -07007637status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007638{
7639 const size_t SIZE = 256;
7640 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007641 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007642
Eric Laurent1afeecb2014-05-14 08:52:28 -07007643 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7644 result.append(buffer);
7645 if (mId != 0) {
7646 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7647 result.append(buffer);
7648 }
7649 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7650 enumToString(sDeviceNameToEnumTable,
7651 ARRAY_SIZE(sDeviceNameToEnumTable),
7652 mDeviceType));
7653 result.append(buffer);
7654 if (mAddress.size() != 0) {
7655 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7656 result.append(buffer);
7657 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007658 write(fd, result.string(), result.size());
7659 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007660
7661 return NO_ERROR;
7662}
7663
Eric Laurent4d416952014-08-10 14:07:09 -07007664status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7665{
7666 const size_t SIZE = 256;
7667 char buffer[SIZE];
7668 String8 result;
7669
7670
7671 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7672 result.append(buffer);
7673 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7674 result.append(buffer);
7675 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7676 result.append(buffer);
7677 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7678 result.append(buffer);
7679 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7680 result.append(buffer);
7681 for (size_t i = 0; i < mPatch.num_sources; i++) {
7682 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7683 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7684 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7685 ARRAY_SIZE(sDeviceNameToEnumTable),
7686 mPatch.sources[i].ext.device.type));
7687 } else {
7688 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7689 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7690 }
7691 result.append(buffer);
7692 }
7693 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7694 result.append(buffer);
7695 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7696 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7697 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7698 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7699 ARRAY_SIZE(sDeviceNameToEnumTable),
7700 mPatch.sinks[i].ext.device.type));
7701 } else {
7702 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7703 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7704 }
7705 result.append(buffer);
7706 }
7707
7708 write(fd, result.string(), result.size());
7709 return NO_ERROR;
7710}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007711
7712// --- audio_policy.conf file parsing
7713
Eric Laurent5dbe4712014-09-19 19:04:57 -07007714uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007715{
7716 uint32_t flag = 0;
7717
7718 // it is OK to cast name to non const here as we are not going to use it after
7719 // strtok() modifies it
7720 char *flagName = strtok(name, "|");
7721 while (flagName != NULL) {
7722 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007723 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7724 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007725 flagName);
7726 }
7727 flagName = strtok(NULL, "|");
7728 }
7729 //force direct flag if offload flag is set: offloading implies a direct output stream
7730 // and all common behaviors are driven by checking only the direct flag
7731 // this should normally be set appropriately in the policy configuration file
7732 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7733 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7734 }
7735
Eric Laurent5dbe4712014-09-19 19:04:57 -07007736 return flag;
7737}
7738
7739uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7740{
7741 uint32_t flag = 0;
7742
7743 // it is OK to cast name to non const here as we are not going to use it after
7744 // strtok() modifies it
7745 char *flagName = strtok(name, "|");
7746 while (flagName != NULL) {
7747 if (strlen(flagName) != 0) {
7748 flag |= stringToEnum(sInputFlagNameToEnumTable,
7749 ARRAY_SIZE(sInputFlagNameToEnumTable),
7750 flagName);
7751 }
7752 flagName = strtok(NULL, "|");
7753 }
7754 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007755}
7756
Eric Laurente0720872014-03-11 09:30:41 -07007757audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007758{
7759 uint32_t device = 0;
7760
7761 char *devName = strtok(name, "|");
7762 while (devName != NULL) {
7763 if (strlen(devName) != 0) {
7764 device |= stringToEnum(sDeviceNameToEnumTable,
7765 ARRAY_SIZE(sDeviceNameToEnumTable),
7766 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007767 }
Eric Laurente552edb2014-03-10 17:42:56 -07007768 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007769 }
Eric Laurente552edb2014-03-10 17:42:56 -07007770 return device;
7771}
7772
Eric Laurente0720872014-03-11 09:30:41 -07007773void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007774{
Eric Laurente552edb2014-03-10 17:42:56 -07007775 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007776 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007777 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007778
Eric Laurent1afeecb2014-05-14 08:52:28 -07007779 node = config_find(root, DEVICES_TAG);
7780 if (node != NULL) {
7781 node = node->first_child;
7782 while (node) {
7783 ALOGV("loadHwModule() loading device %s", node->name);
7784 status_t tmpStatus = module->loadDevice(node);
7785 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7786 status = tmpStatus;
7787 }
7788 node = node->next;
7789 }
7790 }
7791 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007792 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007793 node = node->first_child;
7794 while (node) {
7795 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007796 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007797 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7798 status = tmpStatus;
7799 }
7800 node = node->next;
7801 }
7802 }
7803 node = config_find(root, INPUTS_TAG);
7804 if (node != NULL) {
7805 node = node->first_child;
7806 while (node) {
7807 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007808 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007809 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7810 status = tmpStatus;
7811 }
7812 node = node->next;
7813 }
7814 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007815 loadGlobalConfig(root, module);
7816
Eric Laurente552edb2014-03-10 17:42:56 -07007817 if (status == NO_ERROR) {
7818 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007819 }
7820}
7821
Eric Laurente0720872014-03-11 09:30:41 -07007822void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007823{
7824 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7825 if (node == NULL) {
7826 return;
7827 }
7828
7829 node = node->first_child;
7830 while (node) {
7831 ALOGV("loadHwModules() loading module %s", node->name);
7832 loadHwModule(node);
7833 node = node->next;
7834 }
7835}
7836
Eric Laurent1f2f2232014-06-02 12:01:23 -07007837void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007838{
7839 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007840
Eric Laurente552edb2014-03-10 17:42:56 -07007841 if (node == NULL) {
7842 return;
7843 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007844 DeviceVector declaredDevices;
7845 if (module != NULL) {
7846 declaredDevices = module->mDeclaredDevices;
7847 }
7848
Eric Laurente552edb2014-03-10 17:42:56 -07007849 node = node->first_child;
7850 while (node) {
7851 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007852 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7853 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007854 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7855 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007856 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007857 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007858 ARRAY_SIZE(sDeviceNameToEnumTable),
7859 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007860 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007861 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007862 } else {
7863 ALOGW("loadGlobalConfig() default device not specified");
7864 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007865 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007866 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007867 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7868 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007869 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007870 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7871 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7872 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007873 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7874 uint32_t major, minor;
7875 sscanf((char *)node->value, "%u.%u", &major, &minor);
7876 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7877 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7878 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007879 }
7880 node = node->next;
7881 }
7882}
7883
Eric Laurente0720872014-03-11 09:30:41 -07007884status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007885{
7886 cnode *root;
7887 char *data;
7888
7889 data = (char *)load_file(path, NULL);
7890 if (data == NULL) {
7891 return -ENODEV;
7892 }
7893 root = config_node("", "");
7894 config_load(root, data);
7895
Eric Laurente552edb2014-03-10 17:42:56 -07007896 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007897 // legacy audio_policy.conf files have one global_configuration section
7898 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007899 config_free(root);
7900 free(root);
7901 free(data);
7902
7903 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7904
7905 return NO_ERROR;
7906}
7907
Eric Laurente0720872014-03-11 09:30:41 -07007908void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007909{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007910 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007911 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007912 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7913 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007914 mAvailableOutputDevices.add(mDefaultOutputDevice);
7915 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007916
7917 module = new HwModule("primary");
7918
Eric Laurent1afeecb2014-05-14 08:52:28 -07007919 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007920 profile->mSamplingRates.add(44100);
7921 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7922 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007923 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007924 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7925 module->mOutputProfiles.add(profile);
7926
Eric Laurent1afeecb2014-05-14 08:52:28 -07007927 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007928 profile->mSamplingRates.add(8000);
7929 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7930 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007931 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007932 module->mInputProfiles.add(profile);
7933
7934 mHwModules.add(module);
7935}
7936
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007937audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7938{
7939 // flags to stream type mapping
7940 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7941 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7942 }
7943 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7944 return AUDIO_STREAM_BLUETOOTH_SCO;
7945 }
7946
7947 // usage to stream type mapping
7948 switch (attr->usage) {
7949 case AUDIO_USAGE_MEDIA:
7950 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007951 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7952 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007953 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007954 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7955 return AUDIO_STREAM_ALARM;
7956 }
7957 if (isStreamActive(AUDIO_STREAM_RING)) {
7958 return AUDIO_STREAM_RING;
7959 }
7960 if (isInCall()) {
7961 return AUDIO_STREAM_VOICE_CALL;
7962 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007963 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007964 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7965 return AUDIO_STREAM_SYSTEM;
7966 case AUDIO_USAGE_VOICE_COMMUNICATION:
7967 return AUDIO_STREAM_VOICE_CALL;
7968
7969 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7970 return AUDIO_STREAM_DTMF;
7971
7972 case AUDIO_USAGE_ALARM:
7973 return AUDIO_STREAM_ALARM;
7974 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7975 return AUDIO_STREAM_RING;
7976
7977 case AUDIO_USAGE_NOTIFICATION:
7978 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7979 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7980 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7981 case AUDIO_USAGE_NOTIFICATION_EVENT:
7982 return AUDIO_STREAM_NOTIFICATION;
7983
7984 case AUDIO_USAGE_UNKNOWN:
7985 default:
7986 return AUDIO_STREAM_MUSIC;
7987 }
7988}
Eric Laurente83b55d2014-11-14 10:06:21 -08007989
7990bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7991 // has flags that map to a strategy?
7992 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7993 return true;
7994 }
7995
7996 // has known usage?
7997 switch (paa->usage) {
7998 case AUDIO_USAGE_UNKNOWN:
7999 case AUDIO_USAGE_MEDIA:
8000 case AUDIO_USAGE_VOICE_COMMUNICATION:
8001 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8002 case AUDIO_USAGE_ALARM:
8003 case AUDIO_USAGE_NOTIFICATION:
8004 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8005 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8006 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8007 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8008 case AUDIO_USAGE_NOTIFICATION_EVENT:
8009 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8010 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8011 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8012 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008013 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08008014 break;
8015 default:
8016 return false;
8017 }
8018 return true;
8019}
8020
Eric Laurente552edb2014-03-10 17:42:56 -07008021}; // namespace android