blob: e2b34ee3ee85ce0398df1515f79ec42823e40a1f [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()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
33
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
39#include <hardware/audio.h>
40#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070041#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070043#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070044
Eric Laurent3b73df72014-03-11 09:06:29 -070045namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070046
47// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070048// Definitions for audio_policy.conf file parsing
49// ----------------------------------------------------------------------------
50
51struct StringToEnum {
52 const char *name;
53 uint32_t value;
54};
55
56#define STRING_TO_ENUM(string) { #string, string }
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
59const StringToEnum sDeviceNameToEnumTable[] = {
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070073 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070074 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900104 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700105};
106
107const StringToEnum sFlagNameToEnumTable[] = {
108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
113 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
114};
115
116const StringToEnum sFormatNameToEnumTable[] = {
117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
122 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
123 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
124 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530125 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
126 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
127 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
128 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
129 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
130 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
131 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700136 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
137 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
138 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
139 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
140 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700141};
142
143const StringToEnum sOutChannelsNameToEnumTable[] = {
144 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
145 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
146 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
147 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
148};
149
150const StringToEnum sInChannelsNameToEnumTable[] = {
151 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
152 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
153 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
154};
155
Eric Laurent1afeecb2014-05-14 08:52:28 -0700156const StringToEnum sGainModeNameToEnumTable[] = {
157 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
158 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
159 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
160};
161
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162
163uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
164 size_t size,
165 const char *name)
166{
167 for (size_t i = 0; i < size; i++) {
168 if (strcmp(table[i].name, name) == 0) {
169 ALOGV("stringToEnum() found %s", table[i].name);
170 return table[i].value;
171 }
172 }
173 return 0;
174}
175
176const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
177 size_t size,
178 uint32_t value)
179{
180 for (size_t i = 0; i < size; i++) {
181 if (table[i].value == value) {
182 return table[i].name;
183 }
184 }
185 return "";
186}
187
188bool AudioPolicyManager::stringToBool(const char *value)
189{
190 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
191}
192
193
194// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700195// AudioPolicyInterface implementation
196// ----------------------------------------------------------------------------
197
198
Eric Laurente0720872014-03-11 09:30:41 -0700199status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700200 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700201 const char *device_address)
202{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700204
205 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
206
207 // connect/disconnect only 1 device at a time
208 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
209
Eric Laurente552edb2014-03-10 17:42:56 -0700210 // handle output devices
211 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700212 SortedVector <audio_io_handle_t> outputs;
213
Eric Laurent1afeecb2014-05-14 08:52:28 -0700214 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
215 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700216 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
217
Eric Laurente552edb2014-03-10 17:42:56 -0700218 // save a copy of the opened output descriptors before any output is opened or closed
219 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
220 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700221 switch (state)
222 {
223 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700224 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700226 ALOGW("setDeviceConnectionState() device already connected: %x", device);
227 return INVALID_OPERATION;
228 }
229 ALOGV("setDeviceConnectionState() connecting device %x", device);
230
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700232 return INVALID_OPERATION;
233 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700234 // outputs should never be empty here
235 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
236 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700237 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700238 outputs.size());
239 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700240 index = mAvailableOutputDevices.add(devDesc);
241 if (index >= 0) {
242 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700243 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700244 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
245 "could not find HW module for device %08x", device);
246 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700247 } else {
248 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700249 }
250
251 break;
252 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700253 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700255 ALOGW("setDeviceConnectionState() device not connected: %x", device);
256 return INVALID_OPERATION;
257 }
258
259 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
260 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700261 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700262
Eric Laurent3a4311c2014-03-17 12:00:47 -0700263 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700264 // not currently handling multiple simultaneous submixes: ignoring remote submix
265 // case and address
266 } break;
267
268 default:
269 ALOGE("setDeviceConnectionState() invalid state: %x", state);
270 return BAD_VALUE;
271 }
272
Eric Laurent3a4311c2014-03-17 12:00:47 -0700273 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
274 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700275 checkA2dpSuspend();
276 checkOutputForAllStrategies();
277 // outputs must be closed after checkOutputForAllStrategies() is executed
278 if (!outputs.isEmpty()) {
279 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700280 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700281 // close unused outputs after device disconnection or direct outputs that have been
282 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700283 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700284 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
285 (desc->mDirectOpenCount == 0))) {
286 closeOutput(outputs[i]);
287 }
288 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 // check again after closing A2DP output to reset mA2dpSuspended if needed
290 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700291 }
292
293 updateDevicesAndOutputs();
294 for (size_t i = 0; i < mOutputs.size(); i++) {
295 // do not force device change on duplicated output because if device is 0, it will
296 // also force a device 0 for the two outputs it is duplicated to which may override
297 // a valid device selection on those outputs.
298 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700299 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700300 !mOutputs.valueAt(i)->isDuplicated(),
301 0);
302 }
303
Eric Laurent72aa32f2014-05-30 18:51:48 -0700304 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700305 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700306 } // end if is output device
307
Eric Laurente552edb2014-03-10 17:42:56 -0700308 // handle input devices
309 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700310 SortedVector <audio_io_handle_t> inputs;
311
Eric Laurent1afeecb2014-05-14 08:52:28 -0700312 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
313 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700314 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700315 switch (state)
316 {
317 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700318 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700319 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700320 ALOGW("setDeviceConnectionState() device already connected: %d", device);
321 return INVALID_OPERATION;
322 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700323 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700324 if (module == NULL) {
325 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
326 device);
327 return INVALID_OPERATION;
328 }
Eric Laurentd4692962014-05-05 18:13:44 -0700329 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
330 return INVALID_OPERATION;
331 }
332
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 index = mAvailableInputDevices.add(devDesc);
334 if (index >= 0) {
335 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700336 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700337 } else {
338 return NO_MEMORY;
339 }
Eric Laurentd4692962014-05-05 18:13:44 -0700340 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700341
342 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700343 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700344 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700345 ALOGW("setDeviceConnectionState() device not connected: %d", device);
346 return INVALID_OPERATION;
347 }
Eric Laurentd4692962014-05-05 18:13:44 -0700348 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700350 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700351
352 default:
353 ALOGE("setDeviceConnectionState() invalid state: %x", state);
354 return BAD_VALUE;
355 }
356
Eric Laurentd4692962014-05-05 18:13:44 -0700357 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700358
Eric Laurentb52c1522014-05-20 11:27:36 -0700359 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700360 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700361 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700362
363 ALOGW("setDeviceConnectionState() invalid device: %x", device);
364 return BAD_VALUE;
365}
366
Eric Laurente0720872014-03-11 09:30:41 -0700367audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700368 const char *device_address)
369{
Eric Laurent3b73df72014-03-11 09:06:29 -0700370 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700371 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700372 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
373 devDesc->mAddress = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700374 ssize_t index;
375 DeviceVector *deviceVector;
376
Eric Laurente552edb2014-03-10 17:42:56 -0700377 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700378 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700379 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700380 deviceVector = &mAvailableInputDevices;
381 } else {
382 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
383 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700384 }
385
Eric Laurent3a4311c2014-03-17 12:00:47 -0700386 index = deviceVector->indexOf(devDesc);
387 if (index >= 0) {
388 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
389 } else {
390 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
391 }
Eric Laurente552edb2014-03-10 17:42:56 -0700392}
393
Eric Laurente0720872014-03-11 09:30:41 -0700394void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700395{
396 ALOGV("setPhoneState() state %d", state);
397 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700398 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700399 ALOGW("setPhoneState() invalid state %d", state);
400 return;
401 }
402
403 if (state == mPhoneState ) {
404 ALOGW("setPhoneState() setting same state %d", state);
405 return;
406 }
407
408 // if leaving call state, handle special case of active streams
409 // pertaining to sonification strategy see handleIncallSonification()
410 if (isInCall()) {
411 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700412 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
413 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700414 }
415 }
416
417 // store previous phone state for management of sonification strategy below
418 int oldState = mPhoneState;
419 mPhoneState = state;
420 bool force = false;
421
422 // are we entering or starting a call
423 if (!isStateInCall(oldState) && isStateInCall(state)) {
424 ALOGV(" Entering call in setPhoneState()");
425 // force routing command to audio hardware when starting a call
426 // even if no device change is needed
427 force = true;
428 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
429 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
430 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
431 }
432 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
433 ALOGV(" Exiting call in setPhoneState()");
434 // force routing command to audio hardware when exiting a call
435 // even if no device change is needed
436 force = true;
437 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
438 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
439 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
440 }
441 } else if (isStateInCall(state) && (state != oldState)) {
442 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
443 // force routing command to audio hardware when switching between telephony and VoIP
444 // even if no device change is needed
445 force = true;
446 }
447
448 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700449 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700450 checkA2dpSuspend();
451 checkOutputForAllStrategies();
452 updateDevicesAndOutputs();
453
Eric Laurent1f2f2232014-06-02 12:01:23 -0700454 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700455
456 // force routing command to audio hardware when ending call
457 // even if no device change is needed
458 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
459 newDevice = hwOutputDesc->device();
460 }
461
462 int delayMs = 0;
463 if (isStateInCall(state)) {
464 nsecs_t sysTime = systemTime();
465 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700466 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700467 // mute media and sonification strategies and delay device switch by the largest
468 // latency of any output where either strategy is active.
469 // This avoid sending the ring tone or music tail into the earpiece or headset.
470 if ((desc->isStrategyActive(STRATEGY_MEDIA,
471 SONIFICATION_HEADSET_MUSIC_DELAY,
472 sysTime) ||
473 desc->isStrategyActive(STRATEGY_SONIFICATION,
474 SONIFICATION_HEADSET_MUSIC_DELAY,
475 sysTime)) &&
476 (delayMs < (int)desc->mLatency*2)) {
477 delayMs = desc->mLatency*2;
478 }
479 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
480 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
481 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
482 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
483 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
484 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
485 }
486 }
487
488 // change routing is necessary
489 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
490
491 // if entering in call state, handle special case of active streams
492 // pertaining to sonification strategy see handleIncallSonification()
493 if (isStateInCall(state)) {
494 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700495 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
496 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700497 }
498 }
499
500 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700501 if (state == AUDIO_MODE_RINGTONE &&
502 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700503 mLimitRingtoneVolume = true;
504 } else {
505 mLimitRingtoneVolume = false;
506 }
507}
508
Eric Laurente0720872014-03-11 09:30:41 -0700509void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700510 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700511{
512 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
513
514 bool forceVolumeReeval = false;
515 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700516 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
517 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
518 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700519 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
520 return;
521 }
522 forceVolumeReeval = true;
523 mForceUse[usage] = config;
524 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700525 case AUDIO_POLICY_FORCE_FOR_MEDIA:
526 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
527 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
528 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
529 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900530 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700531 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
532 return;
533 }
534 mForceUse[usage] = config;
535 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700536 case AUDIO_POLICY_FORCE_FOR_RECORD:
537 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
538 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
540 return;
541 }
542 mForceUse[usage] = config;
543 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700544 case AUDIO_POLICY_FORCE_FOR_DOCK:
545 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
546 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
547 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
548 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
549 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700550 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
551 }
552 forceVolumeReeval = true;
553 mForceUse[usage] = config;
554 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700555 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
556 if (config != AUDIO_POLICY_FORCE_NONE &&
557 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700558 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
559 }
560 forceVolumeReeval = true;
561 mForceUse[usage] = config;
562 break;
563 default:
564 ALOGW("setForceUse() invalid usage %d", usage);
565 break;
566 }
567
568 // check for device and output changes triggered by new force usage
569 checkA2dpSuspend();
570 checkOutputForAllStrategies();
571 updateDevicesAndOutputs();
572 for (size_t i = 0; i < mOutputs.size(); i++) {
573 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700574 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700575 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
576 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
577 applyStreamVolumes(output, newDevice, 0, true);
578 }
579 }
580
581 audio_io_handle_t activeInput = getActiveInput();
582 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700583 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700584 }
585
586}
587
Eric Laurente0720872014-03-11 09:30:41 -0700588audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700589{
590 return mForceUse[usage];
591}
592
Eric Laurente0720872014-03-11 09:30:41 -0700593void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700594{
595 ALOGV("setSystemProperty() property %s, value %s", property, value);
596}
597
598// Find a direct output profile compatible with the parameters passed, even if the input flags do
599// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700600sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700601 audio_devices_t device,
602 uint32_t samplingRate,
603 audio_format_t format,
604 audio_channel_mask_t channelMask,
605 audio_output_flags_t flags)
606{
607 for (size_t i = 0; i < mHwModules.size(); i++) {
608 if (mHwModules[i]->mHandle == 0) {
609 continue;
610 }
611 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700612 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700613 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700614 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
615 if (profile->isCompatibleProfile(device, samplingRate, format,
616 channelMask,
617 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700618 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700619 }
620 } else {
621 if (profile->isCompatibleProfile(device, samplingRate, format,
622 channelMask,
623 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700624 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700625 }
626 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700627 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
628 return profile;
629 }
Eric Laurente552edb2014-03-10 17:42:56 -0700630 }
631 }
632 return 0;
633}
634
Eric Laurente0720872014-03-11 09:30:41 -0700635audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700636 uint32_t samplingRate,
637 audio_format_t format,
638 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700639 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700640 const audio_offload_info_t *offloadInfo)
641{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700642
Eric Laurent3b73df72014-03-11 09:06:29 -0700643 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700644 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
645 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
646 device, stream, samplingRate, format, channelMask, flags);
647
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700648 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
649 offloadInfo);
650}
651
652audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
653 uint32_t samplingRate,
654 audio_format_t format,
655 audio_channel_mask_t channelMask,
656 audio_output_flags_t flags,
657 const audio_offload_info_t *offloadInfo)
658{
659 if (attr == NULL) {
660 ALOGE("getOutputForAttr() called with NULL audio attributes");
661 return 0;
662 }
663 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
664 attr->usage, attr->content_type, attr->tags);
665
666 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
667 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
668 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
669 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
670 device, samplingRate, format, channelMask, flags);
671
672 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
673 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
674 offloadInfo);
675}
676
677audio_io_handle_t AudioPolicyManager::getOutputForDevice(
678 audio_devices_t device,
679 audio_stream_type_t stream,
680 uint32_t samplingRate,
681 audio_format_t format,
682 audio_channel_mask_t channelMask,
683 audio_output_flags_t flags,
684 const audio_offload_info_t *offloadInfo)
685{
686 audio_io_handle_t output = 0;
687 uint32_t latency = 0;
688
Eric Laurente552edb2014-03-10 17:42:56 -0700689#ifdef AUDIO_POLICY_TEST
690 if (mCurOutput != 0) {
691 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
692 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
693
694 if (mTestOutputs[mCurOutput] == 0) {
695 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700696 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700697 outputDesc->mDevice = mTestDevice;
698 outputDesc->mSamplingRate = mTestSamplingRate;
699 outputDesc->mFormat = mTestFormat;
700 outputDesc->mChannelMask = mTestChannels;
701 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700702 outputDesc->mFlags =
703 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700704 outputDesc->mRefCount[stream] = 0;
705 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
706 &outputDesc->mSamplingRate,
707 &outputDesc->mFormat,
708 &outputDesc->mChannelMask,
709 &outputDesc->mLatency,
710 outputDesc->mFlags,
711 offloadInfo);
712 if (mTestOutputs[mCurOutput]) {
713 AudioParameter outputCmd = AudioParameter();
714 outputCmd.addInt(String8("set_id"),mCurOutput);
715 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
716 addOutput(mTestOutputs[mCurOutput], outputDesc);
717 }
718 }
719 return mTestOutputs[mCurOutput];
720 }
721#endif //AUDIO_POLICY_TEST
722
723 // open a direct output if required by specified parameters
724 //force direct flag if offload flag is set: offloading implies a direct output stream
725 // and all common behaviors are driven by checking only the direct flag
726 // this should normally be set appropriately in the policy configuration file
727 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700728 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700729 }
730
731 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
732 // creating an offloaded track and tearing it down immediately after start when audioflinger
733 // detects there is an active non offloadable effect.
734 // FIXME: We should check the audio session here but we do not have it in this context.
735 // This may prevent offloading in rare situations where effects are left active by apps
736 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700737 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700738 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
739 !isNonOffloadableEffectEnabled()) {
740 profile = getProfileForDirectOutput(device,
741 samplingRate,
742 format,
743 channelMask,
744 (audio_output_flags_t)flags);
745 }
746
Eric Laurent1c333e22014-05-20 10:48:17 -0700747 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700748 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700749
750 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700751 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700752 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
753 outputDesc = desc;
754 // reuse direct output if currently open and configured with same parameters
755 if ((samplingRate == outputDesc->mSamplingRate) &&
756 (format == outputDesc->mFormat) &&
757 (channelMask == outputDesc->mChannelMask)) {
758 outputDesc->mDirectOpenCount++;
759 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
760 return mOutputs.keyAt(i);
761 }
762 }
763 }
764 // close direct output if currently open and configured with different parameters
765 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700766 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700767 }
768 outputDesc = new AudioOutputDescriptor(profile);
769 outputDesc->mDevice = device;
770 outputDesc->mSamplingRate = samplingRate;
771 outputDesc->mFormat = format;
772 outputDesc->mChannelMask = channelMask;
773 outputDesc->mLatency = 0;
774 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
775 outputDesc->mRefCount[stream] = 0;
776 outputDesc->mStopTime[stream] = 0;
777 outputDesc->mDirectOpenCount = 1;
778 output = mpClientInterface->openOutput(profile->mModule->mHandle,
779 &outputDesc->mDevice,
780 &outputDesc->mSamplingRate,
781 &outputDesc->mFormat,
782 &outputDesc->mChannelMask,
783 &outputDesc->mLatency,
784 outputDesc->mFlags,
785 offloadInfo);
786
787 // only accept an output with the requested parameters
788 if (output == 0 ||
789 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
790 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
791 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
792 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
793 "format %d %d, channelMask %04x %04x", output, samplingRate,
794 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
795 outputDesc->mChannelMask);
796 if (output != 0) {
797 mpClientInterface->closeOutput(output);
798 }
Eric Laurente552edb2014-03-10 17:42:56 -0700799 return 0;
800 }
801 audio_io_handle_t srcOutput = getOutputForEffect();
802 addOutput(output, outputDesc);
803 audio_io_handle_t dstOutput = getOutputForEffect();
804 if (dstOutput == output) {
805 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
806 }
807 mPreviousOutputs = mOutputs;
808 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700809 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700810 return output;
811 }
812
813 // ignoring channel mask due to downmix capability in mixer
814
815 // open a non direct output
816
817 // for non direct outputs, only PCM is supported
818 if (audio_is_linear_pcm(format)) {
819 // get which output is suitable for the specified stream. The actual
820 // routing change will happen when startOutput() will be called
821 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
822
823 output = selectOutput(outputs, flags);
824 }
825 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
826 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
827
828 ALOGV("getOutput() returns output %d", output);
829
830 return output;
831}
832
Eric Laurente0720872014-03-11 09:30:41 -0700833audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700834 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700835{
836 // select one output among several that provide a path to a particular device or set of
837 // devices (the list was previously build by getOutputsForDevice()).
838 // The priority is as follows:
839 // 1: the output with the highest number of requested policy flags
840 // 2: the primary output
841 // 3: the first output in the list
842
843 if (outputs.size() == 0) {
844 return 0;
845 }
846 if (outputs.size() == 1) {
847 return outputs[0];
848 }
849
850 int maxCommonFlags = 0;
851 audio_io_handle_t outputFlags = 0;
852 audio_io_handle_t outputPrimary = 0;
853
854 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700855 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700856 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700857 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700858 if (commonFlags > maxCommonFlags) {
859 outputFlags = outputs[i];
860 maxCommonFlags = commonFlags;
861 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
862 }
863 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
864 outputPrimary = outputs[i];
865 }
866 }
867 }
868
869 if (outputFlags != 0) {
870 return outputFlags;
871 }
872 if (outputPrimary != 0) {
873 return outputPrimary;
874 }
875
876 return outputs[0];
877}
878
Eric Laurente0720872014-03-11 09:30:41 -0700879status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700880 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700881 int session)
882{
883 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
884 ssize_t index = mOutputs.indexOfKey(output);
885 if (index < 0) {
886 ALOGW("startOutput() unknown output %d", output);
887 return BAD_VALUE;
888 }
889
Eric Laurent1f2f2232014-06-02 12:01:23 -0700890 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700891
892 // increment usage count for this stream on the requested output:
893 // NOTE that the usage count is the same for duplicated output and hardware output which is
894 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
895 outputDesc->changeRefCount(stream, 1);
896
897 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700898 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700899 routing_strategy strategy = getStrategy(stream);
900 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
901 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
902 uint32_t waitMs = 0;
903 bool force = false;
904 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700905 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700906 if (desc != outputDesc) {
907 // force a device change if any other output is managed by the same hw
908 // module and has a current device selection that differs from selected device.
909 // In this case, the audio HAL must receive the new device selection so that it can
910 // change the device currently selected by the other active output.
911 if (outputDesc->sharesHwModuleWith(desc) &&
912 desc->device() != newDevice) {
913 force = true;
914 }
915 // wait for audio on other active outputs to be presented when starting
916 // a notification so that audio focus effect can propagate.
917 uint32_t latency = desc->latency();
918 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
919 waitMs = latency;
920 }
921 }
922 }
923 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
924
925 // handle special case for sonification while in call
926 if (isInCall()) {
927 handleIncallSonification(stream, true, false);
928 }
929
930 // apply volume rules for current stream and device if necessary
931 checkAndSetVolume(stream,
932 mStreams[stream].getVolumeIndex(newDevice),
933 output,
934 newDevice);
935
936 // update the outputs if starting an output with a stream that can affect notification
937 // routing
938 handleNotificationRoutingForStream(stream);
939 if (waitMs > muteWaitMs) {
940 usleep((waitMs - muteWaitMs) * 2 * 1000);
941 }
942 }
943 return NO_ERROR;
944}
945
946
Eric Laurente0720872014-03-11 09:30:41 -0700947status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700948 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700949 int session)
950{
951 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
952 ssize_t index = mOutputs.indexOfKey(output);
953 if (index < 0) {
954 ALOGW("stopOutput() unknown output %d", output);
955 return BAD_VALUE;
956 }
957
Eric Laurent1f2f2232014-06-02 12:01:23 -0700958 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700959
960 // handle special case for sonification while in call
961 if (isInCall()) {
962 handleIncallSonification(stream, false, false);
963 }
964
965 if (outputDesc->mRefCount[stream] > 0) {
966 // decrement usage count of this stream on the output
967 outputDesc->changeRefCount(stream, -1);
968 // store time at which the stream was stopped - see isStreamActive()
969 if (outputDesc->mRefCount[stream] == 0) {
970 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700971 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700972 // delay the device switch by twice the latency because stopOutput() is executed when
973 // the track stop() command is received and at that time the audio track buffer can
974 // still contain data that needs to be drained. The latency only covers the audio HAL
975 // and kernel buffers. Also the latency does not always include additional delay in the
976 // audio path (audio DSP, CODEC ...)
977 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
978
979 // force restoring the device selection on other active outputs if it differs from the
980 // one being selected for this output
981 for (size_t i = 0; i < mOutputs.size(); i++) {
982 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700983 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700984 if (curOutput != output &&
985 desc->isActive() &&
986 outputDesc->sharesHwModuleWith(desc) &&
987 (newDevice != desc->device())) {
988 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700989 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700990 true,
991 outputDesc->mLatency*2);
992 }
993 }
994 // update the outputs if stopping one with a stream that can affect notification routing
995 handleNotificationRoutingForStream(stream);
996 }
997 return NO_ERROR;
998 } else {
999 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1000 return INVALID_OPERATION;
1001 }
1002}
1003
Eric Laurente0720872014-03-11 09:30:41 -07001004void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001005{
1006 ALOGV("releaseOutput() %d", output);
1007 ssize_t index = mOutputs.indexOfKey(output);
1008 if (index < 0) {
1009 ALOGW("releaseOutput() releasing unknown output %d", output);
1010 return;
1011 }
1012
1013#ifdef AUDIO_POLICY_TEST
1014 int testIndex = testOutputIndex(output);
1015 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001016 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001017 if (outputDesc->isActive()) {
1018 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001019 mOutputs.removeItem(output);
1020 mTestOutputs[testIndex] = 0;
1021 }
1022 return;
1023 }
1024#endif //AUDIO_POLICY_TEST
1025
Eric Laurent1f2f2232014-06-02 12:01:23 -07001026 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001027 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001028 if (desc->mDirectOpenCount <= 0) {
1029 ALOGW("releaseOutput() invalid open count %d for output %d",
1030 desc->mDirectOpenCount, output);
1031 return;
1032 }
1033 if (--desc->mDirectOpenCount == 0) {
1034 closeOutput(output);
1035 // If effects where present on the output, audioflinger moved them to the primary
1036 // output by default: move them back to the appropriate output.
1037 audio_io_handle_t dstOutput = getOutputForEffect();
1038 if (dstOutput != mPrimaryOutput) {
1039 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1040 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001041 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001042 }
1043 }
1044}
1045
1046
Eric Laurente0720872014-03-11 09:30:41 -07001047audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001048 uint32_t samplingRate,
1049 audio_format_t format,
1050 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001051 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001052{
1053 audio_io_handle_t input = 0;
1054 audio_devices_t device = getDeviceForInputSource(inputSource);
1055
1056 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1057 inputSource, samplingRate, format, channelMask, acoustics);
1058
1059 if (device == AUDIO_DEVICE_NONE) {
1060 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1061 return 0;
1062 }
1063
1064 // adapt channel selection to input source
1065 switch(inputSource) {
1066 case AUDIO_SOURCE_VOICE_UPLINK:
1067 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1068 break;
1069 case AUDIO_SOURCE_VOICE_DOWNLINK:
1070 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1071 break;
1072 case AUDIO_SOURCE_VOICE_CALL:
1073 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1074 break;
1075 default:
1076 break;
1077 }
1078
Eric Laurent1c333e22014-05-20 10:48:17 -07001079 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001080 samplingRate,
1081 format,
1082 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001083 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001084 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1085 "channelMask %04x",
1086 device, samplingRate, format, channelMask);
1087 return 0;
1088 }
1089
1090 if (profile->mModule->mHandle == 0) {
1091 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1092 return 0;
1093 }
1094
Eric Laurent1f2f2232014-06-02 12:01:23 -07001095 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001096
1097 inputDesc->mInputSource = inputSource;
1098 inputDesc->mDevice = device;
1099 inputDesc->mSamplingRate = samplingRate;
1100 inputDesc->mFormat = format;
1101 inputDesc->mChannelMask = channelMask;
1102 inputDesc->mRefCount = 0;
1103 input = mpClientInterface->openInput(profile->mModule->mHandle,
1104 &inputDesc->mDevice,
1105 &inputDesc->mSamplingRate,
1106 &inputDesc->mFormat,
1107 &inputDesc->mChannelMask);
1108
1109 // only accept input with the exact requested set of parameters
1110 if (input == 0 ||
1111 (samplingRate != inputDesc->mSamplingRate) ||
1112 (format != inputDesc->mFormat) ||
1113 (channelMask != inputDesc->mChannelMask)) {
1114 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1115 samplingRate, format, channelMask);
1116 if (input != 0) {
1117 mpClientInterface->closeInput(input);
1118 }
Eric Laurente552edb2014-03-10 17:42:56 -07001119 return 0;
1120 }
Eric Laurentd4692962014-05-05 18:13:44 -07001121 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001122 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001123 return input;
1124}
1125
Eric Laurente0720872014-03-11 09:30:41 -07001126status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001127{
1128 ALOGV("startInput() input %d", input);
1129 ssize_t index = mInputs.indexOfKey(input);
1130 if (index < 0) {
1131 ALOGW("startInput() unknown input %d", input);
1132 return BAD_VALUE;
1133 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001134 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001135
1136#ifdef AUDIO_POLICY_TEST
1137 if (mTestInput == 0)
1138#endif //AUDIO_POLICY_TEST
1139 {
1140 // refuse 2 active AudioRecord clients at the same time except if the active input
1141 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1142 audio_io_handle_t activeInput = getActiveInput();
1143 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001144 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001145 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1146 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1147 stopInput(activeInput);
1148 releaseInput(activeInput);
1149 } else {
1150 ALOGW("startInput() input %d failed: other input already started", input);
1151 return INVALID_OPERATION;
1152 }
1153 }
1154 }
1155
Eric Laurent1c333e22014-05-20 10:48:17 -07001156 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001157
1158 // automatically enable the remote submix output when input is started
1159 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1160 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001161 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001162 }
1163
Eric Laurente552edb2014-03-10 17:42:56 -07001164 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1165
Eric Laurente552edb2014-03-10 17:42:56 -07001166 inputDesc->mRefCount = 1;
1167 return NO_ERROR;
1168}
1169
Eric Laurente0720872014-03-11 09:30:41 -07001170status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001171{
1172 ALOGV("stopInput() input %d", input);
1173 ssize_t index = mInputs.indexOfKey(input);
1174 if (index < 0) {
1175 ALOGW("stopInput() unknown input %d", input);
1176 return BAD_VALUE;
1177 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001178 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001179
1180 if (inputDesc->mRefCount == 0) {
1181 ALOGW("stopInput() input %d already stopped", input);
1182 return INVALID_OPERATION;
1183 } else {
1184 // automatically disable the remote submix output when input is stopped
1185 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1186 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001187 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001188 }
1189
Eric Laurent1c333e22014-05-20 10:48:17 -07001190 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001191 inputDesc->mRefCount = 0;
1192 return NO_ERROR;
1193 }
1194}
1195
Eric Laurente0720872014-03-11 09:30:41 -07001196void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001197{
1198 ALOGV("releaseInput() %d", input);
1199 ssize_t index = mInputs.indexOfKey(input);
1200 if (index < 0) {
1201 ALOGW("releaseInput() releasing unknown input %d", input);
1202 return;
1203 }
1204 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001205 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001206 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001207 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001208 ALOGV("releaseInput() exit");
1209}
1210
Eric Laurentd4692962014-05-05 18:13:44 -07001211void AudioPolicyManager::closeAllInputs() {
1212 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1213 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1214 }
1215 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001216 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001217}
1218
Eric Laurente0720872014-03-11 09:30:41 -07001219void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001220 int indexMin,
1221 int indexMax)
1222{
1223 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1224 if (indexMin < 0 || indexMin >= indexMax) {
1225 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1226 return;
1227 }
1228 mStreams[stream].mIndexMin = indexMin;
1229 mStreams[stream].mIndexMax = indexMax;
1230}
1231
Eric Laurente0720872014-03-11 09:30:41 -07001232status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001233 int index,
1234 audio_devices_t device)
1235{
1236
1237 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1238 return BAD_VALUE;
1239 }
1240 if (!audio_is_output_device(device)) {
1241 return BAD_VALUE;
1242 }
1243
1244 // Force max volume if stream cannot be muted
1245 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1246
1247 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1248 stream, device, index);
1249
1250 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1251 // clear all device specific values
1252 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1253 mStreams[stream].mIndexCur.clear();
1254 }
1255 mStreams[stream].mIndexCur.add(device, index);
1256
1257 // compute and apply stream volume on all outputs according to connected device
1258 status_t status = NO_ERROR;
1259 for (size_t i = 0; i < mOutputs.size(); i++) {
1260 audio_devices_t curDevice =
1261 getDeviceForVolume(mOutputs.valueAt(i)->device());
1262 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1263 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1264 if (volStatus != NO_ERROR) {
1265 status = volStatus;
1266 }
1267 }
1268 }
1269 return status;
1270}
1271
Eric Laurente0720872014-03-11 09:30:41 -07001272status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001273 int *index,
1274 audio_devices_t device)
1275{
1276 if (index == NULL) {
1277 return BAD_VALUE;
1278 }
1279 if (!audio_is_output_device(device)) {
1280 return BAD_VALUE;
1281 }
1282 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1283 // the strategy the stream belongs to.
1284 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1285 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1286 }
1287 device = getDeviceForVolume(device);
1288
1289 *index = mStreams[stream].getVolumeIndex(device);
1290 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1291 return NO_ERROR;
1292}
1293
Eric Laurente0720872014-03-11 09:30:41 -07001294audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001295 const SortedVector<audio_io_handle_t>& outputs)
1296{
1297 // select one output among several suitable for global effects.
1298 // The priority is as follows:
1299 // 1: An offloaded output. If the effect ends up not being offloadable,
1300 // AudioFlinger will invalidate the track and the offloaded output
1301 // will be closed causing the effect to be moved to a PCM output.
1302 // 2: A deep buffer output
1303 // 3: the first output in the list
1304
1305 if (outputs.size() == 0) {
1306 return 0;
1307 }
1308
1309 audio_io_handle_t outputOffloaded = 0;
1310 audio_io_handle_t outputDeepBuffer = 0;
1311
1312 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001313 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001314 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001315 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1316 outputOffloaded = outputs[i];
1317 }
1318 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1319 outputDeepBuffer = outputs[i];
1320 }
1321 }
1322
1323 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1324 outputOffloaded, outputDeepBuffer);
1325 if (outputOffloaded != 0) {
1326 return outputOffloaded;
1327 }
1328 if (outputDeepBuffer != 0) {
1329 return outputDeepBuffer;
1330 }
1331
1332 return outputs[0];
1333}
1334
Eric Laurente0720872014-03-11 09:30:41 -07001335audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001336{
1337 // apply simple rule where global effects are attached to the same output as MUSIC streams
1338
Eric Laurent3b73df72014-03-11 09:06:29 -07001339 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001340 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1341 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1342
1343 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1344 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1345 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1346
1347 return output;
1348}
1349
Eric Laurente0720872014-03-11 09:30:41 -07001350status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001351 audio_io_handle_t io,
1352 uint32_t strategy,
1353 int session,
1354 int id)
1355{
1356 ssize_t index = mOutputs.indexOfKey(io);
1357 if (index < 0) {
1358 index = mInputs.indexOfKey(io);
1359 if (index < 0) {
1360 ALOGW("registerEffect() unknown io %d", io);
1361 return INVALID_OPERATION;
1362 }
1363 }
1364
1365 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1366 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1367 desc->name, desc->memoryUsage);
1368 return INVALID_OPERATION;
1369 }
1370 mTotalEffectsMemory += desc->memoryUsage;
1371 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1372 desc->name, io, strategy, session, id);
1373 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1374
Eric Laurent1f2f2232014-06-02 12:01:23 -07001375 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1376 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1377 effectDesc->mIo = io;
1378 effectDesc->mStrategy = (routing_strategy)strategy;
1379 effectDesc->mSession = session;
1380 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001381
Eric Laurent1f2f2232014-06-02 12:01:23 -07001382 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001383
1384 return NO_ERROR;
1385}
1386
Eric Laurente0720872014-03-11 09:30:41 -07001387status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001388{
1389 ssize_t index = mEffects.indexOfKey(id);
1390 if (index < 0) {
1391 ALOGW("unregisterEffect() unknown effect ID %d", id);
1392 return INVALID_OPERATION;
1393 }
1394
Eric Laurent1f2f2232014-06-02 12:01:23 -07001395 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001396
Eric Laurent1f2f2232014-06-02 12:01:23 -07001397 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001398
Eric Laurent1f2f2232014-06-02 12:01:23 -07001399 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001400 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001401 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1402 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001403 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001404 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001405 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001406 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001407
1408 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001409
1410 return NO_ERROR;
1411}
1412
Eric Laurente0720872014-03-11 09:30:41 -07001413status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001414{
1415 ssize_t index = mEffects.indexOfKey(id);
1416 if (index < 0) {
1417 ALOGW("unregisterEffect() unknown effect ID %d", id);
1418 return INVALID_OPERATION;
1419 }
1420
1421 return setEffectEnabled(mEffects.valueAt(index), enabled);
1422}
1423
Eric Laurent1f2f2232014-06-02 12:01:23 -07001424status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001425{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001426 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001427 ALOGV("setEffectEnabled(%s) effect already %s",
1428 enabled?"true":"false", enabled?"enabled":"disabled");
1429 return INVALID_OPERATION;
1430 }
1431
1432 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001433 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001434 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001435 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001436 return INVALID_OPERATION;
1437 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001438 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001439 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1440 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001441 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001442 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001443 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1444 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001445 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001446 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001447 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1448 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001449 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001450 return NO_ERROR;
1451}
1452
Eric Laurente0720872014-03-11 09:30:41 -07001453bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001454{
1455 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001456 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1457 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1458 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001459 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001460 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001461 return true;
1462 }
1463 }
1464 return false;
1465}
1466
Eric Laurente0720872014-03-11 09:30:41 -07001467bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001468{
1469 nsecs_t sysTime = systemTime();
1470 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001471 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001472 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001473 return true;
1474 }
1475 }
1476 return false;
1477}
1478
Eric Laurente0720872014-03-11 09:30:41 -07001479bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001480 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001481{
1482 nsecs_t sysTime = systemTime();
1483 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001484 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001485 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001486 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001487 return true;
1488 }
1489 }
1490 return false;
1491}
1492
Eric Laurente0720872014-03-11 09:30:41 -07001493bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001494{
1495 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001496 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001497 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001498 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001499 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1500 && (inputDescriptor->mRefCount > 0)) {
1501 return true;
1502 }
1503 }
1504 return false;
1505}
1506
1507
Eric Laurente0720872014-03-11 09:30:41 -07001508status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001509{
1510 const size_t SIZE = 256;
1511 char buffer[SIZE];
1512 String8 result;
1513
1514 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1515 result.append(buffer);
1516
1517 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1518 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001519 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1520 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001521 snprintf(buffer, SIZE, " Force use for communications %d\n",
1522 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001523 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001524 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001525 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001526 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001527 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001528 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001529 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001530 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001531 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001532
Eric Laurent3a4311c2014-03-17 12:00:47 -07001533 snprintf(buffer, SIZE, " Available output devices:\n");
1534 result.append(buffer);
1535 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001536 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001537 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001538 }
1539 snprintf(buffer, SIZE, "\n Available input devices:\n");
1540 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001541 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001542 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001543 }
Eric Laurente552edb2014-03-10 17:42:56 -07001544
1545 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1546 write(fd, buffer, strlen(buffer));
1547 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001548 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001549 write(fd, buffer, strlen(buffer));
1550 mHwModules[i]->dump(fd);
1551 }
1552
1553 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1554 write(fd, buffer, strlen(buffer));
1555 for (size_t i = 0; i < mOutputs.size(); i++) {
1556 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1557 write(fd, buffer, strlen(buffer));
1558 mOutputs.valueAt(i)->dump(fd);
1559 }
1560
1561 snprintf(buffer, SIZE, "\nInputs dump:\n");
1562 write(fd, buffer, strlen(buffer));
1563 for (size_t i = 0; i < mInputs.size(); i++) {
1564 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1565 write(fd, buffer, strlen(buffer));
1566 mInputs.valueAt(i)->dump(fd);
1567 }
1568
1569 snprintf(buffer, SIZE, "\nStreams dump:\n");
1570 write(fd, buffer, strlen(buffer));
1571 snprintf(buffer, SIZE,
1572 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1573 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001574 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001575 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001576 write(fd, buffer, strlen(buffer));
1577 mStreams[i].dump(fd);
1578 }
1579
1580 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1581 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1582 write(fd, buffer, strlen(buffer));
1583
1584 snprintf(buffer, SIZE, "Registered effects:\n");
1585 write(fd, buffer, strlen(buffer));
1586 for (size_t i = 0; i < mEffects.size(); i++) {
1587 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1588 write(fd, buffer, strlen(buffer));
1589 mEffects.valueAt(i)->dump(fd);
1590 }
1591
1592
1593 return NO_ERROR;
1594}
1595
1596// This function checks for the parameters which can be offloaded.
1597// This can be enhanced depending on the capability of the DSP and policy
1598// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001599bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001600{
1601 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001602 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001603 offloadInfo.sample_rate, offloadInfo.channel_mask,
1604 offloadInfo.format,
1605 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1606 offloadInfo.has_video);
1607
1608 // Check if offload has been disabled
1609 char propValue[PROPERTY_VALUE_MAX];
1610 if (property_get("audio.offload.disable", propValue, "0")) {
1611 if (atoi(propValue) != 0) {
1612 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1613 return false;
1614 }
1615 }
1616
1617 // Check if stream type is music, then only allow offload as of now.
1618 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1619 {
1620 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1621 return false;
1622 }
1623
1624 //TODO: enable audio offloading with video when ready
1625 if (offloadInfo.has_video)
1626 {
1627 ALOGV("isOffloadSupported: has_video == true, returning false");
1628 return false;
1629 }
1630
1631 //If duration is less than minimum value defined in property, return false
1632 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1633 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1634 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1635 return false;
1636 }
1637 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1638 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1639 return false;
1640 }
1641
1642 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1643 // creating an offloaded track and tearing it down immediately after start when audioflinger
1644 // detects there is an active non offloadable effect.
1645 // FIXME: We should check the audio session here but we do not have it in this context.
1646 // This may prevent offloading in rare situations where effects are left active by apps
1647 // in the background.
1648 if (isNonOffloadableEffectEnabled()) {
1649 return false;
1650 }
1651
1652 // See if there is a profile to support this.
1653 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001654 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001655 offloadInfo.sample_rate,
1656 offloadInfo.format,
1657 offloadInfo.channel_mask,
1658 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001659 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1660 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001661}
1662
Eric Laurent6a94d692014-05-20 11:18:06 -07001663status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1664 audio_port_type_t type,
1665 unsigned int *num_ports,
1666 struct audio_port *ports,
1667 unsigned int *generation)
1668{
1669 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1670 generation == NULL) {
1671 return BAD_VALUE;
1672 }
1673 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1674 if (ports == NULL) {
1675 *num_ports = 0;
1676 }
1677
1678 size_t portsWritten = 0;
1679 size_t portsMax = *num_ports;
1680 *num_ports = 0;
1681 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1682 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1683 for (size_t i = 0;
1684 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1685 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1686 }
1687 *num_ports += mAvailableOutputDevices.size();
1688 }
1689 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1690 for (size_t i = 0;
1691 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1692 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1693 }
1694 *num_ports += mAvailableInputDevices.size();
1695 }
1696 }
1697 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1698 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1699 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1700 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1701 }
1702 *num_ports += mInputs.size();
1703 }
1704 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001705 size_t numOutputs = 0;
1706 for (size_t i = 0; i < mOutputs.size(); i++) {
1707 if (!mOutputs[i]->isDuplicated()) {
1708 numOutputs++;
1709 if (portsWritten < portsMax) {
1710 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1711 }
1712 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001713 }
Eric Laurent84c70242014-06-23 08:46:27 -07001714 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001715 }
1716 }
1717 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001718 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001719 return NO_ERROR;
1720}
1721
1722status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1723{
1724 return NO_ERROR;
1725}
1726
Eric Laurent1f2f2232014-06-02 12:01:23 -07001727sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001728 audio_port_handle_t id) const
1729{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001730 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001731 for (size_t i = 0; i < mOutputs.size(); i++) {
1732 outputDesc = mOutputs.valueAt(i);
1733 if (outputDesc->mId == id) {
1734 break;
1735 }
1736 }
1737 return outputDesc;
1738}
1739
Eric Laurent1f2f2232014-06-02 12:01:23 -07001740sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001741 audio_port_handle_t id) const
1742{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001743 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001744 for (size_t i = 0; i < mInputs.size(); i++) {
1745 inputDesc = mInputs.valueAt(i);
1746 if (inputDesc->mId == id) {
1747 break;
1748 }
1749 }
1750 return inputDesc;
1751}
1752
Eric Laurent1f2f2232014-06-02 12:01:23 -07001753sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1754 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001755{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001756 sp <HwModule> module;
1757
Eric Laurent6a94d692014-05-20 11:18:06 -07001758 for (size_t i = 0; i < mHwModules.size(); i++) {
1759 if (mHwModules[i]->mHandle == 0) {
1760 continue;
1761 }
1762 if (audio_is_output_device(device)) {
1763 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1764 {
1765 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1766 return mHwModules[i];
1767 }
1768 }
1769 } else {
1770 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1771 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1772 device & ~AUDIO_DEVICE_BIT_IN) {
1773 return mHwModules[i];
1774 }
1775 }
1776 }
1777 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001778 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001779}
1780
Eric Laurent1f2f2232014-06-02 12:01:23 -07001781sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001782{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001783 sp <HwModule> module;
1784
Eric Laurent1afeecb2014-05-14 08:52:28 -07001785 for (size_t i = 0; i < mHwModules.size(); i++)
1786 {
1787 if (strcmp(mHwModules[i]->mName, name) == 0) {
1788 return mHwModules[i];
1789 }
1790 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001791 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001792}
1793
1794
Eric Laurent6a94d692014-05-20 11:18:06 -07001795status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1796 audio_patch_handle_t *handle,
1797 uid_t uid)
1798{
1799 ALOGV("createAudioPatch()");
1800
1801 if (handle == NULL || patch == NULL) {
1802 return BAD_VALUE;
1803 }
1804 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1805
1806 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1807 return INVALID_OPERATION;
1808 }
1809 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1810 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1811 return INVALID_OPERATION;
1812 }
1813
1814 sp<AudioPatch> patchDesc;
1815 ssize_t index = mAudioPatches.indexOfKey(*handle);
1816
1817 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1818 patch->sinks[0].type);
1819 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1820 patch->sources[0].role,
1821 patch->sources[0].type);
1822
1823 if (index >= 0) {
1824 patchDesc = mAudioPatches.valueAt(index);
1825 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1826 mUidCached, patchDesc->mUid, uid);
1827 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1828 return INVALID_OPERATION;
1829 }
1830 } else {
1831 *handle = 0;
1832 }
1833
1834 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1835 // TODO add support for mix to mix connection
1836 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1837 ALOGV("createAudioPatch() source mix sink not device");
1838 return BAD_VALUE;
1839 }
1840 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001841 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001842 if (outputDesc == NULL) {
1843 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1844 return BAD_VALUE;
1845 }
Eric Laurent84c70242014-06-23 08:46:27 -07001846 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1847 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001848 if (patchDesc != 0) {
1849 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1850 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1851 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1852 return BAD_VALUE;
1853 }
1854 }
1855 sp<DeviceDescriptor> devDesc =
1856 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1857 if (devDesc == 0) {
1858 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1859 return BAD_VALUE;
1860 }
1861
Eric Laurent84c70242014-06-23 08:46:27 -07001862 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001863 patch->sources[0].sample_rate,
1864 patch->sources[0].format,
1865 patch->sources[0].channel_mask,
1866 AUDIO_OUTPUT_FLAG_NONE)) {
1867 return INVALID_OPERATION;
1868 }
1869 // TODO: reconfigure output format and channels here
1870 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001871 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001872 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001873 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001874 true,
1875 0,
1876 handle);
1877 index = mAudioPatches.indexOfKey(*handle);
1878 if (index >= 0) {
1879 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1880 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1881 }
1882 patchDesc = mAudioPatches.valueAt(index);
1883 patchDesc->mUid = uid;
1884 ALOGV("createAudioPatch() success");
1885 } else {
1886 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1887 return INVALID_OPERATION;
1888 }
1889 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1890 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1891 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001892 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001893 if (inputDesc == NULL) {
1894 return BAD_VALUE;
1895 }
1896 if (patchDesc != 0) {
1897 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1898 return BAD_VALUE;
1899 }
1900 }
1901 sp<DeviceDescriptor> devDesc =
1902 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1903 if (devDesc == 0) {
1904 return BAD_VALUE;
1905 }
1906
Eric Laurent84c70242014-06-23 08:46:27 -07001907 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001908 patch->sinks[0].sample_rate,
1909 patch->sinks[0].format,
1910 patch->sinks[0].channel_mask,
1911 AUDIO_OUTPUT_FLAG_NONE)) {
1912 return INVALID_OPERATION;
1913 }
1914 // TODO: reconfigure output format and channels here
1915 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001916 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001917 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001918 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001919 true,
1920 handle);
1921 index = mAudioPatches.indexOfKey(*handle);
1922 if (index >= 0) {
1923 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1924 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1925 }
1926 patchDesc = mAudioPatches.valueAt(index);
1927 patchDesc->mUid = uid;
1928 ALOGV("createAudioPatch() success");
1929 } else {
1930 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1931 return INVALID_OPERATION;
1932 }
1933 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1934 // device to device connection
1935 if (patchDesc != 0) {
1936 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1937 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1938 return BAD_VALUE;
1939 }
1940 }
1941
1942 sp<DeviceDescriptor> srcDeviceDesc =
1943 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1944 sp<DeviceDescriptor> sinkDeviceDesc =
1945 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1946 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1947 return BAD_VALUE;
1948 }
1949 //update source and sink with our own data as the data passed in the patch may
1950 // be incomplete.
1951 struct audio_patch newPatch = *patch;
1952 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1953 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1954
1955 // TODO: add support for devices on different HW modules
1956 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1957 return INVALID_OPERATION;
1958 }
1959 // TODO: check from routing capabilities in config file and other conflicting patches
1960
1961 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1962 if (index >= 0) {
1963 afPatchHandle = patchDesc->mAfPatchHandle;
1964 }
1965
1966 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1967 &afPatchHandle,
1968 0);
1969 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1970 status, afPatchHandle);
1971 if (status == NO_ERROR) {
1972 if (index < 0) {
1973 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1974 &newPatch, uid);
1975 addAudioPatch(patchDesc->mHandle, patchDesc);
1976 } else {
1977 patchDesc->mPatch = newPatch;
1978 }
1979 patchDesc->mAfPatchHandle = afPatchHandle;
1980 *handle = patchDesc->mHandle;
1981 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001982 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001983 } else {
1984 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1985 status);
1986 return INVALID_OPERATION;
1987 }
1988 } else {
1989 return BAD_VALUE;
1990 }
1991 } else {
1992 return BAD_VALUE;
1993 }
1994 return NO_ERROR;
1995}
1996
1997status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1998 uid_t uid)
1999{
2000 ALOGV("releaseAudioPatch() patch %d", handle);
2001
2002 ssize_t index = mAudioPatches.indexOfKey(handle);
2003
2004 if (index < 0) {
2005 return BAD_VALUE;
2006 }
2007 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2008 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2009 mUidCached, patchDesc->mUid, uid);
2010 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2011 return INVALID_OPERATION;
2012 }
2013
2014 struct audio_patch *patch = &patchDesc->mPatch;
2015 patchDesc->mUid = mUidCached;
2016 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002017 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002018 if (outputDesc == NULL) {
2019 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2020 return BAD_VALUE;
2021 }
2022
2023 setOutputDevice(outputDesc->mIoHandle,
2024 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2025 true,
2026 0,
2027 NULL);
2028 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2029 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002030 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002031 if (inputDesc == NULL) {
2032 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2033 return BAD_VALUE;
2034 }
2035 setInputDevice(inputDesc->mIoHandle,
2036 getNewInputDevice(inputDesc->mIoHandle),
2037 true,
2038 NULL);
2039 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2040 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2041 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2042 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2043 status, patchDesc->mAfPatchHandle);
2044 removeAudioPatch(patchDesc->mHandle);
2045 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002046 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002047 } else {
2048 return BAD_VALUE;
2049 }
2050 } else {
2051 return BAD_VALUE;
2052 }
2053 return NO_ERROR;
2054}
2055
2056status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2057 struct audio_patch *patches,
2058 unsigned int *generation)
2059{
2060 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2061 generation == NULL) {
2062 return BAD_VALUE;
2063 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002064 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002065 *num_patches, patches, mAudioPatches.size());
2066 if (patches == NULL) {
2067 *num_patches = 0;
2068 }
2069
2070 size_t patchesWritten = 0;
2071 size_t patchesMax = *num_patches;
2072 for (size_t i = 0;
2073 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2074 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2075 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002076 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002077 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2078 }
2079 *num_patches = mAudioPatches.size();
2080
2081 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002082 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002083 return NO_ERROR;
2084}
2085
Eric Laurente1715a42014-05-20 11:30:42 -07002086status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002087{
Eric Laurente1715a42014-05-20 11:30:42 -07002088 ALOGV("setAudioPortConfig()");
2089
2090 if (config == NULL) {
2091 return BAD_VALUE;
2092 }
2093 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2094 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002095 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2096 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002097 }
2098
Eric Laurenta121f902014-06-03 13:32:54 -07002099 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002100 if (config->type == AUDIO_PORT_TYPE_MIX) {
2101 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002102 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002103 if (outputDesc == NULL) {
2104 return BAD_VALUE;
2105 }
Eric Laurent84c70242014-06-23 08:46:27 -07002106 ALOG_ASSERT(!outputDesc->isDuplicated(),
2107 "setAudioPortConfig() called on duplicated output %d",
2108 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002109 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002110 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002111 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002112 if (inputDesc == NULL) {
2113 return BAD_VALUE;
2114 }
Eric Laurenta121f902014-06-03 13:32:54 -07002115 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002116 } else {
2117 return BAD_VALUE;
2118 }
2119 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2120 sp<DeviceDescriptor> deviceDesc;
2121 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2122 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2123 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2124 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2125 } else {
2126 return BAD_VALUE;
2127 }
2128 if (deviceDesc == NULL) {
2129 return BAD_VALUE;
2130 }
Eric Laurenta121f902014-06-03 13:32:54 -07002131 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002132 } else {
2133 return BAD_VALUE;
2134 }
2135
Eric Laurenta121f902014-06-03 13:32:54 -07002136 struct audio_port_config backupConfig;
2137 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2138 if (status == NO_ERROR) {
2139 struct audio_port_config newConfig;
2140 audioPortConfig->toAudioPortConfig(&newConfig, config);
2141 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002142 }
Eric Laurenta121f902014-06-03 13:32:54 -07002143 if (status != NO_ERROR) {
2144 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002145 }
Eric Laurente1715a42014-05-20 11:30:42 -07002146
2147 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002148}
2149
2150void AudioPolicyManager::clearAudioPatches(uid_t uid)
2151{
2152 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2153 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2154 if (patchDesc->mUid == uid) {
2155 // releaseAudioPatch() removes the patch from mAudioPatches
2156 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2157 i--;
2158 }
2159 }
2160 }
2161}
2162
2163status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2164 const sp<AudioPatch>& patch)
2165{
2166 ssize_t index = mAudioPatches.indexOfKey(handle);
2167
2168 if (index >= 0) {
2169 ALOGW("addAudioPatch() patch %d already in", handle);
2170 return ALREADY_EXISTS;
2171 }
2172 mAudioPatches.add(handle, patch);
2173 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2174 "sink handle %d",
2175 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2176 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2177 return NO_ERROR;
2178}
2179
2180status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2181{
2182 ssize_t index = mAudioPatches.indexOfKey(handle);
2183
2184 if (index < 0) {
2185 ALOGW("removeAudioPatch() patch %d not in", handle);
2186 return ALREADY_EXISTS;
2187 }
2188 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2189 mAudioPatches.valueAt(index)->mAfPatchHandle);
2190 mAudioPatches.removeItemsAt(index);
2191 return NO_ERROR;
2192}
2193
Eric Laurente552edb2014-03-10 17:42:56 -07002194// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002195// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002196// ----------------------------------------------------------------------------
2197
Eric Laurent3a4311c2014-03-17 12:00:47 -07002198uint32_t AudioPolicyManager::nextUniqueId()
2199{
2200 return android_atomic_inc(&mNextUniqueId);
2201}
2202
Eric Laurent6a94d692014-05-20 11:18:06 -07002203uint32_t AudioPolicyManager::nextAudioPortGeneration()
2204{
2205 return android_atomic_inc(&mAudioPortGeneration);
2206}
2207
Eric Laurente0720872014-03-11 09:30:41 -07002208AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002209 :
2210#ifdef AUDIO_POLICY_TEST
2211 Thread(false),
2212#endif //AUDIO_POLICY_TEST
2213 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002214 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002215 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2216 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002217 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002218 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2219 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002220{
Eric Laurent6a94d692014-05-20 11:18:06 -07002221 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002222 mpClientInterface = clientInterface;
2223
Eric Laurent3b73df72014-03-11 09:06:29 -07002224 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2225 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002226 }
2227
Eric Laurent1afeecb2014-05-14 08:52:28 -07002228 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002229 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2230 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2231 ALOGE("could not load audio policy configuration file, setting defaults");
2232 defaultAudioPolicyConfig();
2233 }
2234 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002235 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002236
2237 // must be done after reading the policy
2238 initializeVolumeCurves();
2239
2240 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002241 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2242 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002243 for (size_t i = 0; i < mHwModules.size(); i++) {
2244 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2245 if (mHwModules[i]->mHandle == 0) {
2246 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2247 continue;
2248 }
2249 // open all output streams needed to access attached devices
2250 // except for direct output streams that are only opened when they are actually
2251 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002252 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002253 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2254 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002255 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002256
Eric Laurent3a4311c2014-03-17 12:00:47 -07002257 if (outProfile->mSupportedDevices.isEmpty()) {
2258 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2259 continue;
2260 }
2261
2262 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2263 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002264 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002265 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002266
Eric Laurent1c333e22014-05-20 10:48:17 -07002267 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002268 audio_io_handle_t output = mpClientInterface->openOutput(
2269 outProfile->mModule->mHandle,
2270 &outputDesc->mDevice,
2271 &outputDesc->mSamplingRate,
2272 &outputDesc->mFormat,
2273 &outputDesc->mChannelMask,
2274 &outputDesc->mLatency,
2275 outputDesc->mFlags);
2276 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002277 ALOGW("Cannot open output stream for device %08x on hw module %s",
2278 outputDesc->mDevice,
2279 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002280 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002281 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002282 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002283 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002284 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002285 // give a valid ID to an attached device once confirmed it is reachable
2286 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2287 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002288 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002289 }
2290 }
Eric Laurente552edb2014-03-10 17:42:56 -07002291 if (mPrimaryOutput == 0 &&
2292 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2293 mPrimaryOutput = output;
2294 }
2295 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002296 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002297 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002298 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002299 true);
2300 }
2301 }
2302 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002303 // open input streams needed to access attached devices to validate
2304 // mAvailableInputDevices list
2305 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2306 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002307 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002308
Eric Laurent3a4311c2014-03-17 12:00:47 -07002309 if (inProfile->mSupportedDevices.isEmpty()) {
2310 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2311 continue;
2312 }
2313
2314 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2315 if (profileTypes & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002316 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002317
2318 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002319 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002320 audio_io_handle_t input = mpClientInterface->openInput(
2321 inProfile->mModule->mHandle,
2322 &inputDesc->mDevice,
2323 &inputDesc->mSamplingRate,
2324 &inputDesc->mFormat,
2325 &inputDesc->mChannelMask);
2326
2327 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002328 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002329 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002330 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002331 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002332 // give a valid ID to an attached device once confirmed it is reachable
2333 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2334 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002335 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002336 }
2337 }
2338 mpClientInterface->closeInput(input);
2339 } else {
2340 ALOGW("Cannot open input stream for device %08x on hw module %s",
2341 inputDesc->mDevice,
2342 mHwModules[i]->mName);
2343 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002344 }
2345 }
2346 }
2347 // make sure all attached devices have been allocated a unique ID
2348 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2349 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002350 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002351 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2352 continue;
2353 }
2354 i++;
2355 }
2356 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2357 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002358 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002359 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2360 continue;
2361 }
2362 i++;
2363 }
2364 // make sure default device is reachable
2365 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002366 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002367 }
Eric Laurente552edb2014-03-10 17:42:56 -07002368
2369 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2370
2371 updateDevicesAndOutputs();
2372
2373#ifdef AUDIO_POLICY_TEST
2374 if (mPrimaryOutput != 0) {
2375 AudioParameter outputCmd = AudioParameter();
2376 outputCmd.addInt(String8("set_id"), 0);
2377 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2378
2379 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2380 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002381 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2382 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002383 mTestLatencyMs = 0;
2384 mCurOutput = 0;
2385 mDirectOutput = false;
2386 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2387 mTestOutputs[i] = 0;
2388 }
2389
2390 const size_t SIZE = 256;
2391 char buffer[SIZE];
2392 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2393 run(buffer, ANDROID_PRIORITY_AUDIO);
2394 }
2395#endif //AUDIO_POLICY_TEST
2396}
2397
Eric Laurente0720872014-03-11 09:30:41 -07002398AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002399{
2400#ifdef AUDIO_POLICY_TEST
2401 exit();
2402#endif //AUDIO_POLICY_TEST
2403 for (size_t i = 0; i < mOutputs.size(); i++) {
2404 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002405 }
2406 for (size_t i = 0; i < mInputs.size(); i++) {
2407 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002408 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002409 mAvailableOutputDevices.clear();
2410 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002411 mOutputs.clear();
2412 mInputs.clear();
2413 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002414}
2415
Eric Laurente0720872014-03-11 09:30:41 -07002416status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002417{
2418 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2419}
2420
2421#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002422bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002423{
2424 ALOGV("entering threadLoop()");
2425 while (!exitPending())
2426 {
2427 String8 command;
2428 int valueInt;
2429 String8 value;
2430
2431 Mutex::Autolock _l(mLock);
2432 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2433
2434 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2435 AudioParameter param = AudioParameter(command);
2436
2437 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2438 valueInt != 0) {
2439 ALOGV("Test command %s received", command.string());
2440 String8 target;
2441 if (param.get(String8("target"), target) != NO_ERROR) {
2442 target = "Manager";
2443 }
2444 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2445 param.remove(String8("test_cmd_policy_output"));
2446 mCurOutput = valueInt;
2447 }
2448 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2449 param.remove(String8("test_cmd_policy_direct"));
2450 if (value == "false") {
2451 mDirectOutput = false;
2452 } else if (value == "true") {
2453 mDirectOutput = true;
2454 }
2455 }
2456 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2457 param.remove(String8("test_cmd_policy_input"));
2458 mTestInput = valueInt;
2459 }
2460
2461 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2462 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002463 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002464 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002465 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002466 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002467 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002468 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002469 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002470 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002471 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002472 if (target == "Manager") {
2473 mTestFormat = format;
2474 } else if (mTestOutputs[mCurOutput] != 0) {
2475 AudioParameter outputParam = AudioParameter();
2476 outputParam.addInt(String8("format"), format);
2477 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2478 }
2479 }
2480 }
2481 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2482 param.remove(String8("test_cmd_policy_channels"));
2483 int channels = 0;
2484
2485 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002486 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002487 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002488 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002489 }
2490 if (channels != 0) {
2491 if (target == "Manager") {
2492 mTestChannels = channels;
2493 } else if (mTestOutputs[mCurOutput] != 0) {
2494 AudioParameter outputParam = AudioParameter();
2495 outputParam.addInt(String8("channels"), channels);
2496 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2497 }
2498 }
2499 }
2500 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2501 param.remove(String8("test_cmd_policy_sampleRate"));
2502 if (valueInt >= 0 && valueInt <= 96000) {
2503 int samplingRate = valueInt;
2504 if (target == "Manager") {
2505 mTestSamplingRate = samplingRate;
2506 } else if (mTestOutputs[mCurOutput] != 0) {
2507 AudioParameter outputParam = AudioParameter();
2508 outputParam.addInt(String8("sampling_rate"), samplingRate);
2509 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2510 }
2511 }
2512 }
2513
2514 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2515 param.remove(String8("test_cmd_policy_reopen"));
2516
Eric Laurent1f2f2232014-06-02 12:01:23 -07002517 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002518 mpClientInterface->closeOutput(mPrimaryOutput);
2519
2520 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2521
Eric Laurente552edb2014-03-10 17:42:56 -07002522 mOutputs.removeItem(mPrimaryOutput);
2523
Eric Laurent1f2f2232014-06-02 12:01:23 -07002524 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002525 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2526 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2527 &outputDesc->mDevice,
2528 &outputDesc->mSamplingRate,
2529 &outputDesc->mFormat,
2530 &outputDesc->mChannelMask,
2531 &outputDesc->mLatency,
2532 outputDesc->mFlags);
2533 if (mPrimaryOutput == 0) {
2534 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2535 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2536 } else {
2537 AudioParameter outputCmd = AudioParameter();
2538 outputCmd.addInt(String8("set_id"), 0);
2539 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2540 addOutput(mPrimaryOutput, outputDesc);
2541 }
2542 }
2543
2544
2545 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2546 }
2547 }
2548 return false;
2549}
2550
Eric Laurente0720872014-03-11 09:30:41 -07002551void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002552{
2553 {
2554 AutoMutex _l(mLock);
2555 requestExit();
2556 mWaitWorkCV.signal();
2557 }
2558 requestExitAndWait();
2559}
2560
Eric Laurente0720872014-03-11 09:30:41 -07002561int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002562{
2563 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2564 if (output == mTestOutputs[i]) return i;
2565 }
2566 return 0;
2567}
2568#endif //AUDIO_POLICY_TEST
2569
2570// ---
2571
Eric Laurent1f2f2232014-06-02 12:01:23 -07002572void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002573{
Eric Laurent1c333e22014-05-20 10:48:17 -07002574 outputDesc->mIoHandle = output;
2575 outputDesc->mId = nextUniqueId();
2576 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002577 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002578}
2579
Eric Laurent1f2f2232014-06-02 12:01:23 -07002580void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002581{
Eric Laurent1c333e22014-05-20 10:48:17 -07002582 inputDesc->mIoHandle = input;
2583 inputDesc->mId = nextUniqueId();
2584 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002585 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002586}
Eric Laurente552edb2014-03-10 17:42:56 -07002587
Eric Laurent3a4311c2014-03-17 12:00:47 -07002588String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2589{
2590 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2591 return String8("a2dp_sink_address=")+address;
2592 }
2593 return address;
2594}
2595
Eric Laurente0720872014-03-11 09:30:41 -07002596status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002597 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002598 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002599 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002600{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002601 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002602
Eric Laurent3b73df72014-03-11 09:06:29 -07002603 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002604 // first list already open outputs that can be routed to this device
2605 for (size_t i = 0; i < mOutputs.size(); i++) {
2606 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002607 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002608 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2609 outputs.add(mOutputs.keyAt(i));
2610 }
2611 }
2612 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002613 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002614 for (size_t i = 0; i < mHwModules.size(); i++)
2615 {
2616 if (mHwModules[i]->mHandle == 0) {
2617 continue;
2618 }
2619 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2620 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002621 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002622 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002623 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2624 }
2625 }
2626 }
2627
2628 if (profiles.isEmpty() && outputs.isEmpty()) {
2629 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2630 return BAD_VALUE;
2631 }
2632
2633 // open outputs for matching profiles if needed. Direct outputs are also opened to
2634 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2635 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002636 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002637
2638 // nothing to do if one output is already opened for this profile
2639 size_t j;
2640 for (j = 0; j < mOutputs.size(); j++) {
2641 desc = mOutputs.valueAt(j);
2642 if (!desc->isDuplicated() && desc->mProfile == profile) {
2643 break;
2644 }
2645 }
2646 if (j != mOutputs.size()) {
2647 continue;
2648 }
2649
Eric Laurent3a4311c2014-03-17 12:00:47 -07002650 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002651 desc = new AudioOutputDescriptor(profile);
2652 desc->mDevice = device;
2653 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2654 offloadInfo.sample_rate = desc->mSamplingRate;
2655 offloadInfo.format = desc->mFormat;
2656 offloadInfo.channel_mask = desc->mChannelMask;
2657
2658 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2659 &desc->mDevice,
2660 &desc->mSamplingRate,
2661 &desc->mFormat,
2662 &desc->mChannelMask,
2663 &desc->mLatency,
2664 desc->mFlags,
2665 &offloadInfo);
2666 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002667 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002668 if (!address.isEmpty()) {
2669 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002670 }
2671
Eric Laurentd4692962014-05-05 18:13:44 -07002672 // Here is where we step through and resolve any "dynamic" fields
2673 String8 reply;
2674 char *value;
2675 if (profile->mSamplingRates[0] == 0) {
2676 reply = mpClientInterface->getParameters(output,
2677 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2678 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2679 reply.string());
2680 value = strpbrk((char *)reply.string(), "=");
2681 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002682 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002683 }
Eric Laurentd4692962014-05-05 18:13:44 -07002684 }
2685 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2686 reply = mpClientInterface->getParameters(output,
2687 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2688 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2689 reply.string());
2690 value = strpbrk((char *)reply.string(), "=");
2691 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002692 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002693 }
Eric Laurentd4692962014-05-05 18:13:44 -07002694 }
2695 if (profile->mChannelMasks[0] == 0) {
2696 reply = mpClientInterface->getParameters(output,
2697 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2698 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2699 reply.string());
2700 value = strpbrk((char *)reply.string(), "=");
2701 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002702 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002703 }
Eric Laurentd4692962014-05-05 18:13:44 -07002704 }
2705 if (((profile->mSamplingRates[0] == 0) &&
2706 (profile->mSamplingRates.size() < 2)) ||
2707 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2708 (profile->mFormats.size() < 2)) ||
2709 ((profile->mChannelMasks[0] == 0) &&
2710 (profile->mChannelMasks.size() < 2))) {
2711 ALOGW("checkOutputsForDevice() direct output missing param");
2712 mpClientInterface->closeOutput(output);
2713 output = 0;
2714 } else if (profile->mSamplingRates[0] == 0) {
2715 mpClientInterface->closeOutput(output);
2716 desc->mSamplingRate = profile->mSamplingRates[1];
2717 offloadInfo.sample_rate = desc->mSamplingRate;
2718 output = mpClientInterface->openOutput(
2719 profile->mModule->mHandle,
2720 &desc->mDevice,
2721 &desc->mSamplingRate,
2722 &desc->mFormat,
2723 &desc->mChannelMask,
2724 &desc->mLatency,
2725 desc->mFlags,
2726 &offloadInfo);
2727 }
2728
2729 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002730 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002731 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2732 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002733
Eric Laurentd4692962014-05-05 18:13:44 -07002734 // set initial stream volume for device
2735 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002736
Eric Laurentd4692962014-05-05 18:13:44 -07002737 //TODO: configure audio effect output stage here
2738
2739 // open a duplicating output thread for the new output and the primary output
2740 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2741 mPrimaryOutput);
2742 if (duplicatedOutput != 0) {
2743 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002744 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002745 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2746 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2747 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2748 dupOutputDesc->mFormat = desc->mFormat;
2749 dupOutputDesc->mChannelMask = desc->mChannelMask;
2750 dupOutputDesc->mLatency = desc->mLatency;
2751 addOutput(duplicatedOutput, dupOutputDesc);
2752 applyStreamVolumes(duplicatedOutput, device, 0, true);
2753 } else {
2754 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2755 mPrimaryOutput, output);
2756 mpClientInterface->closeOutput(output);
2757 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002758 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002759 output = 0;
2760 }
Eric Laurente552edb2014-03-10 17:42:56 -07002761 }
2762 }
2763 }
2764 if (output == 0) {
2765 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002766 profiles.removeAt(profile_index);
2767 profile_index--;
2768 } else {
2769 outputs.add(output);
2770 ALOGV("checkOutputsForDevice(): adding output %d", output);
2771 }
2772 }
2773
2774 if (profiles.isEmpty()) {
2775 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2776 return BAD_VALUE;
2777 }
Eric Laurentd4692962014-05-05 18:13:44 -07002778 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002779 // check if one opened output is not needed any more after disconnecting one device
2780 for (size_t i = 0; i < mOutputs.size(); i++) {
2781 desc = mOutputs.valueAt(i);
2782 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002783 !(desc->mProfile->mSupportedDevices.types() &
2784 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002785 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2786 outputs.add(mOutputs.keyAt(i));
2787 }
2788 }
Eric Laurentd4692962014-05-05 18:13:44 -07002789 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002790 for (size_t i = 0; i < mHwModules.size(); i++)
2791 {
2792 if (mHwModules[i]->mHandle == 0) {
2793 continue;
2794 }
2795 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2796 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002797 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002798 if (profile->mSupportedDevices.types() & device) {
2799 ALOGV("checkOutputsForDevice(): "
2800 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002801 if (profile->mSamplingRates[0] == 0) {
2802 profile->mSamplingRates.clear();
2803 profile->mSamplingRates.add(0);
2804 }
2805 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2806 profile->mFormats.clear();
2807 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2808 }
2809 if (profile->mChannelMasks[0] == 0) {
2810 profile->mChannelMasks.clear();
2811 profile->mChannelMasks.add(0);
2812 }
2813 }
2814 }
2815 }
2816 }
2817 return NO_ERROR;
2818}
2819
Eric Laurentd4692962014-05-05 18:13:44 -07002820status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2821 audio_policy_dev_state_t state,
2822 SortedVector<audio_io_handle_t>& inputs,
2823 const String8 address)
2824{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002825 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002826 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2827 // first list already open inputs that can be routed to this device
2828 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2829 desc = mInputs.valueAt(input_index);
2830 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2831 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2832 inputs.add(mInputs.keyAt(input_index));
2833 }
2834 }
2835
2836 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002837 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002838 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2839 {
2840 if (mHwModules[module_idx]->mHandle == 0) {
2841 continue;
2842 }
2843 for (size_t profile_index = 0;
2844 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2845 profile_index++)
2846 {
2847 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2848 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002849 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002850 profile_index, module_idx);
2851 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2852 }
2853 }
2854 }
2855
2856 if (profiles.isEmpty() && inputs.isEmpty()) {
2857 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2858 return BAD_VALUE;
2859 }
2860
2861 // open inputs for matching profiles if needed. Direct inputs are also opened to
2862 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2863 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2864
Eric Laurent1c333e22014-05-20 10:48:17 -07002865 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002866 // nothing to do if one input is already opened for this profile
2867 size_t input_index;
2868 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2869 desc = mInputs.valueAt(input_index);
2870 if (desc->mProfile == profile) {
2871 break;
2872 }
2873 }
2874 if (input_index != mInputs.size()) {
2875 continue;
2876 }
2877
2878 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2879 desc = new AudioInputDescriptor(profile);
2880 desc->mDevice = device;
2881
2882 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2883 &desc->mDevice,
2884 &desc->mSamplingRate,
2885 &desc->mFormat,
2886 &desc->mChannelMask);
2887
2888 if (input != 0) {
2889 if (!address.isEmpty()) {
2890 mpClientInterface->setParameters(input, addressToParameter(device, address));
2891 }
2892
2893 // Here is where we step through and resolve any "dynamic" fields
2894 String8 reply;
2895 char *value;
2896 if (profile->mSamplingRates[0] == 0) {
2897 reply = mpClientInterface->getParameters(input,
2898 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2899 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2900 reply.string());
2901 value = strpbrk((char *)reply.string(), "=");
2902 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002903 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002904 }
2905 }
2906 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2907 reply = mpClientInterface->getParameters(input,
2908 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2909 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2910 value = strpbrk((char *)reply.string(), "=");
2911 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002912 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002913 }
2914 }
2915 if (profile->mChannelMasks[0] == 0) {
2916 reply = mpClientInterface->getParameters(input,
2917 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2918 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2919 reply.string());
2920 value = strpbrk((char *)reply.string(), "=");
2921 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002922 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002923 }
2924 }
2925 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2926 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2927 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2928 ALOGW("checkInputsForDevice() direct input missing param");
2929 mpClientInterface->closeInput(input);
2930 input = 0;
2931 }
2932
2933 if (input != 0) {
2934 addInput(input, desc);
2935 }
2936 } // endif input != 0
2937
2938 if (input == 0) {
2939 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07002940 profiles.removeAt(profile_index);
2941 profile_index--;
2942 } else {
2943 inputs.add(input);
2944 ALOGV("checkInputsForDevice(): adding input %d", input);
2945 }
2946 } // end scan profiles
2947
2948 if (profiles.isEmpty()) {
2949 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2950 return BAD_VALUE;
2951 }
2952 } else {
2953 // Disconnect
2954 // check if one opened input is not needed any more after disconnecting one device
2955 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2956 desc = mInputs.valueAt(input_index);
2957 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2958 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2959 mInputs.keyAt(input_index));
2960 inputs.add(mInputs.keyAt(input_index));
2961 }
2962 }
2963 // Clear any profiles associated with the disconnected device.
2964 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2965 if (mHwModules[module_index]->mHandle == 0) {
2966 continue;
2967 }
2968 for (size_t profile_index = 0;
2969 profile_index < mHwModules[module_index]->mInputProfiles.size();
2970 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002971 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002972 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002973 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002974 profile_index, module_index);
2975 if (profile->mSamplingRates[0] == 0) {
2976 profile->mSamplingRates.clear();
2977 profile->mSamplingRates.add(0);
2978 }
2979 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2980 profile->mFormats.clear();
2981 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2982 }
2983 if (profile->mChannelMasks[0] == 0) {
2984 profile->mChannelMasks.clear();
2985 profile->mChannelMasks.add(0);
2986 }
2987 }
2988 }
2989 }
2990 } // end disconnect
2991
2992 return NO_ERROR;
2993}
2994
2995
Eric Laurente0720872014-03-11 09:30:41 -07002996void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002997{
2998 ALOGV("closeOutput(%d)", output);
2999
Eric Laurent1f2f2232014-06-02 12:01:23 -07003000 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003001 if (outputDesc == NULL) {
3002 ALOGW("closeOutput() unknown output %d", output);
3003 return;
3004 }
3005
3006 // look for duplicated outputs connected to the output being removed.
3007 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003008 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003009 if (dupOutputDesc->isDuplicated() &&
3010 (dupOutputDesc->mOutput1 == outputDesc ||
3011 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003012 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003013 if (dupOutputDesc->mOutput1 == outputDesc) {
3014 outputDesc2 = dupOutputDesc->mOutput2;
3015 } else {
3016 outputDesc2 = dupOutputDesc->mOutput1;
3017 }
3018 // As all active tracks on duplicated output will be deleted,
3019 // and as they were also referenced on the other output, the reference
3020 // count for their stream type must be adjusted accordingly on
3021 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003022 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003023 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003024 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003025 }
3026 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3027 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3028
3029 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003030 mOutputs.removeItem(duplicatedOutput);
3031 }
3032 }
3033
3034 AudioParameter param;
3035 param.add(String8("closing"), String8("true"));
3036 mpClientInterface->setParameters(output, param.toString());
3037
3038 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003039 mOutputs.removeItem(output);
3040 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003041 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003042}
3043
Eric Laurente0720872014-03-11 09:30:41 -07003044SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003045 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003046{
3047 SortedVector<audio_io_handle_t> outputs;
3048
3049 ALOGVV("getOutputsForDevice() device %04x", device);
3050 for (size_t i = 0; i < openOutputs.size(); i++) {
3051 ALOGVV("output %d isDuplicated=%d device=%04x",
3052 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3053 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3054 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3055 outputs.add(openOutputs.keyAt(i));
3056 }
3057 }
3058 return outputs;
3059}
3060
Eric Laurente0720872014-03-11 09:30:41 -07003061bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003062 SortedVector<audio_io_handle_t>& outputs2)
3063{
3064 if (outputs1.size() != outputs2.size()) {
3065 return false;
3066 }
3067 for (size_t i = 0; i < outputs1.size(); i++) {
3068 if (outputs1[i] != outputs2[i]) {
3069 return false;
3070 }
3071 }
3072 return true;
3073}
3074
Eric Laurente0720872014-03-11 09:30:41 -07003075void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003076{
3077 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3078 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3079 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3080 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3081
3082 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3083 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3084 strategy, srcOutputs[0], dstOutputs[0]);
3085 // mute strategy while moving tracks from one output to another
3086 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003087 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003088 if (desc->isStrategyActive(strategy)) {
3089 setStrategyMute(strategy, true, srcOutputs[i]);
3090 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3091 }
3092 }
3093
3094 // Move effects associated to this strategy from previous output to new output
3095 if (strategy == STRATEGY_MEDIA) {
3096 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3097 SortedVector<audio_io_handle_t> moved;
3098 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003099 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3100 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3101 effectDesc->mIo != fxOutput) {
3102 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003103 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3104 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003105 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003106 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003107 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003108 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003109 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003110 }
3111 }
3112 }
3113 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003114 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3115 if (getStrategy((audio_stream_type_t)i) == strategy) {
3116 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003117 }
3118 }
3119 }
3120}
3121
Eric Laurente0720872014-03-11 09:30:41 -07003122void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003123{
3124 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3125 checkOutputForStrategy(STRATEGY_PHONE);
3126 checkOutputForStrategy(STRATEGY_SONIFICATION);
3127 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3128 checkOutputForStrategy(STRATEGY_MEDIA);
3129 checkOutputForStrategy(STRATEGY_DTMF);
3130}
3131
Eric Laurente0720872014-03-11 09:30:41 -07003132audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003133{
Eric Laurente552edb2014-03-10 17:42:56 -07003134 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003135 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003136 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3137 return mOutputs.keyAt(i);
3138 }
3139 }
3140
3141 return 0;
3142}
3143
Eric Laurente0720872014-03-11 09:30:41 -07003144void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003145{
Eric Laurente552edb2014-03-10 17:42:56 -07003146 audio_io_handle_t a2dpOutput = getA2dpOutput();
3147 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003148 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003149 return;
3150 }
3151
Eric Laurent3a4311c2014-03-17 12:00:47 -07003152 bool isScoConnected =
3153 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003154 // suspend A2DP output if:
3155 // (NOT already suspended) &&
3156 // ((SCO device is connected &&
3157 // (forced usage for communication || for record is SCO))) ||
3158 // (phone state is ringing || in call)
3159 //
3160 // restore A2DP output if:
3161 // (Already suspended) &&
3162 // ((SCO device is NOT connected ||
3163 // (forced usage NOT for communication && NOT for record is SCO))) &&
3164 // (phone state is NOT ringing && NOT in call)
3165 //
3166 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003167 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003168 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3169 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3170 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3171 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003172
3173 mpClientInterface->restoreOutput(a2dpOutput);
3174 mA2dpSuspended = false;
3175 }
3176 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003177 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003178 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3179 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3180 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3181 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003182
3183 mpClientInterface->suspendOutput(a2dpOutput);
3184 mA2dpSuspended = true;
3185 }
3186 }
3187}
3188
Eric Laurent1c333e22014-05-20 10:48:17 -07003189audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003190{
3191 audio_devices_t device = AUDIO_DEVICE_NONE;
3192
Eric Laurent1f2f2232014-06-02 12:01:23 -07003193 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003194
3195 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3196 if (index >= 0) {
3197 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3198 if (patchDesc->mUid != mUidCached) {
3199 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3200 outputDesc->device(), outputDesc->mPatchHandle);
3201 return outputDesc->device();
3202 }
3203 }
3204
Eric Laurente552edb2014-03-10 17:42:56 -07003205 // check the following by order of priority to request a routing change if necessary:
3206 // 1: the strategy enforced audible is active on the output:
3207 // use device for strategy enforced audible
3208 // 2: we are in call or the strategy phone is active on the output:
3209 // use device for strategy phone
3210 // 3: the strategy sonification is active on the output:
3211 // use device for strategy sonification
3212 // 4: the strategy "respectful" sonification is active on the output:
3213 // use device for strategy "respectful" sonification
3214 // 5: the strategy media is active on the output:
3215 // use device for strategy media
3216 // 6: the strategy DTMF is active on the output:
3217 // use device for strategy DTMF
3218 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3219 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3220 } else if (isInCall() ||
3221 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3222 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3223 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3224 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3225 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3226 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3227 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3228 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3229 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3230 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3231 }
3232
Eric Laurent1c333e22014-05-20 10:48:17 -07003233 ALOGV("getNewOutputDevice() selected device %x", device);
3234 return device;
3235}
3236
3237audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3238{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003239 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003240
3241 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3242 if (index >= 0) {
3243 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3244 if (patchDesc->mUid != mUidCached) {
3245 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3246 inputDesc->mDevice, inputDesc->mPatchHandle);
3247 return inputDesc->mDevice;
3248 }
3249 }
3250
Eric Laurent1c333e22014-05-20 10:48:17 -07003251 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3252
3253 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003254 return device;
3255}
3256
Eric Laurente0720872014-03-11 09:30:41 -07003257uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003258 return (uint32_t)getStrategy(stream);
3259}
3260
Eric Laurente0720872014-03-11 09:30:41 -07003261audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003262 // By checking the range of stream before calling getStrategy, we avoid
3263 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3264 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003265 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003266 return AUDIO_DEVICE_NONE;
3267 }
3268 audio_devices_t devices;
3269 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3270 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3271 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3272 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003273 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003274 if (outputDesc->isStrategyActive(strategy)) {
3275 devices = outputDesc->device();
3276 break;
3277 }
Eric Laurente552edb2014-03-10 17:42:56 -07003278 }
3279 return devices;
3280}
3281
Eric Laurente0720872014-03-11 09:30:41 -07003282AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003283 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003284 // stream to strategy mapping
3285 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003286 case AUDIO_STREAM_VOICE_CALL:
3287 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003288 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003289 case AUDIO_STREAM_RING:
3290 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003291 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003292 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003293 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003294 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003295 return STRATEGY_DTMF;
3296 default:
3297 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003298 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003299 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3300 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003301 case AUDIO_STREAM_TTS:
3302 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003303 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003304 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003305 return STRATEGY_ENFORCED_AUDIBLE;
3306 }
3307}
3308
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003309uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3310 // flags to strategy mapping
3311 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3312 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3313 }
3314
3315 // usage to strategy mapping
3316 switch (attr->usage) {
3317 case AUDIO_USAGE_MEDIA:
3318 case AUDIO_USAGE_GAME:
3319 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3320 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3321 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3322 return (uint32_t) STRATEGY_MEDIA;
3323
3324 case AUDIO_USAGE_VOICE_COMMUNICATION:
3325 return (uint32_t) STRATEGY_PHONE;
3326
3327 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3328 return (uint32_t) STRATEGY_DTMF;
3329
3330 case AUDIO_USAGE_ALARM:
3331 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3332 return (uint32_t) STRATEGY_SONIFICATION;
3333
3334 case AUDIO_USAGE_NOTIFICATION:
3335 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3336 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3337 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3338 case AUDIO_USAGE_NOTIFICATION_EVENT:
3339 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3340
3341 case AUDIO_USAGE_UNKNOWN:
3342 default:
3343 return (uint32_t) STRATEGY_MEDIA;
3344 }
3345}
3346
Eric Laurente0720872014-03-11 09:30:41 -07003347void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003348 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003349 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003350 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3351 updateDevicesAndOutputs();
3352 break;
3353 default:
3354 break;
3355 }
3356}
3357
Eric Laurente0720872014-03-11 09:30:41 -07003358audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003359 bool fromCache)
3360{
3361 uint32_t device = AUDIO_DEVICE_NONE;
3362
3363 if (fromCache) {
3364 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3365 strategy, mDeviceForStrategy[strategy]);
3366 return mDeviceForStrategy[strategy];
3367 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003368 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003369 switch (strategy) {
3370
3371 case STRATEGY_SONIFICATION_RESPECTFUL:
3372 if (isInCall()) {
3373 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003374 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003375 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3376 // while media is playing on a remote device, use the the sonification behavior.
3377 // Note that we test this usecase before testing if media is playing because
3378 // the isStreamActive() method only informs about the activity of a stream, not
3379 // if it's for local playback. Note also that we use the same delay between both tests
3380 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003381 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003382 // while media is playing (or has recently played), use the same device
3383 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3384 } else {
3385 // when media is not playing anymore, fall back on the sonification behavior
3386 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3387 }
3388
3389 break;
3390
3391 case STRATEGY_DTMF:
3392 if (!isInCall()) {
3393 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3394 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3395 break;
3396 }
3397 // when in call, DTMF and PHONE strategies follow the same rules
3398 // FALL THROUGH
3399
3400 case STRATEGY_PHONE:
3401 // for phone strategy, we first consider the forced use and then the available devices by order
3402 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003403 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3404 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003405 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003406 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003407 if (device) break;
3408 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003409 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003410 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003411 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003412 if (device) break;
3413 // if SCO device is requested but no SCO device is available, fall back to default case
3414 // FALL THROUGH
3415
3416 default: // FORCE_NONE
3417 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003418 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003419 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003420 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003421 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003422 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003423 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003424 if (device) break;
3425 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003426 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003427 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003428 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003429 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003430 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003431 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003432 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003433 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003434 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003435 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003436 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003437 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003438 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003439 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003440 if (device) break;
3441 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003442 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003443 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003444 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003445 if (device == AUDIO_DEVICE_NONE) {
3446 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3447 }
3448 break;
3449
Eric Laurent3b73df72014-03-11 09:06:29 -07003450 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003451 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3452 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003453 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003454 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003455 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003456 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003457 if (device) break;
3458 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003459 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003460 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003461 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003462 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003463 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003464 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003465 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003466 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003467 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003468 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003469 if (device) break;
3470 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003471 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003472 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003473 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003474 if (device == AUDIO_DEVICE_NONE) {
3475 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3476 }
3477 break;
3478 }
3479 break;
3480
3481 case STRATEGY_SONIFICATION:
3482
3483 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3484 // handleIncallSonification().
3485 if (isInCall()) {
3486 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3487 break;
3488 }
3489 // FALL THROUGH
3490
3491 case STRATEGY_ENFORCED_AUDIBLE:
3492 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3493 // except:
3494 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3495 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3496
3497 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003498 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003499 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003500 if (device == AUDIO_DEVICE_NONE) {
3501 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3502 }
3503 }
3504 // The second device used for sonification is the same as the device used by media strategy
3505 // FALL THROUGH
3506
3507 case STRATEGY_MEDIA: {
3508 uint32_t device2 = AUDIO_DEVICE_NONE;
3509 if (strategy != STRATEGY_SONIFICATION) {
3510 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003511 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003512 }
3513 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003514 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003515 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003516 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003517 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003518 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003519 }
3520 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003521 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003522 }
3523 }
3524 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003525 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003526 }
3527 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003528 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003529 }
3530 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003531 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003532 }
3533 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003534 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003535 }
3536 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003537 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003538 }
3539 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3540 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003541 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003542 }
3543 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003544 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003545 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003546 }
3547 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003548 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003549 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003550 int device3 = AUDIO_DEVICE_NONE;
3551 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang0c943092014-07-08 22:11:24 +09003552 // ARC, SPDIF and LINE can co-exist with others.
3553 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3554 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
3555 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003556 }
Eric Laurente552edb2014-03-10 17:42:56 -07003557
Jungshik Jang839e4f32014-06-26 17:23:40 +09003558 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003559 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3560 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3561 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003562
Eric Laurente552edb2014-03-10 17:42:56 -07003563 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003564 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003565 if (device == AUDIO_DEVICE_NONE) {
3566 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3567 }
3568 } break;
3569
3570 default:
3571 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3572 break;
3573 }
3574
3575 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3576 return device;
3577}
3578
Eric Laurente0720872014-03-11 09:30:41 -07003579void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003580{
3581 for (int i = 0; i < NUM_STRATEGIES; i++) {
3582 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3583 }
3584 mPreviousOutputs = mOutputs;
3585}
3586
Eric Laurent1f2f2232014-06-02 12:01:23 -07003587uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003588 audio_devices_t prevDevice,
3589 uint32_t delayMs)
3590{
3591 // mute/unmute strategies using an incompatible device combination
3592 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3593 // if unmuting, unmute only after the specified delay
3594 if (outputDesc->isDuplicated()) {
3595 return 0;
3596 }
3597
3598 uint32_t muteWaitMs = 0;
3599 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003600 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003601
3602 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3603 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3604 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3605 bool doMute = false;
3606
3607 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3608 doMute = true;
3609 outputDesc->mStrategyMutedByDevice[i] = true;
3610 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3611 doMute = true;
3612 outputDesc->mStrategyMutedByDevice[i] = false;
3613 }
Eric Laurent99401132014-05-07 19:48:15 -07003614 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003615 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003616 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003617 // skip output if it does not share any device with current output
3618 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3619 == AUDIO_DEVICE_NONE) {
3620 continue;
3621 }
3622 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3623 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3624 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3625 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3626 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003627 if (mute) {
3628 // FIXME: should not need to double latency if volume could be applied
3629 // immediately by the audioflinger mixer. We must account for the delay
3630 // between now and the next time the audioflinger thread for this output
3631 // will process a buffer (which corresponds to one buffer size,
3632 // usually 1/2 or 1/4 of the latency).
3633 if (muteWaitMs < desc->latency() * 2) {
3634 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003635 }
3636 }
3637 }
3638 }
3639 }
3640 }
3641
Eric Laurent99401132014-05-07 19:48:15 -07003642 // temporary mute output if device selection changes to avoid volume bursts due to
3643 // different per device volumes
3644 if (outputDesc->isActive() && (device != prevDevice)) {
3645 if (muteWaitMs < outputDesc->latency() * 2) {
3646 muteWaitMs = outputDesc->latency() * 2;
3647 }
3648 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3649 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003650 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003651 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003652 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003653 muteWaitMs *2, device);
3654 }
3655 }
3656 }
3657
Eric Laurente552edb2014-03-10 17:42:56 -07003658 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3659 if (muteWaitMs > delayMs) {
3660 muteWaitMs -= delayMs;
3661 usleep(muteWaitMs * 1000);
3662 return muteWaitMs;
3663 }
3664 return 0;
3665}
3666
Eric Laurente0720872014-03-11 09:30:41 -07003667uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003668 audio_devices_t device,
3669 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003670 int delayMs,
3671 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003672{
3673 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003674 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003675 AudioParameter param;
3676 uint32_t muteWaitMs;
3677
3678 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003679 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3680 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003681 return muteWaitMs;
3682 }
3683 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3684 // output profile
3685 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003686 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003687 return 0;
3688 }
3689
3690 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003691 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003692
3693 audio_devices_t prevDevice = outputDesc->mDevice;
3694
3695 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3696
3697 if (device != AUDIO_DEVICE_NONE) {
3698 outputDesc->mDevice = device;
3699 }
3700 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3701
3702 // Do not change the routing if:
3703 // - the requested device is AUDIO_DEVICE_NONE
3704 // - the requested device is the same as current device and force is not specified.
3705 // Doing this check here allows the caller to call setOutputDevice() without conditions
3706 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3707 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3708 return muteWaitMs;
3709 }
3710
3711 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003712
Eric Laurente552edb2014-03-10 17:42:56 -07003713 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003714 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003715 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003716 } else {
3717 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3718 if (!deviceList.isEmpty()) {
3719 struct audio_patch patch;
3720 outputDesc->toAudioPortConfig(&patch.sources[0]);
3721 patch.num_sources = 1;
3722 patch.num_sinks = 0;
3723 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3724 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003725 patch.num_sinks++;
3726 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003727 ssize_t index;
3728 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3729 index = mAudioPatches.indexOfKey(*patchHandle);
3730 } else {
3731 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3732 }
3733 sp< AudioPatch> patchDesc;
3734 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3735 if (index >= 0) {
3736 patchDesc = mAudioPatches.valueAt(index);
3737 afPatchHandle = patchDesc->mAfPatchHandle;
3738 }
3739
Eric Laurent1c333e22014-05-20 10:48:17 -07003740 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003741 &afPatchHandle,
3742 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003743 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3744 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003745 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003746 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003747 if (index < 0) {
3748 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3749 &patch, mUidCached);
3750 addAudioPatch(patchDesc->mHandle, patchDesc);
3751 } else {
3752 patchDesc->mPatch = patch;
3753 }
3754 patchDesc->mAfPatchHandle = afPatchHandle;
3755 patchDesc->mUid = mUidCached;
3756 if (patchHandle) {
3757 *patchHandle = patchDesc->mHandle;
3758 }
3759 outputDesc->mPatchHandle = patchDesc->mHandle;
3760 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003761 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003762 }
3763 }
3764 }
Eric Laurente552edb2014-03-10 17:42:56 -07003765
3766 // update stream volumes according to new device
3767 applyStreamVolumes(output, device, delayMs);
3768
3769 return muteWaitMs;
3770}
3771
Eric Laurent1c333e22014-05-20 10:48:17 -07003772status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003773 int delayMs,
3774 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003775{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003776 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003777 ssize_t index;
3778 if (patchHandle) {
3779 index = mAudioPatches.indexOfKey(*patchHandle);
3780 } else {
3781 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3782 }
3783 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003784 return INVALID_OPERATION;
3785 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003786 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3787 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003788 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3789 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003790 removeAudioPatch(patchDesc->mHandle);
3791 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003792 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003793 return status;
3794}
3795
3796status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3797 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003798 bool force,
3799 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003800{
3801 status_t status = NO_ERROR;
3802
Eric Laurent1f2f2232014-06-02 12:01:23 -07003803 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003804 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3805 inputDesc->mDevice = device;
3806
3807 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3808 if (!deviceList.isEmpty()) {
3809 struct audio_patch patch;
3810 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3811 patch.num_sinks = 1;
3812 //only one input device for now
3813 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003814 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003815 ssize_t index;
3816 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3817 index = mAudioPatches.indexOfKey(*patchHandle);
3818 } else {
3819 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3820 }
3821 sp< AudioPatch> patchDesc;
3822 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3823 if (index >= 0) {
3824 patchDesc = mAudioPatches.valueAt(index);
3825 afPatchHandle = patchDesc->mAfPatchHandle;
3826 }
3827
Eric Laurent1c333e22014-05-20 10:48:17 -07003828 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003829 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003830 0);
3831 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003832 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003833 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003834 if (index < 0) {
3835 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3836 &patch, mUidCached);
3837 addAudioPatch(patchDesc->mHandle, patchDesc);
3838 } else {
3839 patchDesc->mPatch = patch;
3840 }
3841 patchDesc->mAfPatchHandle = afPatchHandle;
3842 patchDesc->mUid = mUidCached;
3843 if (patchHandle) {
3844 *patchHandle = patchDesc->mHandle;
3845 }
3846 inputDesc->mPatchHandle = patchDesc->mHandle;
3847 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003848 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003849 }
3850 }
3851 }
3852 return status;
3853}
3854
Eric Laurent6a94d692014-05-20 11:18:06 -07003855status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3856 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003857{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003858 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003859 ssize_t index;
3860 if (patchHandle) {
3861 index = mAudioPatches.indexOfKey(*patchHandle);
3862 } else {
3863 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3864 }
3865 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003866 return INVALID_OPERATION;
3867 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003868 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3869 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003870 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3871 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003872 removeAudioPatch(patchDesc->mHandle);
3873 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003874 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003875 return status;
3876}
3877
3878sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003879 uint32_t samplingRate,
3880 audio_format_t format,
3881 audio_channel_mask_t channelMask)
3882{
3883 // Choose an input profile based on the requested capture parameters: select the first available
3884 // profile supporting all requested parameters.
3885
3886 for (size_t i = 0; i < mHwModules.size(); i++)
3887 {
3888 if (mHwModules[i]->mHandle == 0) {
3889 continue;
3890 }
3891 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3892 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003893 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003894 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003895 if (profile->isCompatibleProfile(device, samplingRate, format,
3896 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3897 return profile;
3898 }
3899 }
3900 }
3901 return NULL;
3902}
3903
Eric Laurente0720872014-03-11 09:30:41 -07003904audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003905{
3906 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003907 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3908 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003909 switch (inputSource) {
3910 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003911 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003912 device = AUDIO_DEVICE_IN_VOICE_CALL;
3913 break;
3914 }
3915 // FALL THROUGH
3916
3917 case AUDIO_SOURCE_DEFAULT:
3918 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003919 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3920 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3921 break;
3922 }
3923 // FALL THROUGH
3924
Eric Laurente552edb2014-03-10 17:42:56 -07003925 case AUDIO_SOURCE_VOICE_RECOGNITION:
3926 case AUDIO_SOURCE_HOTWORD:
3927 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003928 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003929 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003930 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003931 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003932 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003933 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3934 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003935 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003936 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3937 }
3938 break;
3939 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003940 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003941 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003942 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003943 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3944 }
3945 break;
3946 case AUDIO_SOURCE_VOICE_DOWNLINK:
3947 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003948 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003949 device = AUDIO_DEVICE_IN_VOICE_CALL;
3950 }
3951 break;
3952 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003953 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003954 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3955 }
3956 break;
3957 default:
3958 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3959 break;
3960 }
3961 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3962 return device;
3963}
3964
Eric Laurente0720872014-03-11 09:30:41 -07003965bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003966{
3967 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3968 device &= ~AUDIO_DEVICE_BIT_IN;
3969 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3970 return true;
3971 }
3972 return false;
3973}
3974
Eric Laurente0720872014-03-11 09:30:41 -07003975audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003976{
3977 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003978 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003979 if ((input_descriptor->mRefCount > 0)
3980 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3981 return mInputs.keyAt(i);
3982 }
3983 }
3984 return 0;
3985}
3986
3987
Eric Laurente0720872014-03-11 09:30:41 -07003988audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003989{
3990 if (device == AUDIO_DEVICE_NONE) {
3991 // this happens when forcing a route update and no track is active on an output.
3992 // In this case the returned category is not important.
3993 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003994 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003995 // Multiple device selection is either:
3996 // - speaker + one other device: give priority to speaker in this case.
3997 // - one A2DP device + another device: happens with duplicated output. In this case
3998 // retain the device on the A2DP output as the other must not correspond to an active
3999 // selection if not the speaker.
4000 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4001 device = AUDIO_DEVICE_OUT_SPEAKER;
4002 } else {
4003 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4004 }
4005 }
4006
Eric Laurent3b73df72014-03-11 09:06:29 -07004007 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004008 "getDeviceForVolume() invalid device combination: %08x",
4009 device);
4010
4011 return device;
4012}
4013
Eric Laurente0720872014-03-11 09:30:41 -07004014AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004015{
4016 switch(getDeviceForVolume(device)) {
4017 case AUDIO_DEVICE_OUT_EARPIECE:
4018 return DEVICE_CATEGORY_EARPIECE;
4019 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4020 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4021 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4022 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4023 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4024 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4025 return DEVICE_CATEGORY_HEADSET;
4026 case AUDIO_DEVICE_OUT_SPEAKER:
4027 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4028 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4029 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4030 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4031 case AUDIO_DEVICE_OUT_USB_DEVICE:
4032 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4033 default:
4034 return DEVICE_CATEGORY_SPEAKER;
4035 }
4036}
4037
Eric Laurente0720872014-03-11 09:30:41 -07004038float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004039 int indexInUi)
4040{
4041 device_category deviceCategory = getDeviceCategory(device);
4042 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4043
4044 // the volume index in the UI is relative to the min and max volume indices for this stream type
4045 int nbSteps = 1 + curve[VOLMAX].mIndex -
4046 curve[VOLMIN].mIndex;
4047 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4048 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4049
4050 // find what part of the curve this index volume belongs to, or if it's out of bounds
4051 int segment = 0;
4052 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4053 return 0.0f;
4054 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4055 segment = 0;
4056 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4057 segment = 1;
4058 } else if (volIdx <= curve[VOLMAX].mIndex) {
4059 segment = 2;
4060 } else { // out of bounds
4061 return 1.0f;
4062 }
4063
4064 // linear interpolation in the attenuation table in dB
4065 float decibels = curve[segment].mDBAttenuation +
4066 ((float)(volIdx - curve[segment].mIndex)) *
4067 ( (curve[segment+1].mDBAttenuation -
4068 curve[segment].mDBAttenuation) /
4069 ((float)(curve[segment+1].mIndex -
4070 curve[segment].mIndex)) );
4071
4072 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4073
4074 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4075 curve[segment].mIndex, volIdx,
4076 curve[segment+1].mIndex,
4077 curve[segment].mDBAttenuation,
4078 decibels,
4079 curve[segment+1].mDBAttenuation,
4080 amplification);
4081
4082 return amplification;
4083}
4084
Eric Laurente0720872014-03-11 09:30:41 -07004085const AudioPolicyManager::VolumeCurvePoint
4086 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004087 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4088};
4089
Eric Laurente0720872014-03-11 09:30:41 -07004090const AudioPolicyManager::VolumeCurvePoint
4091 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004092 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4093};
4094
Eric Laurente0720872014-03-11 09:30:41 -07004095const AudioPolicyManager::VolumeCurvePoint
4096 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004097 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4098};
4099
Eric Laurente0720872014-03-11 09:30:41 -07004100const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004101 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004102 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004103};
4104
4105const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004106 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004107 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4108};
4109
Eric Laurente0720872014-03-11 09:30:41 -07004110const AudioPolicyManager::VolumeCurvePoint
4111 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004112 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4113};
4114
4115// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4116// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4117// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4118// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4119
Eric Laurente0720872014-03-11 09:30:41 -07004120const AudioPolicyManager::VolumeCurvePoint
4121 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004122 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4123};
4124
Eric Laurente0720872014-03-11 09:30:41 -07004125const AudioPolicyManager::VolumeCurvePoint
4126 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004127 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4128};
4129
Eric Laurente0720872014-03-11 09:30:41 -07004130const AudioPolicyManager::VolumeCurvePoint
4131 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004132 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4133};
4134
Eric Laurente0720872014-03-11 09:30:41 -07004135const AudioPolicyManager::VolumeCurvePoint
4136 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004137 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4138};
4139
Eric Laurente0720872014-03-11 09:30:41 -07004140const AudioPolicyManager::VolumeCurvePoint
4141 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004142 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4143};
4144
Eric Laurente0720872014-03-11 09:30:41 -07004145const AudioPolicyManager::VolumeCurvePoint
4146 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4147 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004148 { // AUDIO_STREAM_VOICE_CALL
4149 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4150 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4151 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4152 },
4153 { // AUDIO_STREAM_SYSTEM
4154 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4155 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4156 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4157 },
4158 { // AUDIO_STREAM_RING
4159 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4160 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4161 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4162 },
4163 { // AUDIO_STREAM_MUSIC
4164 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4165 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4166 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4167 },
4168 { // AUDIO_STREAM_ALARM
4169 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4170 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4171 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4172 },
4173 { // AUDIO_STREAM_NOTIFICATION
4174 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4175 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4176 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4177 },
4178 { // AUDIO_STREAM_BLUETOOTH_SCO
4179 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4180 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4181 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4182 },
4183 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4184 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4185 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4186 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4187 },
4188 { // AUDIO_STREAM_DTMF
4189 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4190 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4191 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4192 },
4193 { // AUDIO_STREAM_TTS
4194 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4195 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4196 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4197 },
4198};
4199
Eric Laurente0720872014-03-11 09:30:41 -07004200void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004201{
4202 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4203 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4204 mStreams[i].mVolumeCurve[j] =
4205 sVolumeProfiles[i][j];
4206 }
4207 }
4208
4209 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4210 if (mSpeakerDrcEnabled) {
4211 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4212 sDefaultSystemVolumeCurveDrc;
4213 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4214 sSpeakerSonificationVolumeCurveDrc;
4215 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4216 sSpeakerSonificationVolumeCurveDrc;
4217 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4218 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004219 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4220 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004221 }
4222}
4223
Eric Laurente0720872014-03-11 09:30:41 -07004224float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004225 int index,
4226 audio_io_handle_t output,
4227 audio_devices_t device)
4228{
4229 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004230 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004231 StreamDescriptor &streamDesc = mStreams[stream];
4232
4233 if (device == AUDIO_DEVICE_NONE) {
4234 device = outputDesc->device();
4235 }
4236
4237 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004238 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004239 index != mStreams[stream].mIndexMin &&
4240 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
Paul McLeanb919dd32014-06-26 13:16:44 -07004241 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004242 return 1.0;
4243 }
4244
4245 volume = volIndexToAmpl(device, streamDesc, index);
4246
4247 // if a headset is connected, apply the following rules to ring tones and notifications
4248 // to avoid sound level bursts in user's ears:
4249 // - always attenuate ring tones and notifications volume by 6dB
4250 // - if music is playing, always limit the volume to current music volume,
4251 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004252 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004253 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4254 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4255 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4256 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4257 ((stream_strategy == STRATEGY_SONIFICATION)
4258 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004259 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004260 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004261 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004262 streamDesc.mCanBeMuted) {
4263 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4264 // when the phone is ringing we must consider that music could have been paused just before
4265 // by the music application and behave as if music was active if the last music track was
4266 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004267 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004268 mLimitRingtoneVolume) {
4269 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004270 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4271 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004272 output,
4273 musicDevice);
4274 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4275 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4276 if (volume > minVol) {
4277 volume = minVol;
4278 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4279 }
4280 }
4281 }
4282
4283 return volume;
4284}
4285
Eric Laurente0720872014-03-11 09:30:41 -07004286status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004287 int index,
4288 audio_io_handle_t output,
4289 audio_devices_t device,
4290 int delayMs,
4291 bool force)
4292{
4293
4294 // do not change actual stream volume if the stream is muted
4295 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4296 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4297 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4298 return NO_ERROR;
4299 }
4300
4301 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004302 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4303 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4304 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4305 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004306 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004307 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004308 return INVALID_OPERATION;
4309 }
4310
4311 float volume = computeVolume(stream, index, output, device);
4312 // We actually change the volume if:
4313 // - the float value returned by computeVolume() changed
4314 // - the force flag is set
4315 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4316 force) {
4317 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4318 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4319 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4320 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004321 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4322 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004323 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004324 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004325 }
4326
Eric Laurent3b73df72014-03-11 09:06:29 -07004327 if (stream == AUDIO_STREAM_VOICE_CALL ||
4328 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004329 float voiceVolume;
4330 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004331 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004332 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4333 } else {
4334 voiceVolume = 1.0;
4335 }
4336
4337 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4338 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4339 mLastVoiceVolume = voiceVolume;
4340 }
4341 }
4342
4343 return NO_ERROR;
4344}
4345
Eric Laurente0720872014-03-11 09:30:41 -07004346void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004347 audio_devices_t device,
4348 int delayMs,
4349 bool force)
4350{
4351 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4352
Eric Laurent3b73df72014-03-11 09:06:29 -07004353 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4354 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004355 mStreams[stream].getVolumeIndex(device),
4356 output,
4357 device,
4358 delayMs,
4359 force);
4360 }
4361}
4362
Eric Laurente0720872014-03-11 09:30:41 -07004363void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004364 bool on,
4365 audio_io_handle_t output,
4366 int delayMs,
4367 audio_devices_t device)
4368{
4369 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004370 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4371 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4372 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004373 }
4374 }
4375}
4376
Eric Laurente0720872014-03-11 09:30:41 -07004377void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004378 bool on,
4379 audio_io_handle_t output,
4380 int delayMs,
4381 audio_devices_t device)
4382{
4383 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004384 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004385 if (device == AUDIO_DEVICE_NONE) {
4386 device = outputDesc->device();
4387 }
4388
4389 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4390 stream, on, output, outputDesc->mMuteCount[stream], device);
4391
4392 if (on) {
4393 if (outputDesc->mMuteCount[stream] == 0) {
4394 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004395 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4396 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004397 checkAndSetVolume(stream, 0, output, device, delayMs);
4398 }
4399 }
4400 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4401 outputDesc->mMuteCount[stream]++;
4402 } else {
4403 if (outputDesc->mMuteCount[stream] == 0) {
4404 ALOGV("setStreamMute() unmuting non muted stream!");
4405 return;
4406 }
4407 if (--outputDesc->mMuteCount[stream] == 0) {
4408 checkAndSetVolume(stream,
4409 streamDesc.getVolumeIndex(device),
4410 output,
4411 device,
4412 delayMs);
4413 }
4414 }
4415}
4416
Eric Laurente0720872014-03-11 09:30:41 -07004417void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004418 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004419{
4420 // if the stream pertains to sonification strategy and we are in call we must
4421 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4422 // in the device used for phone strategy and play the tone if the selected device does not
4423 // interfere with the device used for phone strategy
4424 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4425 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004426 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004427 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4428 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004429 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004430 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4431 stream, starting, outputDesc->mDevice, stateChange);
4432 if (outputDesc->mRefCount[stream]) {
4433 int muteCount = 1;
4434 if (stateChange) {
4435 muteCount = outputDesc->mRefCount[stream];
4436 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004437 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004438 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4439 for (int i = 0; i < muteCount; i++) {
4440 setStreamMute(stream, starting, mPrimaryOutput);
4441 }
4442 } else {
4443 ALOGV("handleIncallSonification() high visibility");
4444 if (outputDesc->device() &
4445 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4446 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4447 for (int i = 0; i < muteCount; i++) {
4448 setStreamMute(stream, starting, mPrimaryOutput);
4449 }
4450 }
4451 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004452 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4453 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004454 } else {
4455 mpClientInterface->stopTone();
4456 }
4457 }
4458 }
4459 }
4460}
4461
Eric Laurente0720872014-03-11 09:30:41 -07004462bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004463{
4464 return isStateInCall(mPhoneState);
4465}
4466
Eric Laurente0720872014-03-11 09:30:41 -07004467bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004468 return ((state == AUDIO_MODE_IN_CALL) ||
4469 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004470}
4471
Eric Laurente0720872014-03-11 09:30:41 -07004472uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004473{
4474 return MAX_EFFECTS_CPU_LOAD;
4475}
4476
Eric Laurente0720872014-03-11 09:30:41 -07004477uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004478{
4479 return MAX_EFFECTS_MEMORY;
4480}
4481
Eric Laurent6a94d692014-05-20 11:18:06 -07004482
Eric Laurente552edb2014-03-10 17:42:56 -07004483// --- AudioOutputDescriptor class implementation
4484
Eric Laurente0720872014-03-11 09:30:41 -07004485AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004486 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004487 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004488 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004489 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4490{
4491 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004492 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004493 mRefCount[i] = 0;
4494 mCurVolume[i] = -1.0;
4495 mMuteCount[i] = 0;
4496 mStopTime[i] = 0;
4497 }
4498 for (int i = 0; i < NUM_STRATEGIES; i++) {
4499 mStrategyMutedByDevice[i] = false;
4500 }
4501 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004502 mAudioPort = profile;
Eric Laurente552edb2014-03-10 17:42:56 -07004503 mSamplingRate = profile->mSamplingRates[0];
4504 mFormat = profile->mFormats[0];
4505 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004506 if (profile->mGains.size() > 0) {
4507 profile->mGains[0]->getDefaultConfig(&mGain);
4508 }
Eric Laurente552edb2014-03-10 17:42:56 -07004509 mFlags = profile->mFlags;
4510 }
4511}
4512
Eric Laurente0720872014-03-11 09:30:41 -07004513audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004514{
4515 if (isDuplicated()) {
4516 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4517 } else {
4518 return mDevice;
4519 }
4520}
4521
Eric Laurente0720872014-03-11 09:30:41 -07004522uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004523{
4524 if (isDuplicated()) {
4525 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4526 } else {
4527 return mLatency;
4528 }
4529}
4530
Eric Laurente0720872014-03-11 09:30:41 -07004531bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004532 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004533{
4534 if (isDuplicated()) {
4535 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4536 } else if (outputDesc->isDuplicated()){
4537 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4538 } else {
4539 return (mProfile->mModule == outputDesc->mProfile->mModule);
4540 }
4541}
4542
Eric Laurente0720872014-03-11 09:30:41 -07004543void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004544 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004545{
4546 // forward usage count change to attached outputs
4547 if (isDuplicated()) {
4548 mOutput1->changeRefCount(stream, delta);
4549 mOutput2->changeRefCount(stream, delta);
4550 }
4551 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004552 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4553 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004554 mRefCount[stream] = 0;
4555 return;
4556 }
4557 mRefCount[stream] += delta;
4558 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4559}
4560
Eric Laurente0720872014-03-11 09:30:41 -07004561audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004562{
4563 if (isDuplicated()) {
4564 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4565 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004566 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004567 }
4568}
4569
Eric Laurente0720872014-03-11 09:30:41 -07004570bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004571{
4572 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4573}
4574
Eric Laurente0720872014-03-11 09:30:41 -07004575bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004576 uint32_t inPastMs,
4577 nsecs_t sysTime) const
4578{
4579 if ((sysTime == 0) && (inPastMs != 0)) {
4580 sysTime = systemTime();
4581 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004582 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4583 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004584 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004585 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004586 return true;
4587 }
4588 }
4589 return false;
4590}
4591
Eric Laurente0720872014-03-11 09:30:41 -07004592bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004593 uint32_t inPastMs,
4594 nsecs_t sysTime) const
4595{
4596 if (mRefCount[stream] != 0) {
4597 return true;
4598 }
4599 if (inPastMs == 0) {
4600 return false;
4601 }
4602 if (sysTime == 0) {
4603 sysTime = systemTime();
4604 }
4605 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4606 return true;
4607 }
4608 return false;
4609}
4610
Eric Laurent1c333e22014-05-20 10:48:17 -07004611void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004612 struct audio_port_config *dstConfig,
4613 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004614{
Eric Laurent84c70242014-06-23 08:46:27 -07004615 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4616
Eric Laurent1f2f2232014-06-02 12:01:23 -07004617 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4618 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4619 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004620 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004621 }
4622 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4623
Eric Laurent6a94d692014-05-20 11:18:06 -07004624 dstConfig->id = mId;
4625 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4626 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004627 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4628 dstConfig->ext.mix.handle = mIoHandle;
4629 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004630}
4631
4632void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4633 struct audio_port *port) const
4634{
Eric Laurent84c70242014-06-23 08:46:27 -07004635 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004636 mProfile->toAudioPort(port);
4637 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004638 toAudioPortConfig(&port->active_config);
4639 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004640 port->ext.mix.handle = mIoHandle;
4641 port->ext.mix.latency_class =
4642 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4643}
Eric Laurente552edb2014-03-10 17:42:56 -07004644
Eric Laurente0720872014-03-11 09:30:41 -07004645status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004646{
4647 const size_t SIZE = 256;
4648 char buffer[SIZE];
4649 String8 result;
4650
4651 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4652 result.append(buffer);
4653 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4654 result.append(buffer);
4655 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4656 result.append(buffer);
4657 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4658 result.append(buffer);
4659 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4660 result.append(buffer);
4661 snprintf(buffer, SIZE, " Devices %08x\n", device());
4662 result.append(buffer);
4663 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4664 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004665 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4666 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4667 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004668 result.append(buffer);
4669 }
4670 write(fd, result.string(), result.size());
4671
4672 return NO_ERROR;
4673}
4674
4675// --- AudioInputDescriptor class implementation
4676
Eric Laurent1c333e22014-05-20 10:48:17 -07004677AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004678 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004679 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004680 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004681{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004682 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004683 mAudioPort = profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004684 mSamplingRate = profile->mSamplingRates[0];
4685 mFormat = profile->mFormats[0];
4686 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004687 if (profile->mGains.size() > 0) {
4688 profile->mGains[0]->getDefaultConfig(&mGain);
4689 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004690 } else {
4691 mSamplingRate = 0;
4692 mFormat = AUDIO_FORMAT_DEFAULT;
4693 mChannelMask = 0;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004694 }
Eric Laurente552edb2014-03-10 17:42:56 -07004695}
4696
Eric Laurent1c333e22014-05-20 10:48:17 -07004697void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004698 struct audio_port_config *dstConfig,
4699 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004700{
Eric Laurent84c70242014-06-23 08:46:27 -07004701 ALOG_ASSERT(mProfile != 0,
4702 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004703 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4704 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4705 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004706 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004707 }
4708
4709 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4710
Eric Laurent6a94d692014-05-20 11:18:06 -07004711 dstConfig->id = mId;
4712 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4713 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004714 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4715 dstConfig->ext.mix.handle = mIoHandle;
4716 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004717}
4718
4719void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4720 struct audio_port *port) const
4721{
Eric Laurent84c70242014-06-23 08:46:27 -07004722 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4723
Eric Laurent1c333e22014-05-20 10:48:17 -07004724 mProfile->toAudioPort(port);
4725 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 toAudioPortConfig(&port->active_config);
4727 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004728 port->ext.mix.handle = mIoHandle;
4729 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4730}
4731
Eric Laurente0720872014-03-11 09:30:41 -07004732status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004733{
4734 const size_t SIZE = 256;
4735 char buffer[SIZE];
4736 String8 result;
4737
4738 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4739 result.append(buffer);
4740 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4741 result.append(buffer);
4742 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4743 result.append(buffer);
4744 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4745 result.append(buffer);
4746 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4747 result.append(buffer);
4748 write(fd, result.string(), result.size());
4749
4750 return NO_ERROR;
4751}
4752
4753// --- StreamDescriptor class implementation
4754
Eric Laurente0720872014-03-11 09:30:41 -07004755AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004756 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4757{
4758 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4759}
4760
Eric Laurente0720872014-03-11 09:30:41 -07004761int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004762{
Eric Laurente0720872014-03-11 09:30:41 -07004763 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004764 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4765 if (mIndexCur.indexOfKey(device) < 0) {
4766 device = AUDIO_DEVICE_OUT_DEFAULT;
4767 }
4768 return mIndexCur.valueFor(device);
4769}
4770
Eric Laurente0720872014-03-11 09:30:41 -07004771void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004772{
4773 const size_t SIZE = 256;
4774 char buffer[SIZE];
4775 String8 result;
4776
4777 snprintf(buffer, SIZE, "%s %02d %02d ",
4778 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4779 result.append(buffer);
4780 for (size_t i = 0; i < mIndexCur.size(); i++) {
4781 snprintf(buffer, SIZE, "%04x : %02d, ",
4782 mIndexCur.keyAt(i),
4783 mIndexCur.valueAt(i));
4784 result.append(buffer);
4785 }
4786 result.append("\n");
4787
4788 write(fd, result.string(), result.size());
4789}
4790
4791// --- EffectDescriptor class implementation
4792
Eric Laurente0720872014-03-11 09:30:41 -07004793status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004794{
4795 const size_t SIZE = 256;
4796 char buffer[SIZE];
4797 String8 result;
4798
4799 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4800 result.append(buffer);
4801 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4802 result.append(buffer);
4803 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4804 result.append(buffer);
4805 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4806 result.append(buffer);
4807 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4808 result.append(buffer);
4809 write(fd, result.string(), result.size());
4810
4811 return NO_ERROR;
4812}
4813
Eric Laurent1c333e22014-05-20 10:48:17 -07004814// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004815
Eric Laurente0720872014-03-11 09:30:41 -07004816AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004817 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4818 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004819{
4820}
4821
Eric Laurente0720872014-03-11 09:30:41 -07004822AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004823{
4824 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004825 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004826 }
4827 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004828 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004829 }
4830 free((void *)mName);
4831}
4832
Eric Laurent1afeecb2014-05-14 08:52:28 -07004833status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4834{
4835 cnode *node = root->first_child;
4836
4837 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4838
4839 while (node) {
4840 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4841 profile->loadSamplingRates((char *)node->value);
4842 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4843 profile->loadFormats((char *)node->value);
4844 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4845 profile->loadInChannels((char *)node->value);
4846 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4847 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4848 mDeclaredDevices);
4849 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4850 profile->loadGains(node);
4851 }
4852 node = node->next;
4853 }
4854 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4855 "loadInput() invalid supported devices");
4856 ALOGW_IF(profile->mChannelMasks.size() == 0,
4857 "loadInput() invalid supported channel masks");
4858 ALOGW_IF(profile->mSamplingRates.size() == 0,
4859 "loadInput() invalid supported sampling rates");
4860 ALOGW_IF(profile->mFormats.size() == 0,
4861 "loadInput() invalid supported formats");
4862 if (!profile->mSupportedDevices.isEmpty() &&
4863 (profile->mChannelMasks.size() != 0) &&
4864 (profile->mSamplingRates.size() != 0) &&
4865 (profile->mFormats.size() != 0)) {
4866
4867 ALOGV("loadInput() adding input Supported Devices %04x",
4868 profile->mSupportedDevices.types());
4869
4870 mInputProfiles.add(profile);
4871 return NO_ERROR;
4872 } else {
4873 return BAD_VALUE;
4874 }
4875}
4876
4877status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4878{
4879 cnode *node = root->first_child;
4880
4881 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4882
4883 while (node) {
4884 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4885 profile->loadSamplingRates((char *)node->value);
4886 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4887 profile->loadFormats((char *)node->value);
4888 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4889 profile->loadOutChannels((char *)node->value);
4890 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4891 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4892 mDeclaredDevices);
4893 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4894 profile->mFlags = parseFlagNames((char *)node->value);
4895 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4896 profile->loadGains(node);
4897 }
4898 node = node->next;
4899 }
4900 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4901 "loadOutput() invalid supported devices");
4902 ALOGW_IF(profile->mChannelMasks.size() == 0,
4903 "loadOutput() invalid supported channel masks");
4904 ALOGW_IF(profile->mSamplingRates.size() == 0,
4905 "loadOutput() invalid supported sampling rates");
4906 ALOGW_IF(profile->mFormats.size() == 0,
4907 "loadOutput() invalid supported formats");
4908 if (!profile->mSupportedDevices.isEmpty() &&
4909 (profile->mChannelMasks.size() != 0) &&
4910 (profile->mSamplingRates.size() != 0) &&
4911 (profile->mFormats.size() != 0)) {
4912
4913 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4914 profile->mSupportedDevices.types(), profile->mFlags);
4915
4916 mOutputProfiles.add(profile);
4917 return NO_ERROR;
4918 } else {
4919 return BAD_VALUE;
4920 }
4921}
4922
4923status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4924{
4925 cnode *node = root->first_child;
4926
4927 audio_devices_t type = AUDIO_DEVICE_NONE;
4928 while (node) {
4929 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4930 type = parseDeviceNames((char *)node->value);
4931 break;
4932 }
4933 node = node->next;
4934 }
4935 if (type == AUDIO_DEVICE_NONE ||
4936 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4937 ALOGW("loadDevice() bad type %08x", type);
4938 return BAD_VALUE;
4939 }
4940 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4941 deviceDesc->mModule = this;
4942
4943 node = root->first_child;
4944 while (node) {
4945 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4946 deviceDesc->mAddress = String8((char *)node->value);
4947 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4948 if (audio_is_input_device(type)) {
4949 deviceDesc->loadInChannels((char *)node->value);
4950 } else {
4951 deviceDesc->loadOutChannels((char *)node->value);
4952 }
4953 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4954 deviceDesc->loadGains(node);
4955 }
4956 node = node->next;
4957 }
4958
4959 ALOGV("loadDevice() adding device name %s type %08x address %s",
4960 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4961
4962 mDeclaredDevices.add(deviceDesc);
4963
4964 return NO_ERROR;
4965}
4966
Eric Laurente0720872014-03-11 09:30:41 -07004967void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004968{
4969 const size_t SIZE = 256;
4970 char buffer[SIZE];
4971 String8 result;
4972
4973 snprintf(buffer, SIZE, " - name: %s\n", mName);
4974 result.append(buffer);
4975 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4976 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07004977 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
4978 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07004979 write(fd, result.string(), result.size());
4980 if (mOutputProfiles.size()) {
4981 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4982 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004983 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004984 write(fd, buffer, strlen(buffer));
4985 mOutputProfiles[i]->dump(fd);
4986 }
4987 }
4988 if (mInputProfiles.size()) {
4989 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4990 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004991 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004992 write(fd, buffer, strlen(buffer));
4993 mInputProfiles[i]->dump(fd);
4994 }
4995 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07004996 if (mDeclaredDevices.size()) {
4997 write(fd, " - devices:\n", strlen(" - devices:\n"));
4998 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
4999 mDeclaredDevices[i]->dump(fd, 4, i);
5000 }
5001 }
Eric Laurente552edb2014-03-10 17:42:56 -07005002}
5003
Eric Laurent1c333e22014-05-20 10:48:17 -07005004// --- AudioPort class implementation
5005
Eric Laurenta121f902014-06-03 13:32:54 -07005006
5007AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5008 audio_port_role_t role, const sp<HwModule>& module) :
5009 mName(name), mType(type), mRole(role), mModule(module)
5010{
5011 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5012 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5013}
5014
Eric Laurent1c333e22014-05-20 10:48:17 -07005015void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5016{
5017 port->role = mRole;
5018 port->type = mType;
5019 unsigned int i;
5020 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5021 port->sample_rates[i] = mSamplingRates[i];
5022 }
5023 port->num_sample_rates = i;
5024 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5025 port->channel_masks[i] = mChannelMasks[i];
5026 }
5027 port->num_channel_masks = i;
5028 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5029 port->formats[i] = mFormats[i];
5030 }
5031 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005032
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005033 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005034
5035 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5036 port->gains[i] = mGains[i]->mGain;
5037 }
5038 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005039}
5040
5041
5042void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5043{
5044 char *str = strtok(name, "|");
5045
5046 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5047 // rates should be read from the output stream after it is opened for the first time
5048 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5049 mSamplingRates.add(0);
5050 return;
5051 }
5052
5053 while (str != NULL) {
5054 uint32_t rate = atoi(str);
5055 if (rate != 0) {
5056 ALOGV("loadSamplingRates() adding rate %d", rate);
5057 mSamplingRates.add(rate);
5058 }
5059 str = strtok(NULL, "|");
5060 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005061}
5062
5063void AudioPolicyManager::AudioPort::loadFormats(char *name)
5064{
5065 char *str = strtok(name, "|");
5066
5067 // by convention, "0' in the first entry in mFormats indicates the supported formats
5068 // should be read from the output stream after it is opened for the first time
5069 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5070 mFormats.add(AUDIO_FORMAT_DEFAULT);
5071 return;
5072 }
5073
5074 while (str != NULL) {
5075 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5076 ARRAY_SIZE(sFormatNameToEnumTable),
5077 str);
5078 if (format != AUDIO_FORMAT_DEFAULT) {
5079 mFormats.add(format);
5080 }
5081 str = strtok(NULL, "|");
5082 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005083}
5084
5085void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5086{
5087 const char *str = strtok(name, "|");
5088
5089 ALOGV("loadInChannels() %s", name);
5090
5091 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5092 mChannelMasks.add(0);
5093 return;
5094 }
5095
5096 while (str != NULL) {
5097 audio_channel_mask_t channelMask =
5098 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5099 ARRAY_SIZE(sInChannelsNameToEnumTable),
5100 str);
5101 if (channelMask != 0) {
5102 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5103 mChannelMasks.add(channelMask);
5104 }
5105 str = strtok(NULL, "|");
5106 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005107}
5108
5109void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5110{
5111 const char *str = strtok(name, "|");
5112
5113 ALOGV("loadOutChannels() %s", name);
5114
5115 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5116 // masks should be read from the output stream after it is opened for the first time
5117 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5118 mChannelMasks.add(0);
5119 return;
5120 }
5121
5122 while (str != NULL) {
5123 audio_channel_mask_t channelMask =
5124 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5125 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5126 str);
5127 if (channelMask != 0) {
5128 mChannelMasks.add(channelMask);
5129 }
5130 str = strtok(NULL, "|");
5131 }
5132 return;
5133}
5134
Eric Laurent1afeecb2014-05-14 08:52:28 -07005135audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5136{
5137 const char *str = strtok(name, "|");
5138
5139 ALOGV("loadGainMode() %s", name);
5140 audio_gain_mode_t mode = 0;
5141 while (str != NULL) {
5142 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5143 ARRAY_SIZE(sGainModeNameToEnumTable),
5144 str);
5145 str = strtok(NULL, "|");
5146 }
5147 return mode;
5148}
5149
Eric Laurenta121f902014-06-03 13:32:54 -07005150void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005151{
5152 cnode *node = root->first_child;
5153
Eric Laurenta121f902014-06-03 13:32:54 -07005154 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005155
5156 while (node) {
5157 if (strcmp(node->name, GAIN_MODE) == 0) {
5158 gain->mGain.mode = loadGainMode((char *)node->value);
5159 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005160 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005161 gain->mGain.channel_mask =
5162 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5163 ARRAY_SIZE(sInChannelsNameToEnumTable),
5164 (char *)node->value);
5165 } else {
5166 gain->mGain.channel_mask =
5167 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5168 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5169 (char *)node->value);
5170 }
5171 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5172 gain->mGain.min_value = atoi((char *)node->value);
5173 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5174 gain->mGain.max_value = atoi((char *)node->value);
5175 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5176 gain->mGain.default_value = atoi((char *)node->value);
5177 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5178 gain->mGain.step_value = atoi((char *)node->value);
5179 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5180 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5181 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5182 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5183 }
5184 node = node->next;
5185 }
5186
5187 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5188 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5189
5190 if (gain->mGain.mode == 0) {
5191 return;
5192 }
5193 mGains.add(gain);
5194}
5195
5196void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5197{
5198 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005199 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005200 while (node) {
5201 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005202 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005203 node = node->next;
5204 }
5205}
5206
Eric Laurenta121f902014-06-03 13:32:54 -07005207status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const
5208{
5209 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5210 if (mSamplingRates[i] == samplingRate) {
5211 return NO_ERROR;
5212 }
5213 }
5214 return BAD_VALUE;
5215}
5216
5217status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const
5218{
5219 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5220 if (mChannelMasks[i] == channelMask) {
5221 return NO_ERROR;
5222 }
5223 }
5224 return BAD_VALUE;
5225}
5226
5227status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5228{
5229 for (size_t i = 0; i < mFormats.size(); i ++) {
5230 if (mFormats[i] == format) {
5231 return NO_ERROR;
5232 }
5233 }
5234 return BAD_VALUE;
5235}
5236
5237status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5238 int index) const
5239{
5240 if (index < 0 || (size_t)index >= mGains.size()) {
5241 return BAD_VALUE;
5242 }
5243 return mGains[index]->checkConfig(gainConfig);
5244}
5245
Eric Laurent1afeecb2014-05-14 08:52:28 -07005246void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5247{
5248 const size_t SIZE = 256;
5249 char buffer[SIZE];
5250 String8 result;
5251
5252 if (mName.size() != 0) {
5253 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5254 result.append(buffer);
5255 }
5256
5257 if (mSamplingRates.size() != 0) {
5258 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5259 result.append(buffer);
5260 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5261 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5262 result.append(buffer);
5263 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5264 }
5265 result.append("\n");
5266 }
5267
5268 if (mChannelMasks.size() != 0) {
5269 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5270 result.append(buffer);
5271 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5272 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5273 result.append(buffer);
5274 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5275 }
5276 result.append("\n");
5277 }
5278
5279 if (mFormats.size() != 0) {
5280 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5281 result.append(buffer);
5282 for (size_t i = 0; i < mFormats.size(); i++) {
5283 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5284 ARRAY_SIZE(sFormatNameToEnumTable),
5285 mFormats[i]));
5286 result.append(buffer);
5287 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5288 }
5289 result.append("\n");
5290 }
5291 write(fd, result.string(), result.size());
5292 if (mGains.size() != 0) {
5293 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5294 write(fd, buffer, strlen(buffer) + 1);
5295 result.append(buffer);
5296 for (size_t i = 0; i < mGains.size(); i++) {
5297 mGains[i]->dump(fd, spaces + 2, i);
5298 }
5299 }
5300}
5301
5302// --- AudioGain class implementation
5303
Eric Laurenta121f902014-06-03 13:32:54 -07005304AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005305{
Eric Laurenta121f902014-06-03 13:32:54 -07005306 mIndex = index;
5307 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005308 memset(&mGain, 0, sizeof(struct audio_gain));
5309}
5310
Eric Laurenta121f902014-06-03 13:32:54 -07005311void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5312{
5313 config->index = mIndex;
5314 config->mode = mGain.mode;
5315 config->channel_mask = mGain.channel_mask;
5316 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5317 config->values[0] = mGain.default_value;
5318 } else {
5319 uint32_t numValues;
5320 if (mUseInChannelMask) {
5321 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5322 } else {
5323 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5324 }
5325 for (size_t i = 0; i < numValues; i++) {
5326 config->values[i] = mGain.default_value;
5327 }
5328 }
5329 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5330 config->ramp_duration_ms = mGain.min_ramp_ms;
5331 }
5332}
5333
5334status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5335{
5336 if ((config->mode & ~mGain.mode) != 0) {
5337 return BAD_VALUE;
5338 }
5339 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5340 if ((config->values[0] < mGain.min_value) ||
5341 (config->values[0] > mGain.max_value)) {
5342 return BAD_VALUE;
5343 }
5344 } else {
5345 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5346 return BAD_VALUE;
5347 }
5348 uint32_t numValues;
5349 if (mUseInChannelMask) {
5350 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5351 } else {
5352 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5353 }
5354 for (size_t i = 0; i < numValues; i++) {
5355 if ((config->values[i] < mGain.min_value) ||
5356 (config->values[i] > mGain.max_value)) {
5357 return BAD_VALUE;
5358 }
5359 }
5360 }
5361 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5362 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5363 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5364 return BAD_VALUE;
5365 }
5366 }
5367 return NO_ERROR;
5368}
5369
Eric Laurent1afeecb2014-05-14 08:52:28 -07005370void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5371{
5372 const size_t SIZE = 256;
5373 char buffer[SIZE];
5374 String8 result;
5375
5376 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5377 result.append(buffer);
5378 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5379 result.append(buffer);
5380 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5381 result.append(buffer);
5382 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5383 result.append(buffer);
5384 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5385 result.append(buffer);
5386 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5387 result.append(buffer);
5388 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5389 result.append(buffer);
5390 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5391 result.append(buffer);
5392 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5393 result.append(buffer);
5394
5395 write(fd, result.string(), result.size());
5396}
5397
Eric Laurent1f2f2232014-06-02 12:01:23 -07005398// --- AudioPortConfig class implementation
5399
5400AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5401{
5402 mSamplingRate = 0;
5403 mChannelMask = AUDIO_CHANNEL_NONE;
5404 mFormat = AUDIO_FORMAT_INVALID;
5405 mGain.index = -1;
5406}
5407
Eric Laurenta121f902014-06-03 13:32:54 -07005408status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5409 const struct audio_port_config *config,
5410 struct audio_port_config *backupConfig)
5411{
5412 struct audio_port_config localBackupConfig;
5413 status_t status = NO_ERROR;
5414
5415 localBackupConfig.config_mask = config->config_mask;
5416 toAudioPortConfig(&localBackupConfig);
5417
5418 if (mAudioPort == 0) {
5419 status = NO_INIT;
5420 goto exit;
5421 }
5422 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5423 status = mAudioPort->checkSamplingRate(config->sample_rate);
5424 if (status != NO_ERROR) {
5425 goto exit;
5426 }
5427 mSamplingRate = config->sample_rate;
5428 }
5429 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5430 status = mAudioPort->checkChannelMask(config->channel_mask);
5431 if (status != NO_ERROR) {
5432 goto exit;
5433 }
5434 mChannelMask = config->channel_mask;
5435 }
5436 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5437 status = mAudioPort->checkFormat(config->format);
5438 if (status != NO_ERROR) {
5439 goto exit;
5440 }
5441 mFormat = config->format;
5442 }
5443 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5444 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5445 if (status != NO_ERROR) {
5446 goto exit;
5447 }
5448 mGain = config->gain;
5449 }
5450
5451exit:
5452 if (status != NO_ERROR) {
5453 applyAudioPortConfig(&localBackupConfig);
5454 }
5455 if (backupConfig != NULL) {
5456 *backupConfig = localBackupConfig;
5457 }
5458 return status;
5459}
5460
Eric Laurent1f2f2232014-06-02 12:01:23 -07005461void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5462 struct audio_port_config *dstConfig,
5463 const struct audio_port_config *srcConfig) const
5464{
5465 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5466 dstConfig->sample_rate = mSamplingRate;
5467 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5468 dstConfig->sample_rate = srcConfig->sample_rate;
5469 }
5470 } else {
5471 dstConfig->sample_rate = 0;
5472 }
5473 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5474 dstConfig->channel_mask = mChannelMask;
5475 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5476 dstConfig->channel_mask = srcConfig->channel_mask;
5477 }
5478 } else {
5479 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5480 }
5481 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5482 dstConfig->format = mFormat;
5483 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5484 dstConfig->format = srcConfig->format;
5485 }
5486 } else {
5487 dstConfig->format = AUDIO_FORMAT_INVALID;
5488 }
5489 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5490 dstConfig->gain = mGain;
5491 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5492 dstConfig->gain = srcConfig->gain;
5493 }
5494 } else {
5495 dstConfig->gain.index = -1;
5496 }
5497 if (dstConfig->gain.index != -1) {
5498 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5499 } else {
5500 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5501 }
5502}
5503
Eric Laurent1c333e22014-05-20 10:48:17 -07005504// --- IOProfile class implementation
5505
Eric Laurent1afeecb2014-05-14 08:52:28 -07005506AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005507 const sp<HwModule>& module)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005508 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005509{
5510}
5511
Eric Laurente0720872014-03-11 09:30:41 -07005512AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005513{
5514}
5515
5516// checks if the IO profile is compatible with specified parameters.
5517// Sampling rate, format and channel mask must be specified in order to
5518// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005519bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005520 uint32_t samplingRate,
5521 audio_format_t format,
5522 audio_channel_mask_t channelMask,
5523 audio_output_flags_t flags) const
5524{
5525 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5526 return false;
5527 }
5528
Eric Laurent3a4311c2014-03-17 12:00:47 -07005529 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005530 return false;
5531 }
5532 if ((mFlags & flags) != flags) {
5533 return false;
5534 }
Eric Laurenta121f902014-06-03 13:32:54 -07005535 if (checkSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005536 return false;
5537 }
Eric Laurenta121f902014-06-03 13:32:54 -07005538 if (checkChannelMask(channelMask) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005539 return false;
5540 }
Eric Laurenta121f902014-06-03 13:32:54 -07005541 if (checkFormat(format) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005542 return false;
5543 }
5544 return true;
5545}
5546
Eric Laurente0720872014-03-11 09:30:41 -07005547void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005548{
5549 const size_t SIZE = 256;
5550 char buffer[SIZE];
5551 String8 result;
5552
Eric Laurent1afeecb2014-05-14 08:52:28 -07005553 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005554
Eric Laurente552edb2014-03-10 17:42:56 -07005555 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5556 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005557 snprintf(buffer, SIZE, " - devices:\n");
5558 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005559 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005560 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5561 mSupportedDevices[i]->dump(fd, 6, i);
5562 }
Eric Laurente552edb2014-03-10 17:42:56 -07005563}
5564
Eric Laurentd4692962014-05-05 18:13:44 -07005565void AudioPolicyManager::IOProfile::log()
5566{
5567 const size_t SIZE = 256;
5568 char buffer[SIZE];
5569 String8 result;
5570
5571 ALOGV(" - sampling rates: ");
5572 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5573 ALOGV(" %d", mSamplingRates[i]);
5574 }
5575
5576 ALOGV(" - channel masks: ");
5577 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5578 ALOGV(" 0x%04x", mChannelMasks[i]);
5579 }
5580
5581 ALOGV(" - formats: ");
5582 for (size_t i = 0; i < mFormats.size(); i++) {
5583 ALOGV(" 0x%08x", mFormats[i]);
5584 }
5585
5586 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5587 ALOGV(" - flags: 0x%04x\n", mFlags);
5588}
5589
5590
Eric Laurent3a4311c2014-03-17 12:00:47 -07005591// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005592
Eric Laurent1f2f2232014-06-02 12:01:23 -07005593
5594AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5595 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5596 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5597 AUDIO_PORT_ROLE_SOURCE,
5598 NULL),
5599 mDeviceType(type), mAddress(""),
5600 mChannelMask(AUDIO_CHANNEL_NONE), mId(0)
5601{
5602 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005603 if (mGains.size() > 0) {
5604 mGains[0]->getDefaultConfig(&mGain);
5605 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005606}
5607
Eric Laurent3a4311c2014-03-17 12:00:47 -07005608bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005609{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005610 // Devices are considered equal if they:
5611 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5612 // - have the same address or one device does not specify the address
5613 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005614 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005615 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005616 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005617 mChannelMask == other->mChannelMask);
5618}
5619
5620void AudioPolicyManager::DeviceVector::refreshTypes()
5621{
Eric Laurent1c333e22014-05-20 10:48:17 -07005622 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005623 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005624 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005625 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005626 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005627}
5628
5629ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5630{
5631 for(size_t i = 0; i < size(); i++) {
5632 if (item->equals(itemAt(i))) {
5633 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005634 }
5635 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005636 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005637}
5638
Eric Laurent3a4311c2014-03-17 12:00:47 -07005639ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005640{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005641 ssize_t ret = indexOf(item);
5642
5643 if (ret < 0) {
5644 ret = SortedVector::add(item);
5645 if (ret >= 0) {
5646 refreshTypes();
5647 }
5648 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005649 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005650 ret = -1;
5651 }
5652 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005653}
5654
Eric Laurent3a4311c2014-03-17 12:00:47 -07005655ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5656{
5657 size_t i;
5658 ssize_t ret = indexOf(item);
5659
5660 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005661 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005662 } else {
5663 ret = SortedVector::removeAt(ret);
5664 if (ret >= 0) {
5665 refreshTypes();
5666 }
5667 }
5668 return ret;
5669}
5670
5671void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5672{
5673 DeviceVector deviceList;
5674
5675 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5676 types &= ~role_bit;
5677
5678 while (types) {
5679 uint32_t i = 31 - __builtin_clz(types);
5680 uint32_t type = 1 << i;
5681 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005682 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005683 }
5684}
5685
Eric Laurent1afeecb2014-05-14 08:52:28 -07005686void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5687 const DeviceVector& declaredDevices)
5688{
5689 char *devName = strtok(name, "|");
5690 while (devName != NULL) {
5691 if (strlen(devName) != 0) {
5692 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5693 ARRAY_SIZE(sDeviceNameToEnumTable),
5694 devName);
5695 if (type != AUDIO_DEVICE_NONE) {
5696 add(new DeviceDescriptor(String8(""), type));
5697 } else {
5698 sp<DeviceDescriptor> deviceDesc =
5699 declaredDevices.getDeviceFromName(String8(devName));
5700 if (deviceDesc != 0) {
5701 add(deviceDesc);
5702 }
5703 }
5704 }
5705 devName = strtok(NULL, "|");
5706 }
5707}
5708
Eric Laurent1c333e22014-05-20 10:48:17 -07005709sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5710 audio_devices_t type, String8 address) const
5711{
5712 sp<DeviceDescriptor> device;
5713 for (size_t i = 0; i < size(); i++) {
5714 if (itemAt(i)->mDeviceType == type) {
5715 device = itemAt(i);
5716 if (itemAt(i)->mAddress = address) {
5717 break;
5718 }
5719 }
5720 }
5721 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5722 type, address.string(), device.get());
5723 return device;
5724}
5725
Eric Laurent6a94d692014-05-20 11:18:06 -07005726sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5727 audio_port_handle_t id) const
5728{
5729 sp<DeviceDescriptor> device;
5730 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005731 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07005732 if (itemAt(i)->mId == id) {
5733 device = itemAt(i);
5734 break;
5735 }
5736 }
5737 return device;
5738}
5739
Eric Laurent1c333e22014-05-20 10:48:17 -07005740AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5741 audio_devices_t type) const
5742{
5743 DeviceVector devices;
5744 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5745 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5746 devices.add(itemAt(i));
5747 type &= ~itemAt(i)->mDeviceType;
5748 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5749 itemAt(i)->mDeviceType, itemAt(i).get());
5750 }
5751 }
5752 return devices;
5753}
5754
Eric Laurent1afeecb2014-05-14 08:52:28 -07005755sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5756 const String8& name) const
5757{
5758 sp<DeviceDescriptor> device;
5759 for (size_t i = 0; i < size(); i++) {
5760 if (itemAt(i)->mName == name) {
5761 device = itemAt(i);
5762 break;
5763 }
5764 }
5765 return device;
5766}
5767
Eric Laurent6a94d692014-05-20 11:18:06 -07005768void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5769 struct audio_port_config *dstConfig,
5770 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005771{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005772 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
5773 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005774 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005775 }
5776
5777 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5778
Eric Laurent6a94d692014-05-20 11:18:06 -07005779 dstConfig->id = mId;
5780 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005781 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005782 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005783 dstConfig->ext.device.type = mDeviceType;
5784 dstConfig->ext.device.hw_module = mModule->mHandle;
5785 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005786}
5787
5788void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5789{
Eric Laurente1715a42014-05-20 11:30:42 -07005790 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07005791 AudioPort::toAudioPort(port);
5792 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005793 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005794 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005795 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005796 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5797}
5798
Eric Laurent1afeecb2014-05-14 08:52:28 -07005799status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005800{
5801 const size_t SIZE = 256;
5802 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005803 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005804
Eric Laurent1afeecb2014-05-14 08:52:28 -07005805 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5806 result.append(buffer);
5807 if (mId != 0) {
5808 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5809 result.append(buffer);
5810 }
5811 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5812 enumToString(sDeviceNameToEnumTable,
5813 ARRAY_SIZE(sDeviceNameToEnumTable),
5814 mDeviceType));
5815 result.append(buffer);
5816 if (mAddress.size() != 0) {
5817 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5818 result.append(buffer);
5819 }
5820 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5821 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5822 result.append(buffer);
5823 }
5824 write(fd, result.string(), result.size());
5825 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005826
5827 return NO_ERROR;
5828}
5829
5830
5831// --- audio_policy.conf file parsing
5832
Eric Laurente0720872014-03-11 09:30:41 -07005833audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005834{
5835 uint32_t flag = 0;
5836
5837 // it is OK to cast name to non const here as we are not going to use it after
5838 // strtok() modifies it
5839 char *flagName = strtok(name, "|");
5840 while (flagName != NULL) {
5841 if (strlen(flagName) != 0) {
5842 flag |= stringToEnum(sFlagNameToEnumTable,
5843 ARRAY_SIZE(sFlagNameToEnumTable),
5844 flagName);
5845 }
5846 flagName = strtok(NULL, "|");
5847 }
5848 //force direct flag if offload flag is set: offloading implies a direct output stream
5849 // and all common behaviors are driven by checking only the direct flag
5850 // this should normally be set appropriately in the policy configuration file
5851 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5852 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5853 }
5854
5855 return (audio_output_flags_t)flag;
5856}
5857
Eric Laurente0720872014-03-11 09:30:41 -07005858audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005859{
5860 uint32_t device = 0;
5861
5862 char *devName = strtok(name, "|");
5863 while (devName != NULL) {
5864 if (strlen(devName) != 0) {
5865 device |= stringToEnum(sDeviceNameToEnumTable,
5866 ARRAY_SIZE(sDeviceNameToEnumTable),
5867 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005868 }
Eric Laurente552edb2014-03-10 17:42:56 -07005869 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005870 }
Eric Laurente552edb2014-03-10 17:42:56 -07005871 return device;
5872}
5873
Eric Laurente0720872014-03-11 09:30:41 -07005874void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005875{
Eric Laurente552edb2014-03-10 17:42:56 -07005876 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005877 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005878 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07005879
Eric Laurent1afeecb2014-05-14 08:52:28 -07005880 node = config_find(root, DEVICES_TAG);
5881 if (node != NULL) {
5882 node = node->first_child;
5883 while (node) {
5884 ALOGV("loadHwModule() loading device %s", node->name);
5885 status_t tmpStatus = module->loadDevice(node);
5886 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5887 status = tmpStatus;
5888 }
5889 node = node->next;
5890 }
5891 }
5892 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005893 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005894 node = node->first_child;
5895 while (node) {
5896 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005897 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005898 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5899 status = tmpStatus;
5900 }
5901 node = node->next;
5902 }
5903 }
5904 node = config_find(root, INPUTS_TAG);
5905 if (node != NULL) {
5906 node = node->first_child;
5907 while (node) {
5908 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005909 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005910 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5911 status = tmpStatus;
5912 }
5913 node = node->next;
5914 }
5915 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005916 loadGlobalConfig(root, module);
5917
Eric Laurente552edb2014-03-10 17:42:56 -07005918 if (status == NO_ERROR) {
5919 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07005920 }
5921}
5922
Eric Laurente0720872014-03-11 09:30:41 -07005923void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005924{
5925 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5926 if (node == NULL) {
5927 return;
5928 }
5929
5930 node = node->first_child;
5931 while (node) {
5932 ALOGV("loadHwModules() loading module %s", node->name);
5933 loadHwModule(node);
5934 node = node->next;
5935 }
5936}
5937
Eric Laurent1f2f2232014-06-02 12:01:23 -07005938void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07005939{
5940 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07005941
Eric Laurente552edb2014-03-10 17:42:56 -07005942 if (node == NULL) {
5943 return;
5944 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005945 DeviceVector declaredDevices;
5946 if (module != NULL) {
5947 declaredDevices = module->mDeclaredDevices;
5948 }
5949
Eric Laurente552edb2014-03-10 17:42:56 -07005950 node = node->first_child;
5951 while (node) {
5952 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005953 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5954 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005955 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5956 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005957 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005958 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005959 ARRAY_SIZE(sDeviceNameToEnumTable),
5960 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005961 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005962 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005963 } else {
5964 ALOGW("loadGlobalConfig() default device not specified");
5965 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005966 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005967 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005968 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5969 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005970 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005971 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5972 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5973 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07005974 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
5975 uint32_t major, minor;
5976 sscanf((char *)node->value, "%u.%u", &major, &minor);
5977 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
5978 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
5979 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07005980 }
5981 node = node->next;
5982 }
5983}
5984
Eric Laurente0720872014-03-11 09:30:41 -07005985status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005986{
5987 cnode *root;
5988 char *data;
5989
5990 data = (char *)load_file(path, NULL);
5991 if (data == NULL) {
5992 return -ENODEV;
5993 }
5994 root = config_node("", "");
5995 config_load(root, data);
5996
Eric Laurente552edb2014-03-10 17:42:56 -07005997 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005998 // legacy audio_policy.conf files have one global_configuration section
5999 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006000 config_free(root);
6001 free(root);
6002 free(data);
6003
6004 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6005
6006 return NO_ERROR;
6007}
6008
Eric Laurente0720872014-03-11 09:30:41 -07006009void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006010{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006011 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006012 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006013 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6014 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006015 mAvailableOutputDevices.add(mDefaultOutputDevice);
6016 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006017
6018 module = new HwModule("primary");
6019
Eric Laurent1afeecb2014-05-14 08:52:28 -07006020 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006021 profile->mSamplingRates.add(44100);
6022 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6023 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006024 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006025 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6026 module->mOutputProfiles.add(profile);
6027
Eric Laurent1afeecb2014-05-14 08:52:28 -07006028 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006029 profile->mSamplingRates.add(8000);
6030 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6031 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006032 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006033 module->mInputProfiles.add(profile);
6034
6035 mHwModules.add(module);
6036}
6037
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006038audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6039{
6040 // flags to stream type mapping
6041 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6042 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6043 }
6044 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6045 return AUDIO_STREAM_BLUETOOTH_SCO;
6046 }
6047
6048 // usage to stream type mapping
6049 switch (attr->usage) {
6050 case AUDIO_USAGE_MEDIA:
6051 case AUDIO_USAGE_GAME:
6052 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6053 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6054 return AUDIO_STREAM_MUSIC;
6055 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6056 return AUDIO_STREAM_SYSTEM;
6057 case AUDIO_USAGE_VOICE_COMMUNICATION:
6058 return AUDIO_STREAM_VOICE_CALL;
6059
6060 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6061 return AUDIO_STREAM_DTMF;
6062
6063 case AUDIO_USAGE_ALARM:
6064 return AUDIO_STREAM_ALARM;
6065 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6066 return AUDIO_STREAM_RING;
6067
6068 case AUDIO_USAGE_NOTIFICATION:
6069 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6070 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6071 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6072 case AUDIO_USAGE_NOTIFICATION_EVENT:
6073 return AUDIO_STREAM_NOTIFICATION;
6074
6075 case AUDIO_USAGE_UNKNOWN:
6076 default:
6077 return AUDIO_STREAM_MUSIC;
6078 }
6079}
Eric Laurente552edb2014-03-10 17:42:56 -07006080}; // namespace android