blob: a0322d60e7bdaf44c6eda2d5d9ba030947713317 [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
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070047#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070048
Eric Laurent3b73df72014-03-11 09:06:29 -070049namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070050
51// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070052// Definitions for audio_policy.conf file parsing
53// ----------------------------------------------------------------------------
54
55struct StringToEnum {
56 const char *name;
57 uint32_t value;
58};
59
60#define STRING_TO_ENUM(string) { #string, string }
61#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
62
63const StringToEnum sDeviceNameToEnumTable[] = {
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070077 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070084 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070089 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
90 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
91 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
92 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070095 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070096 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
99 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900108 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700109};
110
111const StringToEnum sFlagNameToEnumTable[] = {
112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
113 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
114 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
118};
119
120const StringToEnum sFormatNameToEnumTable[] = {
121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
122 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
123 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
124 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
127 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
128 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530129 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
130 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
131 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700139 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700140 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
141 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
142 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
143 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
144 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700145};
146
147const StringToEnum sOutChannelsNameToEnumTable[] = {
148 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
149 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
150 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
151 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
152};
153
154const StringToEnum sInChannelsNameToEnumTable[] = {
155 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
156 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
157 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
158};
159
Eric Laurent1afeecb2014-05-14 08:52:28 -0700160const StringToEnum sGainModeNameToEnumTable[] = {
161 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
162 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
163 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
164};
165
Eric Laurent3a4311c2014-03-17 12:00:47 -0700166
167uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
168 size_t size,
169 const char *name)
170{
171 for (size_t i = 0; i < size; i++) {
172 if (strcmp(table[i].name, name) == 0) {
173 ALOGV("stringToEnum() found %s", table[i].name);
174 return table[i].value;
175 }
176 }
177 return 0;
178}
179
180const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
181 size_t size,
182 uint32_t value)
183{
184 for (size_t i = 0; i < size; i++) {
185 if (table[i].value == value) {
186 return table[i].name;
187 }
188 }
189 return "";
190}
191
192bool AudioPolicyManager::stringToBool(const char *value)
193{
194 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
195}
196
197
198// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700199// AudioPolicyInterface implementation
200// ----------------------------------------------------------------------------
201
202
Eric Laurente0720872014-03-11 09:30:41 -0700203status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700204 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700205 const char *device_address)
206{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700207 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700208
209 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
210
211 // connect/disconnect only 1 device at a time
212 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
213
Eric Laurente552edb2014-03-10 17:42:56 -0700214 // handle output devices
215 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700216 SortedVector <audio_io_handle_t> outputs;
217
Eric Laurent1afeecb2014-05-14 08:52:28 -0700218 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
219 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700220 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
221
Eric Laurente552edb2014-03-10 17:42:56 -0700222 // save a copy of the opened output descriptors before any output is opened or closed
223 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
224 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700225 switch (state)
226 {
227 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700228 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700229 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700230 ALOGW("setDeviceConnectionState() device already connected: %x", device);
231 return INVALID_OPERATION;
232 }
233 ALOGV("setDeviceConnectionState() connecting device %x", device);
234
Eric Laurente552edb2014-03-10 17:42:56 -0700235 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 index = mAvailableOutputDevices.add(devDesc);
237 if (index >= 0) {
238 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700239 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700240 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
241 "could not find HW module for device %08x", device);
242 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 } else {
244 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700245 }
246
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700247 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
248 mAvailableOutputDevices.remove(devDesc);
249 return INVALID_OPERATION;
250 }
251 // outputs should never be empty here
252 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
253 "checkOutputsForDevice() returned no outputs but status OK");
254 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
255 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700256 break;
257 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700258 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700260 ALOGW("setDeviceConnectionState() device not connected: %x", device);
261 return INVALID_OPERATION;
262 }
263
264 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
265 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700266 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700267
Eric Laurent3a4311c2014-03-17 12:00:47 -0700268 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700269 } break;
270
271 default:
272 ALOGE("setDeviceConnectionState() invalid state: %x", state);
273 return BAD_VALUE;
274 }
275
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
277 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700278 checkA2dpSuspend();
279 checkOutputForAllStrategies();
280 // outputs must be closed after checkOutputForAllStrategies() is executed
281 if (!outputs.isEmpty()) {
282 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700283 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700284 // close unused outputs after device disconnection or direct outputs that have been
285 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700286 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700287 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
288 (desc->mDirectOpenCount == 0))) {
289 closeOutput(outputs[i]);
290 }
291 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700292 // check again after closing A2DP output to reset mA2dpSuspended if needed
293 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700294 }
295
296 updateDevicesAndOutputs();
297 for (size_t i = 0; i < mOutputs.size(); i++) {
298 // do not force device change on duplicated output because if device is 0, it will
299 // also force a device 0 for the two outputs it is duplicated to which may override
300 // a valid device selection on those outputs.
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700301 bool force = !mOutputs.valueAt(i)->isDuplicated()
302 && (!deviceDistinguishesOnAddress(device)
303 // always force when disconnecting (a non-duplicated device)
304 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurente552edb2014-03-10 17:42:56 -0700305 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700306 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700307 force, 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700308 }
309
Eric Laurent72aa32f2014-05-30 18:51:48 -0700310 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700311 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700312 } // end if is output device
313
Eric Laurente552edb2014-03-10 17:42:56 -0700314 // handle input devices
315 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700316 SortedVector <audio_io_handle_t> inputs;
317
Eric Laurent1afeecb2014-05-14 08:52:28 -0700318 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
319 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700320 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700321 switch (state)
322 {
323 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700324 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700326 ALOGW("setDeviceConnectionState() device already connected: %d", device);
327 return INVALID_OPERATION;
328 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700329 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700330 if (module == NULL) {
331 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
332 device);
333 return INVALID_OPERATION;
334 }
Eric Laurentd4692962014-05-05 18:13:44 -0700335 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
336 return INVALID_OPERATION;
337 }
338
Eric Laurent3a4311c2014-03-17 12:00:47 -0700339 index = mAvailableInputDevices.add(devDesc);
340 if (index >= 0) {
341 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700342 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700343 } else {
344 return NO_MEMORY;
345 }
Eric Laurentd4692962014-05-05 18:13:44 -0700346 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700347
348 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700349 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700350 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700351 ALOGW("setDeviceConnectionState() device not connected: %d", device);
352 return INVALID_OPERATION;
353 }
Eric Laurentd4692962014-05-05 18:13:44 -0700354 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700355 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700356 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700357
358 default:
359 ALOGE("setDeviceConnectionState() invalid state: %x", state);
360 return BAD_VALUE;
361 }
362
Eric Laurentd4692962014-05-05 18:13:44 -0700363 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700364
Eric Laurentb52c1522014-05-20 11:27:36 -0700365 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700366 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700367 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700368
369 ALOGW("setDeviceConnectionState() invalid device: %x", device);
370 return BAD_VALUE;
371}
372
Eric Laurente0720872014-03-11 09:30:41 -0700373audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700374 const char *device_address)
375{
Eric Laurent3b73df72014-03-11 09:06:29 -0700376 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700377 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700378 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
379 devDesc->mAddress = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700380 ssize_t index;
381 DeviceVector *deviceVector;
382
Eric Laurente552edb2014-03-10 17:42:56 -0700383 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700384 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700385 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700386 deviceVector = &mAvailableInputDevices;
387 } else {
388 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
389 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700390 }
391
Eric Laurent3a4311c2014-03-17 12:00:47 -0700392 index = deviceVector->indexOf(devDesc);
393 if (index >= 0) {
394 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
395 } else {
396 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
397 }
Eric Laurente552edb2014-03-10 17:42:56 -0700398}
399
Eric Laurente0720872014-03-11 09:30:41 -0700400void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700401{
402 ALOGV("setPhoneState() state %d", state);
403 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700404 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700405 ALOGW("setPhoneState() invalid state %d", state);
406 return;
407 }
408
409 if (state == mPhoneState ) {
410 ALOGW("setPhoneState() setting same state %d", state);
411 return;
412 }
413
414 // if leaving call state, handle special case of active streams
415 // pertaining to sonification strategy see handleIncallSonification()
416 if (isInCall()) {
417 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700418 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
419 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700420 }
421 }
422
423 // store previous phone state for management of sonification strategy below
424 int oldState = mPhoneState;
425 mPhoneState = state;
426 bool force = false;
427
428 // are we entering or starting a call
429 if (!isStateInCall(oldState) && isStateInCall(state)) {
430 ALOGV(" Entering call in setPhoneState()");
431 // force routing command to audio hardware when starting a call
432 // even if no device change is needed
433 force = true;
434 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
435 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
436 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
437 }
438 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
439 ALOGV(" Exiting call in setPhoneState()");
440 // force routing command to audio hardware when exiting a call
441 // even if no device change is needed
442 force = true;
443 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
444 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
445 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
446 }
447 } else if (isStateInCall(state) && (state != oldState)) {
448 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
449 // force routing command to audio hardware when switching between telephony and VoIP
450 // even if no device change is needed
451 force = true;
452 }
453
454 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700455 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700456 checkA2dpSuspend();
457 checkOutputForAllStrategies();
458 updateDevicesAndOutputs();
459
Eric Laurent1f2f2232014-06-02 12:01:23 -0700460 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700461
462 // force routing command to audio hardware when ending call
463 // even if no device change is needed
464 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
465 newDevice = hwOutputDesc->device();
466 }
467
468 int delayMs = 0;
469 if (isStateInCall(state)) {
470 nsecs_t sysTime = systemTime();
471 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700472 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700473 // mute media and sonification strategies and delay device switch by the largest
474 // latency of any output where either strategy is active.
475 // This avoid sending the ring tone or music tail into the earpiece or headset.
476 if ((desc->isStrategyActive(STRATEGY_MEDIA,
477 SONIFICATION_HEADSET_MUSIC_DELAY,
478 sysTime) ||
479 desc->isStrategyActive(STRATEGY_SONIFICATION,
480 SONIFICATION_HEADSET_MUSIC_DELAY,
481 sysTime)) &&
482 (delayMs < (int)desc->mLatency*2)) {
483 delayMs = desc->mLatency*2;
484 }
485 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
486 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
487 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
488 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
489 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
490 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
491 }
492 }
493
494 // change routing is necessary
495 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
496
497 // if entering in call state, handle special case of active streams
498 // pertaining to sonification strategy see handleIncallSonification()
499 if (isStateInCall(state)) {
500 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700501 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
502 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700503 }
504 }
505
506 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700507 if (state == AUDIO_MODE_RINGTONE &&
508 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700509 mLimitRingtoneVolume = true;
510 } else {
511 mLimitRingtoneVolume = false;
512 }
513}
514
Eric Laurente0720872014-03-11 09:30:41 -0700515void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700516 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700517{
518 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
519
520 bool forceVolumeReeval = false;
521 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700522 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
523 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
524 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700525 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
526 return;
527 }
528 forceVolumeReeval = true;
529 mForceUse[usage] = config;
530 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700531 case AUDIO_POLICY_FORCE_FOR_MEDIA:
532 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
533 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
534 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
535 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900536 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700537 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
538 return;
539 }
540 mForceUse[usage] = config;
541 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700542 case AUDIO_POLICY_FORCE_FOR_RECORD:
543 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
544 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700545 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
546 return;
547 }
548 mForceUse[usage] = config;
549 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700550 case AUDIO_POLICY_FORCE_FOR_DOCK:
551 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
552 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
553 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
554 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
555 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700556 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
557 }
558 forceVolumeReeval = true;
559 mForceUse[usage] = config;
560 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700561 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
562 if (config != AUDIO_POLICY_FORCE_NONE &&
563 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700564 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
565 }
566 forceVolumeReeval = true;
567 mForceUse[usage] = config;
568 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900569 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
570 if (config != AUDIO_POLICY_FORCE_NONE &&
571 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
572 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
573 }
574 mForceUse[usage] = config;
575 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700576 default:
577 ALOGW("setForceUse() invalid usage %d", usage);
578 break;
579 }
580
581 // check for device and output changes triggered by new force usage
582 checkA2dpSuspend();
583 checkOutputForAllStrategies();
584 updateDevicesAndOutputs();
585 for (size_t i = 0; i < mOutputs.size(); i++) {
586 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700587 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700588 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
589 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
590 applyStreamVolumes(output, newDevice, 0, true);
591 }
592 }
593
594 audio_io_handle_t activeInput = getActiveInput();
595 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700596 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700597 }
598
599}
600
Eric Laurente0720872014-03-11 09:30:41 -0700601audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700602{
603 return mForceUse[usage];
604}
605
Eric Laurente0720872014-03-11 09:30:41 -0700606void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700607{
608 ALOGV("setSystemProperty() property %s, value %s", property, value);
609}
610
611// Find a direct output profile compatible with the parameters passed, even if the input flags do
612// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700613sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700614 audio_devices_t device,
615 uint32_t samplingRate,
616 audio_format_t format,
617 audio_channel_mask_t channelMask,
618 audio_output_flags_t flags)
619{
620 for (size_t i = 0; i < mHwModules.size(); i++) {
621 if (mHwModules[i]->mHandle == 0) {
622 continue;
623 }
624 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700625 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700626 bool found = profile->isCompatibleProfile(device, samplingRate,
627 NULL /*updatedSamplingRate*/, format, channelMask,
628 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
629 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700630 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
631 return profile;
632 }
Eric Laurente552edb2014-03-10 17:42:56 -0700633 }
634 }
635 return 0;
636}
637
Eric Laurente0720872014-03-11 09:30:41 -0700638audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700639 uint32_t samplingRate,
640 audio_format_t format,
641 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700642 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700643 const audio_offload_info_t *offloadInfo)
644{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700645
Eric Laurent3b73df72014-03-11 09:06:29 -0700646 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700647 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
648 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
649 device, stream, samplingRate, format, channelMask, flags);
650
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700651 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
652 offloadInfo);
653}
654
655audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
656 uint32_t samplingRate,
657 audio_format_t format,
658 audio_channel_mask_t channelMask,
659 audio_output_flags_t flags,
660 const audio_offload_info_t *offloadInfo)
661{
662 if (attr == NULL) {
663 ALOGE("getOutputForAttr() called with NULL audio attributes");
664 return 0;
665 }
666 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
667 attr->usage, attr->content_type, attr->tags);
668
669 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
670 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
671 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
672 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
673 device, samplingRate, format, channelMask, flags);
674
675 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
676 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
677 offloadInfo);
678}
679
680audio_io_handle_t AudioPolicyManager::getOutputForDevice(
681 audio_devices_t device,
682 audio_stream_type_t stream,
683 uint32_t samplingRate,
684 audio_format_t format,
685 audio_channel_mask_t channelMask,
686 audio_output_flags_t flags,
687 const audio_offload_info_t *offloadInfo)
688{
689 audio_io_handle_t output = 0;
690 uint32_t latency = 0;
691
Eric Laurente552edb2014-03-10 17:42:56 -0700692#ifdef AUDIO_POLICY_TEST
693 if (mCurOutput != 0) {
694 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
695 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
696
697 if (mTestOutputs[mCurOutput] == 0) {
698 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700699 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700700 outputDesc->mDevice = mTestDevice;
701 outputDesc->mSamplingRate = mTestSamplingRate;
702 outputDesc->mFormat = mTestFormat;
703 outputDesc->mChannelMask = mTestChannels;
704 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 outputDesc->mFlags =
706 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700707 outputDesc->mRefCount[stream] = 0;
708 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
709 &outputDesc->mSamplingRate,
710 &outputDesc->mFormat,
711 &outputDesc->mChannelMask,
712 &outputDesc->mLatency,
713 outputDesc->mFlags,
714 offloadInfo);
715 if (mTestOutputs[mCurOutput]) {
716 AudioParameter outputCmd = AudioParameter();
717 outputCmd.addInt(String8("set_id"),mCurOutput);
718 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
719 addOutput(mTestOutputs[mCurOutput], outputDesc);
720 }
721 }
722 return mTestOutputs[mCurOutput];
723 }
724#endif //AUDIO_POLICY_TEST
725
726 // open a direct output if required by specified parameters
727 //force direct flag if offload flag is set: offloading implies a direct output stream
728 // and all common behaviors are driven by checking only the direct flag
729 // this should normally be set appropriately in the policy configuration file
730 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700731 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700732 }
733
734 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
735 // creating an offloaded track and tearing it down immediately after start when audioflinger
736 // detects there is an active non offloadable effect.
737 // FIXME: We should check the audio session here but we do not have it in this context.
738 // This may prevent offloading in rare situations where effects are left active by apps
739 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700740 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700741 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
742 !isNonOffloadableEffectEnabled()) {
743 profile = getProfileForDirectOutput(device,
744 samplingRate,
745 format,
746 channelMask,
747 (audio_output_flags_t)flags);
748 }
749
Eric Laurent1c333e22014-05-20 10:48:17 -0700750 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700751 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700752
753 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700754 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700755 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
756 outputDesc = desc;
757 // reuse direct output if currently open and configured with same parameters
758 if ((samplingRate == outputDesc->mSamplingRate) &&
759 (format == outputDesc->mFormat) &&
760 (channelMask == outputDesc->mChannelMask)) {
761 outputDesc->mDirectOpenCount++;
762 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
763 return mOutputs.keyAt(i);
764 }
765 }
766 }
767 // close direct output if currently open and configured with different parameters
768 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700769 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700770 }
771 outputDesc = new AudioOutputDescriptor(profile);
772 outputDesc->mDevice = device;
773 outputDesc->mSamplingRate = samplingRate;
774 outputDesc->mFormat = format;
775 outputDesc->mChannelMask = channelMask;
776 outputDesc->mLatency = 0;
777 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
778 outputDesc->mRefCount[stream] = 0;
779 outputDesc->mStopTime[stream] = 0;
780 outputDesc->mDirectOpenCount = 1;
781 output = mpClientInterface->openOutput(profile->mModule->mHandle,
782 &outputDesc->mDevice,
783 &outputDesc->mSamplingRate,
784 &outputDesc->mFormat,
785 &outputDesc->mChannelMask,
786 &outputDesc->mLatency,
787 outputDesc->mFlags,
788 offloadInfo);
789
790 // only accept an output with the requested parameters
791 if (output == 0 ||
792 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
793 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
794 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
795 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
796 "format %d %d, channelMask %04x %04x", output, samplingRate,
797 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
798 outputDesc->mChannelMask);
799 if (output != 0) {
800 mpClientInterface->closeOutput(output);
801 }
Eric Laurente552edb2014-03-10 17:42:56 -0700802 return 0;
803 }
804 audio_io_handle_t srcOutput = getOutputForEffect();
805 addOutput(output, outputDesc);
806 audio_io_handle_t dstOutput = getOutputForEffect();
807 if (dstOutput == output) {
808 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
809 }
810 mPreviousOutputs = mOutputs;
811 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700812 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700813 return output;
814 }
815
816 // ignoring channel mask due to downmix capability in mixer
817
818 // open a non direct output
819
820 // for non direct outputs, only PCM is supported
821 if (audio_is_linear_pcm(format)) {
822 // get which output is suitable for the specified stream. The actual
823 // routing change will happen when startOutput() will be called
824 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
825
826 output = selectOutput(outputs, flags);
827 }
828 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
829 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
830
831 ALOGV("getOutput() returns output %d", output);
832
833 return output;
834}
835
Eric Laurente0720872014-03-11 09:30:41 -0700836audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700837 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700838{
839 // select one output among several that provide a path to a particular device or set of
840 // devices (the list was previously build by getOutputsForDevice()).
841 // The priority is as follows:
842 // 1: the output with the highest number of requested policy flags
843 // 2: the primary output
844 // 3: the first output in the list
845
846 if (outputs.size() == 0) {
847 return 0;
848 }
849 if (outputs.size() == 1) {
850 return outputs[0];
851 }
852
853 int maxCommonFlags = 0;
854 audio_io_handle_t outputFlags = 0;
855 audio_io_handle_t outputPrimary = 0;
856
857 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700858 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700859 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700860 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700861 if (commonFlags > maxCommonFlags) {
862 outputFlags = outputs[i];
863 maxCommonFlags = commonFlags;
864 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
865 }
866 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
867 outputPrimary = outputs[i];
868 }
869 }
870 }
871
872 if (outputFlags != 0) {
873 return outputFlags;
874 }
875 if (outputPrimary != 0) {
876 return outputPrimary;
877 }
878
879 return outputs[0];
880}
881
Eric Laurente0720872014-03-11 09:30:41 -0700882status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700883 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700884 int session)
885{
886 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
887 ssize_t index = mOutputs.indexOfKey(output);
888 if (index < 0) {
889 ALOGW("startOutput() unknown output %d", output);
890 return BAD_VALUE;
891 }
892
Eric Laurent1f2f2232014-06-02 12:01:23 -0700893 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700894
895 // increment usage count for this stream on the requested output:
896 // NOTE that the usage count is the same for duplicated output and hardware output which is
897 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
898 outputDesc->changeRefCount(stream, 1);
899
900 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700901 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700902 routing_strategy strategy = getStrategy(stream);
903 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
904 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
905 uint32_t waitMs = 0;
906 bool force = false;
907 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700908 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700909 if (desc != outputDesc) {
910 // force a device change if any other output is managed by the same hw
911 // module and has a current device selection that differs from selected device.
912 // In this case, the audio HAL must receive the new device selection so that it can
913 // change the device currently selected by the other active output.
914 if (outputDesc->sharesHwModuleWith(desc) &&
915 desc->device() != newDevice) {
916 force = true;
917 }
918 // wait for audio on other active outputs to be presented when starting
919 // a notification so that audio focus effect can propagate.
920 uint32_t latency = desc->latency();
921 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
922 waitMs = latency;
923 }
924 }
925 }
926 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
927
928 // handle special case for sonification while in call
929 if (isInCall()) {
930 handleIncallSonification(stream, true, false);
931 }
932
933 // apply volume rules for current stream and device if necessary
934 checkAndSetVolume(stream,
935 mStreams[stream].getVolumeIndex(newDevice),
936 output,
937 newDevice);
938
939 // update the outputs if starting an output with a stream that can affect notification
940 // routing
941 handleNotificationRoutingForStream(stream);
942 if (waitMs > muteWaitMs) {
943 usleep((waitMs - muteWaitMs) * 2 * 1000);
944 }
945 }
946 return NO_ERROR;
947}
948
949
Eric Laurente0720872014-03-11 09:30:41 -0700950status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700951 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700952 int session)
953{
954 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
955 ssize_t index = mOutputs.indexOfKey(output);
956 if (index < 0) {
957 ALOGW("stopOutput() unknown output %d", output);
958 return BAD_VALUE;
959 }
960
Eric Laurent1f2f2232014-06-02 12:01:23 -0700961 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700962
963 // handle special case for sonification while in call
964 if (isInCall()) {
965 handleIncallSonification(stream, false, false);
966 }
967
968 if (outputDesc->mRefCount[stream] > 0) {
969 // decrement usage count of this stream on the output
970 outputDesc->changeRefCount(stream, -1);
971 // store time at which the stream was stopped - see isStreamActive()
972 if (outputDesc->mRefCount[stream] == 0) {
973 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700974 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700975 // delay the device switch by twice the latency because stopOutput() is executed when
976 // the track stop() command is received and at that time the audio track buffer can
977 // still contain data that needs to be drained. The latency only covers the audio HAL
978 // and kernel buffers. Also the latency does not always include additional delay in the
979 // audio path (audio DSP, CODEC ...)
980 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
981
982 // force restoring the device selection on other active outputs if it differs from the
983 // one being selected for this output
984 for (size_t i = 0; i < mOutputs.size(); i++) {
985 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700986 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700987 if (curOutput != output &&
988 desc->isActive() &&
989 outputDesc->sharesHwModuleWith(desc) &&
990 (newDevice != desc->device())) {
991 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700992 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700993 true,
994 outputDesc->mLatency*2);
995 }
996 }
997 // update the outputs if stopping one with a stream that can affect notification routing
998 handleNotificationRoutingForStream(stream);
999 }
1000 return NO_ERROR;
1001 } else {
1002 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1003 return INVALID_OPERATION;
1004 }
1005}
1006
Eric Laurente0720872014-03-11 09:30:41 -07001007void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001008{
1009 ALOGV("releaseOutput() %d", output);
1010 ssize_t index = mOutputs.indexOfKey(output);
1011 if (index < 0) {
1012 ALOGW("releaseOutput() releasing unknown output %d", output);
1013 return;
1014 }
1015
1016#ifdef AUDIO_POLICY_TEST
1017 int testIndex = testOutputIndex(output);
1018 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001019 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001020 if (outputDesc->isActive()) {
1021 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001022 mOutputs.removeItem(output);
1023 mTestOutputs[testIndex] = 0;
1024 }
1025 return;
1026 }
1027#endif //AUDIO_POLICY_TEST
1028
Eric Laurent1f2f2232014-06-02 12:01:23 -07001029 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001030 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001031 if (desc->mDirectOpenCount <= 0) {
1032 ALOGW("releaseOutput() invalid open count %d for output %d",
1033 desc->mDirectOpenCount, output);
1034 return;
1035 }
1036 if (--desc->mDirectOpenCount == 0) {
1037 closeOutput(output);
1038 // If effects where present on the output, audioflinger moved them to the primary
1039 // output by default: move them back to the appropriate output.
1040 audio_io_handle_t dstOutput = getOutputForEffect();
1041 if (dstOutput != mPrimaryOutput) {
1042 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1043 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001044 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001045 }
1046 }
1047}
1048
1049
Eric Laurente0720872014-03-11 09:30:41 -07001050audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001051 uint32_t samplingRate,
1052 audio_format_t format,
1053 audio_channel_mask_t channelMask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001054 audio_in_acoustics_t acoustics,
1055 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001056{
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001057 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x, "
1058 "flags %#x",
1059 inputSource, samplingRate, format, channelMask, acoustics, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001060
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001061 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001062
1063 if (device == AUDIO_DEVICE_NONE) {
1064 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1065 return 0;
1066 }
1067
1068 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001069 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001070 case AUDIO_SOURCE_VOICE_UPLINK:
1071 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1072 break;
1073 case AUDIO_SOURCE_VOICE_DOWNLINK:
1074 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1075 break;
1076 case AUDIO_SOURCE_VOICE_CALL:
1077 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1078 break;
1079 default:
1080 break;
1081 }
1082
Eric Laurent1c333e22014-05-20 10:48:17 -07001083 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001084 samplingRate,
1085 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001086 channelMask,
1087 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001088 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001089 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1090 "channelMask 0x%X, flags %#x",
1091 device, samplingRate, format, channelMask, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001092 return 0;
1093 }
1094
1095 if (profile->mModule->mHandle == 0) {
1096 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1097 return 0;
1098 }
1099
Eric Laurent1f2f2232014-06-02 12:01:23 -07001100 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001101
1102 inputDesc->mInputSource = inputSource;
1103 inputDesc->mDevice = device;
1104 inputDesc->mSamplingRate = samplingRate;
1105 inputDesc->mFormat = format;
1106 inputDesc->mChannelMask = channelMask;
1107 inputDesc->mRefCount = 0;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001108 inputDesc->mOpenRefCount = 1;
1109
1110 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurente552edb2014-03-10 17:42:56 -07001111 &inputDesc->mDevice,
1112 &inputDesc->mSamplingRate,
1113 &inputDesc->mFormat,
Glenn Kastenec40d282014-07-15 15:31:26 -07001114 &inputDesc->mChannelMask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001115 flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001116
1117 // only accept input with the exact requested set of parameters
1118 if (input == 0 ||
1119 (samplingRate != inputDesc->mSamplingRate) ||
1120 (format != inputDesc->mFormat) ||
1121 (channelMask != inputDesc->mChannelMask)) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001122 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurente552edb2014-03-10 17:42:56 -07001123 samplingRate, format, channelMask);
1124 if (input != 0) {
1125 mpClientInterface->closeInput(input);
1126 }
Eric Laurente552edb2014-03-10 17:42:56 -07001127 return 0;
1128 }
Eric Laurentd4692962014-05-05 18:13:44 -07001129 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001130 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001131 return input;
1132}
1133
Eric Laurente0720872014-03-11 09:30:41 -07001134status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001135{
1136 ALOGV("startInput() input %d", input);
1137 ssize_t index = mInputs.indexOfKey(input);
1138 if (index < 0) {
1139 ALOGW("startInput() unknown input %d", input);
1140 return BAD_VALUE;
1141 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001142 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001143
Glenn Kasten74a8e252014-07-24 14:09:55 -07001144 // virtual input devices are compatible with other input devices
1145 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1146
1147 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001148 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001149 if (activeInput != 0 && activeInput != input) {
1150
1151 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1152 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001153 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001154 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001155 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001156 stopInput(activeInput);
1157 releaseInput(activeInput);
1158 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001159 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001160 return INVALID_OPERATION;
1161 }
1162 }
1163 }
1164
Glenn Kasten74a8e252014-07-24 14:09:55 -07001165 if (inputDesc->mRefCount == 0) {
1166 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001167
Glenn Kasten74a8e252014-07-24 14:09:55 -07001168 // Automatically enable the remote submix output when input is started.
1169 // For remote submix (a virtual device), we open only one input per capture request.
1170 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1171 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1172 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1173 }
Eric Laurente552edb2014-03-10 17:42:56 -07001174 }
1175
Eric Laurente552edb2014-03-10 17:42:56 -07001176 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1177
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001178 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001179 return NO_ERROR;
1180}
1181
Eric Laurente0720872014-03-11 09:30:41 -07001182status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001183{
1184 ALOGV("stopInput() input %d", input);
1185 ssize_t index = mInputs.indexOfKey(input);
1186 if (index < 0) {
1187 ALOGW("stopInput() unknown input %d", input);
1188 return BAD_VALUE;
1189 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001190 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001191
1192 if (inputDesc->mRefCount == 0) {
1193 ALOGW("stopInput() input %d already stopped", input);
1194 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001195 }
1196
1197 inputDesc->mRefCount--;
1198 if (inputDesc->mRefCount == 0) {
1199
Eric Laurente552edb2014-03-10 17:42:56 -07001200 // automatically disable the remote submix output when input is stopped
1201 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1202 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001203 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001204 }
1205
Eric Laurent1c333e22014-05-20 10:48:17 -07001206 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001207 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001208 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001209}
1210
Eric Laurente0720872014-03-11 09:30:41 -07001211void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001212{
1213 ALOGV("releaseInput() %d", input);
1214 ssize_t index = mInputs.indexOfKey(input);
1215 if (index < 0) {
1216 ALOGW("releaseInput() releasing unknown input %d", input);
1217 return;
1218 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001219 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1220 ALOG_ASSERT(inputDesc != 0);
1221 if (inputDesc->mOpenRefCount == 0) {
1222 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1223 return;
1224 }
1225 inputDesc->mOpenRefCount--;
1226 if (inputDesc->mOpenRefCount > 0) {
1227 ALOGV("releaseInput() exit > 0");
1228 return;
1229 }
1230
Eric Laurente552edb2014-03-10 17:42:56 -07001231 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001232 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001233 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001234 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001235 ALOGV("releaseInput() exit");
1236}
1237
Eric Laurentd4692962014-05-05 18:13:44 -07001238void AudioPolicyManager::closeAllInputs() {
1239 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1240 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1241 }
1242 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001243 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001244}
1245
Eric Laurente0720872014-03-11 09:30:41 -07001246void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001247 int indexMin,
1248 int indexMax)
1249{
1250 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1251 if (indexMin < 0 || indexMin >= indexMax) {
1252 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1253 return;
1254 }
1255 mStreams[stream].mIndexMin = indexMin;
1256 mStreams[stream].mIndexMax = indexMax;
1257}
1258
Eric Laurente0720872014-03-11 09:30:41 -07001259status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001260 int index,
1261 audio_devices_t device)
1262{
1263
1264 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1265 return BAD_VALUE;
1266 }
1267 if (!audio_is_output_device(device)) {
1268 return BAD_VALUE;
1269 }
1270
1271 // Force max volume if stream cannot be muted
1272 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1273
1274 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1275 stream, device, index);
1276
1277 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1278 // clear all device specific values
1279 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1280 mStreams[stream].mIndexCur.clear();
1281 }
1282 mStreams[stream].mIndexCur.add(device, index);
1283
1284 // compute and apply stream volume on all outputs according to connected device
1285 status_t status = NO_ERROR;
1286 for (size_t i = 0; i < mOutputs.size(); i++) {
1287 audio_devices_t curDevice =
1288 getDeviceForVolume(mOutputs.valueAt(i)->device());
1289 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1290 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1291 if (volStatus != NO_ERROR) {
1292 status = volStatus;
1293 }
1294 }
1295 }
1296 return status;
1297}
1298
Eric Laurente0720872014-03-11 09:30:41 -07001299status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001300 int *index,
1301 audio_devices_t device)
1302{
1303 if (index == NULL) {
1304 return BAD_VALUE;
1305 }
1306 if (!audio_is_output_device(device)) {
1307 return BAD_VALUE;
1308 }
1309 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1310 // the strategy the stream belongs to.
1311 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1312 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1313 }
1314 device = getDeviceForVolume(device);
1315
1316 *index = mStreams[stream].getVolumeIndex(device);
1317 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1318 return NO_ERROR;
1319}
1320
Eric Laurente0720872014-03-11 09:30:41 -07001321audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001322 const SortedVector<audio_io_handle_t>& outputs)
1323{
1324 // select one output among several suitable for global effects.
1325 // The priority is as follows:
1326 // 1: An offloaded output. If the effect ends up not being offloadable,
1327 // AudioFlinger will invalidate the track and the offloaded output
1328 // will be closed causing the effect to be moved to a PCM output.
1329 // 2: A deep buffer output
1330 // 3: the first output in the list
1331
1332 if (outputs.size() == 0) {
1333 return 0;
1334 }
1335
1336 audio_io_handle_t outputOffloaded = 0;
1337 audio_io_handle_t outputDeepBuffer = 0;
1338
1339 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001340 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001341 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001342 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1343 outputOffloaded = outputs[i];
1344 }
1345 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1346 outputDeepBuffer = outputs[i];
1347 }
1348 }
1349
1350 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1351 outputOffloaded, outputDeepBuffer);
1352 if (outputOffloaded != 0) {
1353 return outputOffloaded;
1354 }
1355 if (outputDeepBuffer != 0) {
1356 return outputDeepBuffer;
1357 }
1358
1359 return outputs[0];
1360}
1361
Eric Laurente0720872014-03-11 09:30:41 -07001362audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001363{
1364 // apply simple rule where global effects are attached to the same output as MUSIC streams
1365
Eric Laurent3b73df72014-03-11 09:06:29 -07001366 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001367 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1368 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1369
1370 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1371 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1372 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1373
1374 return output;
1375}
1376
Eric Laurente0720872014-03-11 09:30:41 -07001377status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001378 audio_io_handle_t io,
1379 uint32_t strategy,
1380 int session,
1381 int id)
1382{
1383 ssize_t index = mOutputs.indexOfKey(io);
1384 if (index < 0) {
1385 index = mInputs.indexOfKey(io);
1386 if (index < 0) {
1387 ALOGW("registerEffect() unknown io %d", io);
1388 return INVALID_OPERATION;
1389 }
1390 }
1391
1392 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1393 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1394 desc->name, desc->memoryUsage);
1395 return INVALID_OPERATION;
1396 }
1397 mTotalEffectsMemory += desc->memoryUsage;
1398 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1399 desc->name, io, strategy, session, id);
1400 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1401
Eric Laurent1f2f2232014-06-02 12:01:23 -07001402 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1403 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1404 effectDesc->mIo = io;
1405 effectDesc->mStrategy = (routing_strategy)strategy;
1406 effectDesc->mSession = session;
1407 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001408
Eric Laurent1f2f2232014-06-02 12:01:23 -07001409 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001410
1411 return NO_ERROR;
1412}
1413
Eric Laurente0720872014-03-11 09:30:41 -07001414status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001415{
1416 ssize_t index = mEffects.indexOfKey(id);
1417 if (index < 0) {
1418 ALOGW("unregisterEffect() unknown effect ID %d", id);
1419 return INVALID_OPERATION;
1420 }
1421
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001423
Eric Laurent1f2f2232014-06-02 12:01:23 -07001424 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001425
Eric Laurent1f2f2232014-06-02 12:01:23 -07001426 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001427 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001428 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1429 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001430 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001431 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001432 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001433 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001434
1435 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001436
1437 return NO_ERROR;
1438}
1439
Eric Laurente0720872014-03-11 09:30:41 -07001440status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001441{
1442 ssize_t index = mEffects.indexOfKey(id);
1443 if (index < 0) {
1444 ALOGW("unregisterEffect() unknown effect ID %d", id);
1445 return INVALID_OPERATION;
1446 }
1447
1448 return setEffectEnabled(mEffects.valueAt(index), enabled);
1449}
1450
Eric Laurent1f2f2232014-06-02 12:01:23 -07001451status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001452{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001453 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001454 ALOGV("setEffectEnabled(%s) effect already %s",
1455 enabled?"true":"false", enabled?"enabled":"disabled");
1456 return INVALID_OPERATION;
1457 }
1458
1459 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001460 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001461 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001462 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001463 return INVALID_OPERATION;
1464 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001465 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001466 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1467 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001468 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001469 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001470 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1471 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001472 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001473 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001474 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1475 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001476 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001477 return NO_ERROR;
1478}
1479
Eric Laurente0720872014-03-11 09:30:41 -07001480bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001481{
1482 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001483 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1484 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1485 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001486 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001487 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001488 return true;
1489 }
1490 }
1491 return false;
1492}
1493
Eric Laurente0720872014-03-11 09:30:41 -07001494bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001495{
1496 nsecs_t sysTime = systemTime();
1497 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001498 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001499 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001500 return true;
1501 }
1502 }
1503 return false;
1504}
1505
Eric Laurente0720872014-03-11 09:30:41 -07001506bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001507 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001508{
1509 nsecs_t sysTime = systemTime();
1510 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001511 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001512 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001513 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001514 return true;
1515 }
1516 }
1517 return false;
1518}
1519
Eric Laurente0720872014-03-11 09:30:41 -07001520bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001521{
1522 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001523 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001524 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001525 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001526 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1527 && (inputDescriptor->mRefCount > 0)) {
1528 return true;
1529 }
1530 }
1531 return false;
1532}
1533
1534
Eric Laurente0720872014-03-11 09:30:41 -07001535status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001536{
1537 const size_t SIZE = 256;
1538 char buffer[SIZE];
1539 String8 result;
1540
1541 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1542 result.append(buffer);
1543
1544 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1545 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001546 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1547 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001548 snprintf(buffer, SIZE, " Force use for communications %d\n",
1549 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001550 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001551 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001552 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001553 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001554 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001555 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001556 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001557 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001558 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001559 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1560 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1561 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001562
Eric Laurent3a4311c2014-03-17 12:00:47 -07001563 snprintf(buffer, SIZE, " Available output devices:\n");
1564 result.append(buffer);
1565 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001566 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001567 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001568 }
1569 snprintf(buffer, SIZE, "\n Available input devices:\n");
1570 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001571 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001572 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001573 }
Eric Laurente552edb2014-03-10 17:42:56 -07001574
1575 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1576 write(fd, buffer, strlen(buffer));
1577 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001578 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001579 write(fd, buffer, strlen(buffer));
1580 mHwModules[i]->dump(fd);
1581 }
1582
1583 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1584 write(fd, buffer, strlen(buffer));
1585 for (size_t i = 0; i < mOutputs.size(); i++) {
1586 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1587 write(fd, buffer, strlen(buffer));
1588 mOutputs.valueAt(i)->dump(fd);
1589 }
1590
1591 snprintf(buffer, SIZE, "\nInputs dump:\n");
1592 write(fd, buffer, strlen(buffer));
1593 for (size_t i = 0; i < mInputs.size(); i++) {
1594 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1595 write(fd, buffer, strlen(buffer));
1596 mInputs.valueAt(i)->dump(fd);
1597 }
1598
1599 snprintf(buffer, SIZE, "\nStreams dump:\n");
1600 write(fd, buffer, strlen(buffer));
1601 snprintf(buffer, SIZE,
1602 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1603 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001604 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001605 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001606 write(fd, buffer, strlen(buffer));
1607 mStreams[i].dump(fd);
1608 }
1609
1610 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1611 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1612 write(fd, buffer, strlen(buffer));
1613
1614 snprintf(buffer, SIZE, "Registered effects:\n");
1615 write(fd, buffer, strlen(buffer));
1616 for (size_t i = 0; i < mEffects.size(); i++) {
1617 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1618 write(fd, buffer, strlen(buffer));
1619 mEffects.valueAt(i)->dump(fd);
1620 }
1621
1622
1623 return NO_ERROR;
1624}
1625
1626// This function checks for the parameters which can be offloaded.
1627// This can be enhanced depending on the capability of the DSP and policy
1628// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001629bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001630{
1631 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001632 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001633 offloadInfo.sample_rate, offloadInfo.channel_mask,
1634 offloadInfo.format,
1635 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1636 offloadInfo.has_video);
1637
1638 // Check if offload has been disabled
1639 char propValue[PROPERTY_VALUE_MAX];
1640 if (property_get("audio.offload.disable", propValue, "0")) {
1641 if (atoi(propValue) != 0) {
1642 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1643 return false;
1644 }
1645 }
1646
1647 // Check if stream type is music, then only allow offload as of now.
1648 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1649 {
1650 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1651 return false;
1652 }
1653
1654 //TODO: enable audio offloading with video when ready
1655 if (offloadInfo.has_video)
1656 {
1657 ALOGV("isOffloadSupported: has_video == true, returning false");
1658 return false;
1659 }
1660
1661 //If duration is less than minimum value defined in property, return false
1662 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1663 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1664 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1665 return false;
1666 }
1667 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1668 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1669 return false;
1670 }
1671
1672 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1673 // creating an offloaded track and tearing it down immediately after start when audioflinger
1674 // detects there is an active non offloadable effect.
1675 // FIXME: We should check the audio session here but we do not have it in this context.
1676 // This may prevent offloading in rare situations where effects are left active by apps
1677 // in the background.
1678 if (isNonOffloadableEffectEnabled()) {
1679 return false;
1680 }
1681
1682 // See if there is a profile to support this.
1683 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001684 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001685 offloadInfo.sample_rate,
1686 offloadInfo.format,
1687 offloadInfo.channel_mask,
1688 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001689 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1690 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001691}
1692
Eric Laurent6a94d692014-05-20 11:18:06 -07001693status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1694 audio_port_type_t type,
1695 unsigned int *num_ports,
1696 struct audio_port *ports,
1697 unsigned int *generation)
1698{
1699 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1700 generation == NULL) {
1701 return BAD_VALUE;
1702 }
1703 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1704 if (ports == NULL) {
1705 *num_ports = 0;
1706 }
1707
1708 size_t portsWritten = 0;
1709 size_t portsMax = *num_ports;
1710 *num_ports = 0;
1711 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1712 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1713 for (size_t i = 0;
1714 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1715 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1716 }
1717 *num_ports += mAvailableOutputDevices.size();
1718 }
1719 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1720 for (size_t i = 0;
1721 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1722 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1723 }
1724 *num_ports += mAvailableInputDevices.size();
1725 }
1726 }
1727 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1728 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1729 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1730 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1731 }
1732 *num_ports += mInputs.size();
1733 }
1734 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001735 size_t numOutputs = 0;
1736 for (size_t i = 0; i < mOutputs.size(); i++) {
1737 if (!mOutputs[i]->isDuplicated()) {
1738 numOutputs++;
1739 if (portsWritten < portsMax) {
1740 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1741 }
1742 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001743 }
Eric Laurent84c70242014-06-23 08:46:27 -07001744 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001745 }
1746 }
1747 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001748 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001749 return NO_ERROR;
1750}
1751
1752status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1753{
1754 return NO_ERROR;
1755}
1756
Eric Laurent1f2f2232014-06-02 12:01:23 -07001757sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001758 audio_port_handle_t id) const
1759{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001760 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001761 for (size_t i = 0; i < mOutputs.size(); i++) {
1762 outputDesc = mOutputs.valueAt(i);
1763 if (outputDesc->mId == id) {
1764 break;
1765 }
1766 }
1767 return outputDesc;
1768}
1769
Eric Laurent1f2f2232014-06-02 12:01:23 -07001770sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001771 audio_port_handle_t id) const
1772{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001773 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001774 for (size_t i = 0; i < mInputs.size(); i++) {
1775 inputDesc = mInputs.valueAt(i);
1776 if (inputDesc->mId == id) {
1777 break;
1778 }
1779 }
1780 return inputDesc;
1781}
1782
Eric Laurent1f2f2232014-06-02 12:01:23 -07001783sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1784 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001785{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001786 sp <HwModule> module;
1787
Eric Laurent6a94d692014-05-20 11:18:06 -07001788 for (size_t i = 0; i < mHwModules.size(); i++) {
1789 if (mHwModules[i]->mHandle == 0) {
1790 continue;
1791 }
1792 if (audio_is_output_device(device)) {
1793 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1794 {
1795 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1796 return mHwModules[i];
1797 }
1798 }
1799 } else {
1800 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1801 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1802 device & ~AUDIO_DEVICE_BIT_IN) {
1803 return mHwModules[i];
1804 }
1805 }
1806 }
1807 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001808 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001809}
1810
Eric Laurent1f2f2232014-06-02 12:01:23 -07001811sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001812{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001813 sp <HwModule> module;
1814
Eric Laurent1afeecb2014-05-14 08:52:28 -07001815 for (size_t i = 0; i < mHwModules.size(); i++)
1816 {
1817 if (strcmp(mHwModules[i]->mName, name) == 0) {
1818 return mHwModules[i];
1819 }
1820 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001821 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001822}
1823
1824
Eric Laurent6a94d692014-05-20 11:18:06 -07001825status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1826 audio_patch_handle_t *handle,
1827 uid_t uid)
1828{
1829 ALOGV("createAudioPatch()");
1830
1831 if (handle == NULL || patch == NULL) {
1832 return BAD_VALUE;
1833 }
1834 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1835
1836 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1837 return INVALID_OPERATION;
1838 }
1839 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1840 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1841 return INVALID_OPERATION;
1842 }
1843
1844 sp<AudioPatch> patchDesc;
1845 ssize_t index = mAudioPatches.indexOfKey(*handle);
1846
1847 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1848 patch->sinks[0].type);
1849 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1850 patch->sources[0].role,
1851 patch->sources[0].type);
1852
1853 if (index >= 0) {
1854 patchDesc = mAudioPatches.valueAt(index);
1855 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1856 mUidCached, patchDesc->mUid, uid);
1857 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1858 return INVALID_OPERATION;
1859 }
1860 } else {
1861 *handle = 0;
1862 }
1863
1864 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1865 // TODO add support for mix to mix connection
1866 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1867 ALOGV("createAudioPatch() source mix sink not device");
1868 return BAD_VALUE;
1869 }
1870 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001871 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001872 if (outputDesc == NULL) {
1873 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1874 return BAD_VALUE;
1875 }
Eric Laurent84c70242014-06-23 08:46:27 -07001876 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1877 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001878 if (patchDesc != 0) {
1879 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1880 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1881 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1882 return BAD_VALUE;
1883 }
1884 }
1885 sp<DeviceDescriptor> devDesc =
1886 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1887 if (devDesc == 0) {
1888 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1889 return BAD_VALUE;
1890 }
1891
Eric Laurent84c70242014-06-23 08:46:27 -07001892 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001893 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07001894 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07001895 patch->sources[0].format,
1896 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001897 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001898 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001899 return INVALID_OPERATION;
1900 }
1901 // TODO: reconfigure output format and channels here
1902 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001903 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001904 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001905 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001906 true,
1907 0,
1908 handle);
1909 index = mAudioPatches.indexOfKey(*handle);
1910 if (index >= 0) {
1911 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1912 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1913 }
1914 patchDesc = mAudioPatches.valueAt(index);
1915 patchDesc->mUid = uid;
1916 ALOGV("createAudioPatch() success");
1917 } else {
1918 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1919 return INVALID_OPERATION;
1920 }
1921 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1922 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1923 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001924 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001925 if (inputDesc == NULL) {
1926 return BAD_VALUE;
1927 }
1928 if (patchDesc != 0) {
1929 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1930 return BAD_VALUE;
1931 }
1932 }
1933 sp<DeviceDescriptor> devDesc =
1934 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1935 if (devDesc == 0) {
1936 return BAD_VALUE;
1937 }
1938
Eric Laurent84c70242014-06-23 08:46:27 -07001939 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07001940 patch->sinks[0].sample_rate,
1941 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07001942 patch->sinks[0].format,
1943 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001944 // FIXME for the parameter type,
1945 // and the NONE
1946 (audio_output_flags_t)
1947 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07001948 return INVALID_OPERATION;
1949 }
1950 // TODO: reconfigure output format and channels here
1951 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001952 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001953 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001954 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001955 true,
1956 handle);
1957 index = mAudioPatches.indexOfKey(*handle);
1958 if (index >= 0) {
1959 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1960 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1961 }
1962 patchDesc = mAudioPatches.valueAt(index);
1963 patchDesc->mUid = uid;
1964 ALOGV("createAudioPatch() success");
1965 } else {
1966 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1967 return INVALID_OPERATION;
1968 }
1969 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1970 // device to device connection
1971 if (patchDesc != 0) {
1972 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1973 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1974 return BAD_VALUE;
1975 }
1976 }
1977
1978 sp<DeviceDescriptor> srcDeviceDesc =
1979 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1980 sp<DeviceDescriptor> sinkDeviceDesc =
1981 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1982 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1983 return BAD_VALUE;
1984 }
1985 //update source and sink with our own data as the data passed in the patch may
1986 // be incomplete.
1987 struct audio_patch newPatch = *patch;
1988 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1989 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1990
Eric Laurent6a94d692014-05-20 11:18:06 -07001991 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07001992 SortedVector<audio_io_handle_t> outputs =
1993 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
1994 // if the sink device is reachable via an opened output stream, request to go via
1995 // this output stream by adding a second source to the patch description
1996 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
1997 if (output != AUDIO_IO_HANDLE_NONE) {
1998 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
1999 if (outputDesc->isDuplicated()) {
2000 return INVALID_OPERATION;
2001 }
2002 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2003 newPatch.num_sources = 2;
2004 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002005 }
2006 // TODO: check from routing capabilities in config file and other conflicting patches
2007
2008 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2009 if (index >= 0) {
2010 afPatchHandle = patchDesc->mAfPatchHandle;
2011 }
2012
2013 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2014 &afPatchHandle,
2015 0);
2016 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2017 status, afPatchHandle);
2018 if (status == NO_ERROR) {
2019 if (index < 0) {
2020 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2021 &newPatch, uid);
2022 addAudioPatch(patchDesc->mHandle, patchDesc);
2023 } else {
2024 patchDesc->mPatch = newPatch;
2025 }
2026 patchDesc->mAfPatchHandle = afPatchHandle;
2027 *handle = patchDesc->mHandle;
2028 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002029 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002030 } else {
2031 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2032 status);
2033 return INVALID_OPERATION;
2034 }
2035 } else {
2036 return BAD_VALUE;
2037 }
2038 } else {
2039 return BAD_VALUE;
2040 }
2041 return NO_ERROR;
2042}
2043
2044status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2045 uid_t uid)
2046{
2047 ALOGV("releaseAudioPatch() patch %d", handle);
2048
2049 ssize_t index = mAudioPatches.indexOfKey(handle);
2050
2051 if (index < 0) {
2052 return BAD_VALUE;
2053 }
2054 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2055 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2056 mUidCached, patchDesc->mUid, uid);
2057 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2058 return INVALID_OPERATION;
2059 }
2060
2061 struct audio_patch *patch = &patchDesc->mPatch;
2062 patchDesc->mUid = mUidCached;
2063 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002064 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002065 if (outputDesc == NULL) {
2066 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2067 return BAD_VALUE;
2068 }
2069
2070 setOutputDevice(outputDesc->mIoHandle,
2071 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2072 true,
2073 0,
2074 NULL);
2075 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2076 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002077 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002078 if (inputDesc == NULL) {
2079 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2080 return BAD_VALUE;
2081 }
2082 setInputDevice(inputDesc->mIoHandle,
2083 getNewInputDevice(inputDesc->mIoHandle),
2084 true,
2085 NULL);
2086 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2087 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2088 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2089 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2090 status, patchDesc->mAfPatchHandle);
2091 removeAudioPatch(patchDesc->mHandle);
2092 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002093 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002094 } else {
2095 return BAD_VALUE;
2096 }
2097 } else {
2098 return BAD_VALUE;
2099 }
2100 return NO_ERROR;
2101}
2102
2103status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2104 struct audio_patch *patches,
2105 unsigned int *generation)
2106{
2107 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2108 generation == NULL) {
2109 return BAD_VALUE;
2110 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002111 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002112 *num_patches, patches, mAudioPatches.size());
2113 if (patches == NULL) {
2114 *num_patches = 0;
2115 }
2116
2117 size_t patchesWritten = 0;
2118 size_t patchesMax = *num_patches;
2119 for (size_t i = 0;
2120 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2121 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2122 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002123 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002124 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2125 }
2126 *num_patches = mAudioPatches.size();
2127
2128 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002129 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002130 return NO_ERROR;
2131}
2132
Eric Laurente1715a42014-05-20 11:30:42 -07002133status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002134{
Eric Laurente1715a42014-05-20 11:30:42 -07002135 ALOGV("setAudioPortConfig()");
2136
2137 if (config == NULL) {
2138 return BAD_VALUE;
2139 }
2140 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2141 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002142 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2143 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002144 }
2145
Eric Laurenta121f902014-06-03 13:32:54 -07002146 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002147 if (config->type == AUDIO_PORT_TYPE_MIX) {
2148 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002149 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002150 if (outputDesc == NULL) {
2151 return BAD_VALUE;
2152 }
Eric Laurent84c70242014-06-23 08:46:27 -07002153 ALOG_ASSERT(!outputDesc->isDuplicated(),
2154 "setAudioPortConfig() called on duplicated output %d",
2155 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002156 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002157 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002158 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002159 if (inputDesc == NULL) {
2160 return BAD_VALUE;
2161 }
Eric Laurenta121f902014-06-03 13:32:54 -07002162 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002163 } else {
2164 return BAD_VALUE;
2165 }
2166 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2167 sp<DeviceDescriptor> deviceDesc;
2168 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2169 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2170 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2171 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2172 } else {
2173 return BAD_VALUE;
2174 }
2175 if (deviceDesc == NULL) {
2176 return BAD_VALUE;
2177 }
Eric Laurenta121f902014-06-03 13:32:54 -07002178 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002179 } else {
2180 return BAD_VALUE;
2181 }
2182
Eric Laurenta121f902014-06-03 13:32:54 -07002183 struct audio_port_config backupConfig;
2184 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2185 if (status == NO_ERROR) {
2186 struct audio_port_config newConfig;
2187 audioPortConfig->toAudioPortConfig(&newConfig, config);
2188 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002189 }
Eric Laurenta121f902014-06-03 13:32:54 -07002190 if (status != NO_ERROR) {
2191 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002192 }
Eric Laurente1715a42014-05-20 11:30:42 -07002193
2194 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002195}
2196
2197void AudioPolicyManager::clearAudioPatches(uid_t uid)
2198{
2199 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2200 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2201 if (patchDesc->mUid == uid) {
2202 // releaseAudioPatch() removes the patch from mAudioPatches
2203 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2204 i--;
2205 }
2206 }
2207 }
2208}
2209
2210status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2211 const sp<AudioPatch>& patch)
2212{
2213 ssize_t index = mAudioPatches.indexOfKey(handle);
2214
2215 if (index >= 0) {
2216 ALOGW("addAudioPatch() patch %d already in", handle);
2217 return ALREADY_EXISTS;
2218 }
2219 mAudioPatches.add(handle, patch);
2220 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2221 "sink handle %d",
2222 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2223 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2224 return NO_ERROR;
2225}
2226
2227status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2228{
2229 ssize_t index = mAudioPatches.indexOfKey(handle);
2230
2231 if (index < 0) {
2232 ALOGW("removeAudioPatch() patch %d not in", handle);
2233 return ALREADY_EXISTS;
2234 }
2235 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2236 mAudioPatches.valueAt(index)->mAfPatchHandle);
2237 mAudioPatches.removeItemsAt(index);
2238 return NO_ERROR;
2239}
2240
Eric Laurente552edb2014-03-10 17:42:56 -07002241// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002242// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002243// ----------------------------------------------------------------------------
2244
Eric Laurent3a4311c2014-03-17 12:00:47 -07002245uint32_t AudioPolicyManager::nextUniqueId()
2246{
2247 return android_atomic_inc(&mNextUniqueId);
2248}
2249
Eric Laurent6a94d692014-05-20 11:18:06 -07002250uint32_t AudioPolicyManager::nextAudioPortGeneration()
2251{
2252 return android_atomic_inc(&mAudioPortGeneration);
2253}
2254
Eric Laurente0720872014-03-11 09:30:41 -07002255AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002256 :
2257#ifdef AUDIO_POLICY_TEST
2258 Thread(false),
2259#endif //AUDIO_POLICY_TEST
2260 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002261 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002262 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2263 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002264 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002265 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2266 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002267{
Eric Laurent6a94d692014-05-20 11:18:06 -07002268 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002269 mpClientInterface = clientInterface;
2270
Eric Laurent3b73df72014-03-11 09:06:29 -07002271 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2272 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002273 }
2274
Eric Laurent1afeecb2014-05-14 08:52:28 -07002275 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002276 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2277 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2278 ALOGE("could not load audio policy configuration file, setting defaults");
2279 defaultAudioPolicyConfig();
2280 }
2281 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002282 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002283
2284 // must be done after reading the policy
2285 initializeVolumeCurves();
2286
2287 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002288 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2289 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002290 for (size_t i = 0; i < mHwModules.size(); i++) {
2291 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2292 if (mHwModules[i]->mHandle == 0) {
2293 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2294 continue;
2295 }
2296 // open all output streams needed to access attached devices
2297 // except for direct output streams that are only opened when they are actually
2298 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002299 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002300 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2301 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002302 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002303
Eric Laurent3a4311c2014-03-17 12:00:47 -07002304 if (outProfile->mSupportedDevices.isEmpty()) {
2305 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2306 continue;
2307 }
2308
Eric Laurent83b88082014-06-20 18:31:16 -07002309 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2310 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2311 profileType = mDefaultOutputDevice->mDeviceType;
2312 } else {
2313 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2314 }
2315 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002316 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002317 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002318
Eric Laurent83b88082014-06-20 18:31:16 -07002319 outputDesc->mDevice = profileType;
Eric Laurente552edb2014-03-10 17:42:56 -07002320 audio_io_handle_t output = mpClientInterface->openOutput(
2321 outProfile->mModule->mHandle,
2322 &outputDesc->mDevice,
2323 &outputDesc->mSamplingRate,
2324 &outputDesc->mFormat,
2325 &outputDesc->mChannelMask,
2326 &outputDesc->mLatency,
2327 outputDesc->mFlags);
2328 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002329 ALOGW("Cannot open output stream for device %08x on hw module %s",
2330 outputDesc->mDevice,
2331 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002332 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002333 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002334 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002335 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002336 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002337 // give a valid ID to an attached device once confirmed it is reachable
2338 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2339 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002340 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002341 }
2342 }
Eric Laurente552edb2014-03-10 17:42:56 -07002343 if (mPrimaryOutput == 0 &&
2344 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2345 mPrimaryOutput = output;
2346 }
2347 addOutput(output, outputDesc);
2348 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002349 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002350 true);
2351 }
2352 }
2353 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002354 // open input streams needed to access attached devices to validate
2355 // mAvailableInputDevices list
2356 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2357 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002358 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002359
Eric Laurent3a4311c2014-03-17 12:00:47 -07002360 if (inProfile->mSupportedDevices.isEmpty()) {
2361 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2362 continue;
2363 }
2364
Eric Laurent83b88082014-06-20 18:31:16 -07002365 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2366 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002367 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002368
2369 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002370 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002371 audio_io_handle_t input = mpClientInterface->openInput(
2372 inProfile->mModule->mHandle,
2373 &inputDesc->mDevice,
2374 &inputDesc->mSamplingRate,
2375 &inputDesc->mFormat,
Glenn Kastenec40d282014-07-15 15:31:26 -07002376 &inputDesc->mChannelMask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002377 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002378
2379 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002380 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002381 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002382 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002383 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002384 // give a valid ID to an attached device once confirmed it is reachable
2385 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2386 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002387 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002388 }
2389 }
2390 mpClientInterface->closeInput(input);
2391 } else {
2392 ALOGW("Cannot open input stream for device %08x on hw module %s",
2393 inputDesc->mDevice,
2394 mHwModules[i]->mName);
2395 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002396 }
2397 }
2398 }
2399 // make sure all attached devices have been allocated a unique ID
2400 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2401 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002402 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002403 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2404 continue;
2405 }
2406 i++;
2407 }
2408 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2409 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002410 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002411 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2412 continue;
2413 }
2414 i++;
2415 }
2416 // make sure default device is reachable
2417 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002418 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002419 }
Eric Laurente552edb2014-03-10 17:42:56 -07002420
2421 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2422
2423 updateDevicesAndOutputs();
2424
2425#ifdef AUDIO_POLICY_TEST
2426 if (mPrimaryOutput != 0) {
2427 AudioParameter outputCmd = AudioParameter();
2428 outputCmd.addInt(String8("set_id"), 0);
2429 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2430
2431 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2432 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002433 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2434 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002435 mTestLatencyMs = 0;
2436 mCurOutput = 0;
2437 mDirectOutput = false;
2438 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2439 mTestOutputs[i] = 0;
2440 }
2441
2442 const size_t SIZE = 256;
2443 char buffer[SIZE];
2444 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2445 run(buffer, ANDROID_PRIORITY_AUDIO);
2446 }
2447#endif //AUDIO_POLICY_TEST
2448}
2449
Eric Laurente0720872014-03-11 09:30:41 -07002450AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002451{
2452#ifdef AUDIO_POLICY_TEST
2453 exit();
2454#endif //AUDIO_POLICY_TEST
2455 for (size_t i = 0; i < mOutputs.size(); i++) {
2456 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002457 }
2458 for (size_t i = 0; i < mInputs.size(); i++) {
2459 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002460 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002461 mAvailableOutputDevices.clear();
2462 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002463 mOutputs.clear();
2464 mInputs.clear();
2465 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002466}
2467
Eric Laurente0720872014-03-11 09:30:41 -07002468status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002469{
2470 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2471}
2472
2473#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002474bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002475{
2476 ALOGV("entering threadLoop()");
2477 while (!exitPending())
2478 {
2479 String8 command;
2480 int valueInt;
2481 String8 value;
2482
2483 Mutex::Autolock _l(mLock);
2484 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2485
2486 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2487 AudioParameter param = AudioParameter(command);
2488
2489 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2490 valueInt != 0) {
2491 ALOGV("Test command %s received", command.string());
2492 String8 target;
2493 if (param.get(String8("target"), target) != NO_ERROR) {
2494 target = "Manager";
2495 }
2496 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2497 param.remove(String8("test_cmd_policy_output"));
2498 mCurOutput = valueInt;
2499 }
2500 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2501 param.remove(String8("test_cmd_policy_direct"));
2502 if (value == "false") {
2503 mDirectOutput = false;
2504 } else if (value == "true") {
2505 mDirectOutput = true;
2506 }
2507 }
2508 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2509 param.remove(String8("test_cmd_policy_input"));
2510 mTestInput = valueInt;
2511 }
2512
2513 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2514 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002515 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002516 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002517 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002518 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002519 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002520 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002521 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002522 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002523 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002524 if (target == "Manager") {
2525 mTestFormat = format;
2526 } else if (mTestOutputs[mCurOutput] != 0) {
2527 AudioParameter outputParam = AudioParameter();
2528 outputParam.addInt(String8("format"), format);
2529 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2530 }
2531 }
2532 }
2533 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2534 param.remove(String8("test_cmd_policy_channels"));
2535 int channels = 0;
2536
2537 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002538 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002539 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002540 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002541 }
2542 if (channels != 0) {
2543 if (target == "Manager") {
2544 mTestChannels = channels;
2545 } else if (mTestOutputs[mCurOutput] != 0) {
2546 AudioParameter outputParam = AudioParameter();
2547 outputParam.addInt(String8("channels"), channels);
2548 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2549 }
2550 }
2551 }
2552 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2553 param.remove(String8("test_cmd_policy_sampleRate"));
2554 if (valueInt >= 0 && valueInt <= 96000) {
2555 int samplingRate = valueInt;
2556 if (target == "Manager") {
2557 mTestSamplingRate = samplingRate;
2558 } else if (mTestOutputs[mCurOutput] != 0) {
2559 AudioParameter outputParam = AudioParameter();
2560 outputParam.addInt(String8("sampling_rate"), samplingRate);
2561 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2562 }
2563 }
2564 }
2565
2566 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2567 param.remove(String8("test_cmd_policy_reopen"));
2568
Eric Laurent1f2f2232014-06-02 12:01:23 -07002569 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002570 mpClientInterface->closeOutput(mPrimaryOutput);
2571
2572 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2573
Eric Laurente552edb2014-03-10 17:42:56 -07002574 mOutputs.removeItem(mPrimaryOutput);
2575
Eric Laurent1f2f2232014-06-02 12:01:23 -07002576 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002577 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2578 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2579 &outputDesc->mDevice,
2580 &outputDesc->mSamplingRate,
2581 &outputDesc->mFormat,
2582 &outputDesc->mChannelMask,
2583 &outputDesc->mLatency,
2584 outputDesc->mFlags);
2585 if (mPrimaryOutput == 0) {
2586 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2587 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2588 } else {
2589 AudioParameter outputCmd = AudioParameter();
2590 outputCmd.addInt(String8("set_id"), 0);
2591 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2592 addOutput(mPrimaryOutput, outputDesc);
2593 }
2594 }
2595
2596
2597 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2598 }
2599 }
2600 return false;
2601}
2602
Eric Laurente0720872014-03-11 09:30:41 -07002603void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002604{
2605 {
2606 AutoMutex _l(mLock);
2607 requestExit();
2608 mWaitWorkCV.signal();
2609 }
2610 requestExitAndWait();
2611}
2612
Eric Laurente0720872014-03-11 09:30:41 -07002613int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002614{
2615 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2616 if (output == mTestOutputs[i]) return i;
2617 }
2618 return 0;
2619}
2620#endif //AUDIO_POLICY_TEST
2621
2622// ---
2623
Eric Laurent1f2f2232014-06-02 12:01:23 -07002624void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002625{
Eric Laurent1c333e22014-05-20 10:48:17 -07002626 outputDesc->mIoHandle = output;
2627 outputDesc->mId = nextUniqueId();
2628 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002629 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002630}
2631
Eric Laurent1f2f2232014-06-02 12:01:23 -07002632void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002633{
Eric Laurent1c333e22014-05-20 10:48:17 -07002634 inputDesc->mIoHandle = input;
2635 inputDesc->mId = nextUniqueId();
2636 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002637 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002638}
Eric Laurente552edb2014-03-10 17:42:56 -07002639
Eric Laurent3a4311c2014-03-17 12:00:47 -07002640String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2641{
2642 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2643 return String8("a2dp_sink_address=")+address;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002644 } else if (device & AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2645 return String8("mix=")+address;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002646 }
2647 return address;
2648}
2649
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002650void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2651 const String8 address /*in*/,
2652 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2653 // look for a match on the given address on the addresses of the outputs:
2654 // find the address by finding the patch that maps to this output
2655 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2656 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2657 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2658 if (patchIdx >= 0) {
2659 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2660 const int numSinks = patchDesc->mPatch.num_sinks;
2661 for (ssize_t j=0; j < numSinks; j++) {
2662 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2663 const char* patchAddr =
2664 patchDesc->mPatch.sinks[j].ext.device.address;
2665 if (strncmp(patchAddr,
2666 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2667 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2668 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2669 outputs.add(desc->mIoHandle);
2670 break;
2671 }
2672 }
2673 }
2674 }
2675}
2676
Eric Laurente0720872014-03-11 09:30:41 -07002677status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002678 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002679 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002680 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002681{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002682 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002683
Eric Laurent3b73df72014-03-11 09:06:29 -07002684 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002685 // first list already open outputs that can be routed to this device
2686 for (size_t i = 0; i < mOutputs.size(); i++) {
2687 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002688 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002689 if (!deviceDistinguishesOnAddress(device)) {
2690 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2691 outputs.add(mOutputs.keyAt(i));
2692 } else {
2693 ALOGV(" checking address match due to device 0x%x", device);
2694 findIoHandlesByAddress(desc, address, outputs);
2695 }
Eric Laurente552edb2014-03-10 17:42:56 -07002696 }
2697 }
2698 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002699 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002700 for (size_t i = 0; i < mHwModules.size(); i++)
2701 {
2702 if (mHwModules[i]->mHandle == 0) {
2703 continue;
2704 }
2705 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2706 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002707 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002708 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002709 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2710 }
2711 }
2712 }
2713
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002714 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2715
Eric Laurente552edb2014-03-10 17:42:56 -07002716 if (profiles.isEmpty() && outputs.isEmpty()) {
2717 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2718 return BAD_VALUE;
2719 }
2720
2721 // open outputs for matching profiles if needed. Direct outputs are also opened to
2722 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2723 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002724 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002725
2726 // nothing to do if one output is already opened for this profile
2727 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002728 for (j = 0; j < outputs.size(); j++) {
2729 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002730 if (!desc->isDuplicated() && desc->mProfile == profile) {
2731 break;
2732 }
2733 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002734 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002735 continue;
2736 }
2737
Eric Laurent83b88082014-06-20 18:31:16 -07002738 ALOGV("opening output for device %08x with params %s profile %p",
2739 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002740 desc = new AudioOutputDescriptor(profile);
2741 desc->mDevice = device;
2742 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2743 offloadInfo.sample_rate = desc->mSamplingRate;
2744 offloadInfo.format = desc->mFormat;
2745 offloadInfo.channel_mask = desc->mChannelMask;
2746
2747 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2748 &desc->mDevice,
2749 &desc->mSamplingRate,
2750 &desc->mFormat,
2751 &desc->mChannelMask,
2752 &desc->mLatency,
2753 desc->mFlags,
2754 &offloadInfo);
2755 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002756 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002757 if (!address.isEmpty()) {
2758 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002759 }
2760
Eric Laurentd4692962014-05-05 18:13:44 -07002761 // Here is where we step through and resolve any "dynamic" fields
2762 String8 reply;
2763 char *value;
2764 if (profile->mSamplingRates[0] == 0) {
2765 reply = mpClientInterface->getParameters(output,
2766 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002767 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002768 reply.string());
2769 value = strpbrk((char *)reply.string(), "=");
2770 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002771 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002772 }
Eric Laurentd4692962014-05-05 18:13:44 -07002773 }
2774 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2775 reply = mpClientInterface->getParameters(output,
2776 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002777 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002778 reply.string());
2779 value = strpbrk((char *)reply.string(), "=");
2780 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002781 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002782 }
Eric Laurentd4692962014-05-05 18:13:44 -07002783 }
2784 if (profile->mChannelMasks[0] == 0) {
2785 reply = mpClientInterface->getParameters(output,
2786 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002787 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002788 reply.string());
2789 value = strpbrk((char *)reply.string(), "=");
2790 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002791 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002792 }
Eric Laurentd4692962014-05-05 18:13:44 -07002793 }
2794 if (((profile->mSamplingRates[0] == 0) &&
2795 (profile->mSamplingRates.size() < 2)) ||
2796 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2797 (profile->mFormats.size() < 2)) ||
2798 ((profile->mChannelMasks[0] == 0) &&
2799 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002800 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002801 mpClientInterface->closeOutput(output);
2802 output = 0;
Eric Laurent1e693b52014-07-09 15:03:28 -07002803 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2804 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002805 mpClientInterface->closeOutput(output);
Eric Laurent1e693b52014-07-09 15:03:28 -07002806 desc->mSamplingRate = profile->pickSamplingRate();
2807 desc->mFormat = profile->pickFormat();
2808 desc->mChannelMask = profile->pickChannelMask();
Eric Laurentd4692962014-05-05 18:13:44 -07002809 offloadInfo.sample_rate = desc->mSamplingRate;
Eric Laurent1e693b52014-07-09 15:03:28 -07002810 offloadInfo.format = desc->mFormat;
2811 offloadInfo.channel_mask = desc->mChannelMask;
Eric Laurentd4692962014-05-05 18:13:44 -07002812 output = mpClientInterface->openOutput(
2813 profile->mModule->mHandle,
2814 &desc->mDevice,
2815 &desc->mSamplingRate,
2816 &desc->mFormat,
2817 &desc->mChannelMask,
2818 &desc->mLatency,
2819 desc->mFlags,
2820 &offloadInfo);
2821 }
2822
2823 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002824 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002825 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2826 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002827
Eric Laurentd4692962014-05-05 18:13:44 -07002828 // set initial stream volume for device
2829 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002830
Eric Laurentd4692962014-05-05 18:13:44 -07002831 //TODO: configure audio effect output stage here
2832
2833 // open a duplicating output thread for the new output and the primary output
2834 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2835 mPrimaryOutput);
2836 if (duplicatedOutput != 0) {
2837 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002838 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002839 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2840 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2841 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2842 dupOutputDesc->mFormat = desc->mFormat;
2843 dupOutputDesc->mChannelMask = desc->mChannelMask;
2844 dupOutputDesc->mLatency = desc->mLatency;
2845 addOutput(duplicatedOutput, dupOutputDesc);
2846 applyStreamVolumes(duplicatedOutput, device, 0, true);
2847 } else {
2848 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2849 mPrimaryOutput, output);
2850 mpClientInterface->closeOutput(output);
2851 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002852 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002853 output = 0;
2854 }
Eric Laurente552edb2014-03-10 17:42:56 -07002855 }
2856 }
2857 }
2858 if (output == 0) {
2859 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002860 profiles.removeAt(profile_index);
2861 profile_index--;
2862 } else {
2863 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002864 if (deviceDistinguishesOnAddress(device)) {
2865 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2866 device, address.string());
2867 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2868 NULL/*patch handle*/, address.string());
2869 }
Eric Laurente552edb2014-03-10 17:42:56 -07002870 ALOGV("checkOutputsForDevice(): adding output %d", output);
2871 }
2872 }
2873
2874 if (profiles.isEmpty()) {
2875 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2876 return BAD_VALUE;
2877 }
Eric Laurentd4692962014-05-05 18:13:44 -07002878 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002879 // check if one opened output is not needed any more after disconnecting one device
2880 for (size_t i = 0; i < mOutputs.size(); i++) {
2881 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002882 if (!desc->isDuplicated()) {
2883 if (!(desc->mProfile->mSupportedDevices.types()
2884 & mAvailableOutputDevices.types())) {
2885 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
2886 mOutputs.keyAt(i));
2887 outputs.add(mOutputs.keyAt(i));
2888 } else if (deviceDistinguishesOnAddress(device) &&
2889 // exact match on device
2890 (desc->mProfile->mSupportedDevices.types() == device)) {
2891 findIoHandlesByAddress(desc, address, outputs);
2892 }
Eric Laurente552edb2014-03-10 17:42:56 -07002893 }
2894 }
Eric Laurentd4692962014-05-05 18:13:44 -07002895 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002896 for (size_t i = 0; i < mHwModules.size(); i++)
2897 {
2898 if (mHwModules[i]->mHandle == 0) {
2899 continue;
2900 }
2901 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2902 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002903 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002904 if (profile->mSupportedDevices.types() & device) {
2905 ALOGV("checkOutputsForDevice(): "
2906 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002907 if (profile->mSamplingRates[0] == 0) {
2908 profile->mSamplingRates.clear();
2909 profile->mSamplingRates.add(0);
2910 }
2911 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2912 profile->mFormats.clear();
2913 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2914 }
2915 if (profile->mChannelMasks[0] == 0) {
2916 profile->mChannelMasks.clear();
2917 profile->mChannelMasks.add(0);
2918 }
2919 }
2920 }
2921 }
2922 }
2923 return NO_ERROR;
2924}
2925
Eric Laurentd4692962014-05-05 18:13:44 -07002926status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2927 audio_policy_dev_state_t state,
2928 SortedVector<audio_io_handle_t>& inputs,
2929 const String8 address)
2930{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002931 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002932 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2933 // first list already open inputs that can be routed to this device
2934 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2935 desc = mInputs.valueAt(input_index);
2936 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2937 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2938 inputs.add(mInputs.keyAt(input_index));
2939 }
2940 }
2941
2942 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002943 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002944 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2945 {
2946 if (mHwModules[module_idx]->mHandle == 0) {
2947 continue;
2948 }
2949 for (size_t profile_index = 0;
2950 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2951 profile_index++)
2952 {
2953 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2954 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002955 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002956 profile_index, module_idx);
2957 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2958 }
2959 }
2960 }
2961
2962 if (profiles.isEmpty() && inputs.isEmpty()) {
2963 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2964 return BAD_VALUE;
2965 }
2966
2967 // open inputs for matching profiles if needed. Direct inputs are also opened to
2968 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2969 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2970
Eric Laurent1c333e22014-05-20 10:48:17 -07002971 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002972 // nothing to do if one input is already opened for this profile
2973 size_t input_index;
2974 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2975 desc = mInputs.valueAt(input_index);
2976 if (desc->mProfile == profile) {
2977 break;
2978 }
2979 }
2980 if (input_index != mInputs.size()) {
2981 continue;
2982 }
2983
2984 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2985 desc = new AudioInputDescriptor(profile);
2986 desc->mDevice = device;
2987
2988 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2989 &desc->mDevice,
2990 &desc->mSamplingRate,
2991 &desc->mFormat,
Glenn Kastenec40d282014-07-15 15:31:26 -07002992 &desc->mChannelMask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002993 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07002994
2995 if (input != 0) {
2996 if (!address.isEmpty()) {
2997 mpClientInterface->setParameters(input, addressToParameter(device, address));
2998 }
2999
3000 // Here is where we step through and resolve any "dynamic" fields
3001 String8 reply;
3002 char *value;
3003 if (profile->mSamplingRates[0] == 0) {
3004 reply = mpClientInterface->getParameters(input,
3005 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3006 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3007 reply.string());
3008 value = strpbrk((char *)reply.string(), "=");
3009 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003010 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003011 }
3012 }
3013 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3014 reply = mpClientInterface->getParameters(input,
3015 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3016 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3017 value = strpbrk((char *)reply.string(), "=");
3018 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003019 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003020 }
3021 }
3022 if (profile->mChannelMasks[0] == 0) {
3023 reply = mpClientInterface->getParameters(input,
3024 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3025 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3026 reply.string());
3027 value = strpbrk((char *)reply.string(), "=");
3028 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003029 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003030 }
3031 }
3032 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3033 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3034 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3035 ALOGW("checkInputsForDevice() direct input missing param");
3036 mpClientInterface->closeInput(input);
3037 input = 0;
3038 }
3039
3040 if (input != 0) {
3041 addInput(input, desc);
3042 }
3043 } // endif input != 0
3044
3045 if (input == 0) {
3046 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003047 profiles.removeAt(profile_index);
3048 profile_index--;
3049 } else {
3050 inputs.add(input);
3051 ALOGV("checkInputsForDevice(): adding input %d", input);
3052 }
3053 } // end scan profiles
3054
3055 if (profiles.isEmpty()) {
3056 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3057 return BAD_VALUE;
3058 }
3059 } else {
3060 // Disconnect
3061 // check if one opened input is not needed any more after disconnecting one device
3062 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3063 desc = mInputs.valueAt(input_index);
3064 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3065 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3066 mInputs.keyAt(input_index));
3067 inputs.add(mInputs.keyAt(input_index));
3068 }
3069 }
3070 // Clear any profiles associated with the disconnected device.
3071 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3072 if (mHwModules[module_index]->mHandle == 0) {
3073 continue;
3074 }
3075 for (size_t profile_index = 0;
3076 profile_index < mHwModules[module_index]->mInputProfiles.size();
3077 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003078 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003079 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003080 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003081 profile_index, module_index);
3082 if (profile->mSamplingRates[0] == 0) {
3083 profile->mSamplingRates.clear();
3084 profile->mSamplingRates.add(0);
3085 }
3086 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3087 profile->mFormats.clear();
3088 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3089 }
3090 if (profile->mChannelMasks[0] == 0) {
3091 profile->mChannelMasks.clear();
3092 profile->mChannelMasks.add(0);
3093 }
3094 }
3095 }
3096 }
3097 } // end disconnect
3098
3099 return NO_ERROR;
3100}
3101
3102
Eric Laurente0720872014-03-11 09:30:41 -07003103void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003104{
3105 ALOGV("closeOutput(%d)", output);
3106
Eric Laurent1f2f2232014-06-02 12:01:23 -07003107 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003108 if (outputDesc == NULL) {
3109 ALOGW("closeOutput() unknown output %d", output);
3110 return;
3111 }
3112
3113 // look for duplicated outputs connected to the output being removed.
3114 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003115 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003116 if (dupOutputDesc->isDuplicated() &&
3117 (dupOutputDesc->mOutput1 == outputDesc ||
3118 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003119 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003120 if (dupOutputDesc->mOutput1 == outputDesc) {
3121 outputDesc2 = dupOutputDesc->mOutput2;
3122 } else {
3123 outputDesc2 = dupOutputDesc->mOutput1;
3124 }
3125 // As all active tracks on duplicated output will be deleted,
3126 // and as they were also referenced on the other output, the reference
3127 // count for their stream type must be adjusted accordingly on
3128 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003129 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003130 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003131 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003132 }
3133 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3134 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3135
3136 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003137 mOutputs.removeItem(duplicatedOutput);
3138 }
3139 }
3140
3141 AudioParameter param;
3142 param.add(String8("closing"), String8("true"));
3143 mpClientInterface->setParameters(output, param.toString());
3144
3145 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003146 mOutputs.removeItem(output);
3147 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003148 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003149}
3150
Eric Laurente0720872014-03-11 09:30:41 -07003151SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003152 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003153{
3154 SortedVector<audio_io_handle_t> outputs;
3155
3156 ALOGVV("getOutputsForDevice() device %04x", device);
3157 for (size_t i = 0; i < openOutputs.size(); i++) {
3158 ALOGVV("output %d isDuplicated=%d device=%04x",
3159 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3160 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3161 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3162 outputs.add(openOutputs.keyAt(i));
3163 }
3164 }
3165 return outputs;
3166}
3167
Eric Laurente0720872014-03-11 09:30:41 -07003168bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003169 SortedVector<audio_io_handle_t>& outputs2)
3170{
3171 if (outputs1.size() != outputs2.size()) {
3172 return false;
3173 }
3174 for (size_t i = 0; i < outputs1.size(); i++) {
3175 if (outputs1[i] != outputs2[i]) {
3176 return false;
3177 }
3178 }
3179 return true;
3180}
3181
Eric Laurente0720872014-03-11 09:30:41 -07003182void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003183{
3184 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3185 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3186 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3187 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3188
3189 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3190 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3191 strategy, srcOutputs[0], dstOutputs[0]);
3192 // mute strategy while moving tracks from one output to another
3193 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003194 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003195 if (desc->isStrategyActive(strategy)) {
3196 setStrategyMute(strategy, true, srcOutputs[i]);
3197 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3198 }
3199 }
3200
3201 // Move effects associated to this strategy from previous output to new output
3202 if (strategy == STRATEGY_MEDIA) {
3203 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3204 SortedVector<audio_io_handle_t> moved;
3205 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003206 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3207 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3208 effectDesc->mIo != fxOutput) {
3209 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003210 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3211 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003212 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003213 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003214 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003215 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003216 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003217 }
3218 }
3219 }
3220 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003221 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3222 if (getStrategy((audio_stream_type_t)i) == strategy) {
3223 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003224 }
3225 }
3226 }
3227}
3228
Eric Laurente0720872014-03-11 09:30:41 -07003229void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003230{
3231 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3232 checkOutputForStrategy(STRATEGY_PHONE);
3233 checkOutputForStrategy(STRATEGY_SONIFICATION);
3234 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3235 checkOutputForStrategy(STRATEGY_MEDIA);
3236 checkOutputForStrategy(STRATEGY_DTMF);
3237}
3238
Eric Laurente0720872014-03-11 09:30:41 -07003239audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003240{
Eric Laurente552edb2014-03-10 17:42:56 -07003241 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003242 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003243 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3244 return mOutputs.keyAt(i);
3245 }
3246 }
3247
3248 return 0;
3249}
3250
Eric Laurente0720872014-03-11 09:30:41 -07003251void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003252{
Eric Laurente552edb2014-03-10 17:42:56 -07003253 audio_io_handle_t a2dpOutput = getA2dpOutput();
3254 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003255 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003256 return;
3257 }
3258
Eric Laurent3a4311c2014-03-17 12:00:47 -07003259 bool isScoConnected =
3260 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003261 // suspend A2DP output if:
3262 // (NOT already suspended) &&
3263 // ((SCO device is connected &&
3264 // (forced usage for communication || for record is SCO))) ||
3265 // (phone state is ringing || in call)
3266 //
3267 // restore A2DP output if:
3268 // (Already suspended) &&
3269 // ((SCO device is NOT connected ||
3270 // (forced usage NOT for communication && NOT for record is SCO))) &&
3271 // (phone state is NOT ringing && NOT in call)
3272 //
3273 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003274 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003275 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3276 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3277 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3278 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003279
3280 mpClientInterface->restoreOutput(a2dpOutput);
3281 mA2dpSuspended = false;
3282 }
3283 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003284 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003285 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3286 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3287 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3288 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003289
3290 mpClientInterface->suspendOutput(a2dpOutput);
3291 mA2dpSuspended = true;
3292 }
3293 }
3294}
3295
Eric Laurent1c333e22014-05-20 10:48:17 -07003296audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003297{
3298 audio_devices_t device = AUDIO_DEVICE_NONE;
3299
Eric Laurent1f2f2232014-06-02 12:01:23 -07003300 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003301
3302 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3303 if (index >= 0) {
3304 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3305 if (patchDesc->mUid != mUidCached) {
3306 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3307 outputDesc->device(), outputDesc->mPatchHandle);
3308 return outputDesc->device();
3309 }
3310 }
3311
Eric Laurente552edb2014-03-10 17:42:56 -07003312 // check the following by order of priority to request a routing change if necessary:
3313 // 1: the strategy enforced audible is active on the output:
3314 // use device for strategy enforced audible
3315 // 2: we are in call or the strategy phone is active on the output:
3316 // use device for strategy phone
3317 // 3: the strategy sonification is active on the output:
3318 // use device for strategy sonification
3319 // 4: the strategy "respectful" sonification is active on the output:
3320 // use device for strategy "respectful" sonification
3321 // 5: the strategy media is active on the output:
3322 // use device for strategy media
3323 // 6: the strategy DTMF is active on the output:
3324 // use device for strategy DTMF
3325 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3326 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3327 } else if (isInCall() ||
3328 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3329 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3330 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3331 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3332 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3333 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3334 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3335 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3336 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3337 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3338 }
3339
Eric Laurent1c333e22014-05-20 10:48:17 -07003340 ALOGV("getNewOutputDevice() selected device %x", device);
3341 return device;
3342}
3343
3344audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3345{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003346 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003347
3348 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3349 if (index >= 0) {
3350 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3351 if (patchDesc->mUid != mUidCached) {
3352 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3353 inputDesc->mDevice, inputDesc->mPatchHandle);
3354 return inputDesc->mDevice;
3355 }
3356 }
3357
Eric Laurent1c333e22014-05-20 10:48:17 -07003358 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3359
3360 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003361 return device;
3362}
3363
Eric Laurente0720872014-03-11 09:30:41 -07003364uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003365 return (uint32_t)getStrategy(stream);
3366}
3367
Eric Laurente0720872014-03-11 09:30:41 -07003368audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003369 // By checking the range of stream before calling getStrategy, we avoid
3370 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3371 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003372 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003373 return AUDIO_DEVICE_NONE;
3374 }
3375 audio_devices_t devices;
3376 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3377 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3378 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3379 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003380 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003381 if (outputDesc->isStrategyActive(strategy)) {
3382 devices = outputDesc->device();
3383 break;
3384 }
Eric Laurente552edb2014-03-10 17:42:56 -07003385 }
3386 return devices;
3387}
3388
Eric Laurente0720872014-03-11 09:30:41 -07003389AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003390 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003391 // stream to strategy mapping
3392 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003393 case AUDIO_STREAM_VOICE_CALL:
3394 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003395 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003396 case AUDIO_STREAM_RING:
3397 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003398 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003399 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003400 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003401 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003402 return STRATEGY_DTMF;
3403 default:
3404 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003405 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003406 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3407 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003408 case AUDIO_STREAM_TTS:
3409 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003410 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003411 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003412 return STRATEGY_ENFORCED_AUDIBLE;
3413 }
3414}
3415
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003416uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3417 // flags to strategy mapping
3418 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3419 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3420 }
3421
3422 // usage to strategy mapping
3423 switch (attr->usage) {
3424 case AUDIO_USAGE_MEDIA:
3425 case AUDIO_USAGE_GAME:
3426 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3427 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3428 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3429 return (uint32_t) STRATEGY_MEDIA;
3430
3431 case AUDIO_USAGE_VOICE_COMMUNICATION:
3432 return (uint32_t) STRATEGY_PHONE;
3433
3434 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3435 return (uint32_t) STRATEGY_DTMF;
3436
3437 case AUDIO_USAGE_ALARM:
3438 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3439 return (uint32_t) STRATEGY_SONIFICATION;
3440
3441 case AUDIO_USAGE_NOTIFICATION:
3442 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3443 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3444 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3445 case AUDIO_USAGE_NOTIFICATION_EVENT:
3446 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3447
3448 case AUDIO_USAGE_UNKNOWN:
3449 default:
3450 return (uint32_t) STRATEGY_MEDIA;
3451 }
3452}
3453
Eric Laurente0720872014-03-11 09:30:41 -07003454void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003455 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003456 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003457 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3458 updateDevicesAndOutputs();
3459 break;
3460 default:
3461 break;
3462 }
3463}
3464
Eric Laurente0720872014-03-11 09:30:41 -07003465audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003466 bool fromCache)
3467{
3468 uint32_t device = AUDIO_DEVICE_NONE;
3469
3470 if (fromCache) {
3471 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3472 strategy, mDeviceForStrategy[strategy]);
3473 return mDeviceForStrategy[strategy];
3474 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003475 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003476 switch (strategy) {
3477
3478 case STRATEGY_SONIFICATION_RESPECTFUL:
3479 if (isInCall()) {
3480 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003481 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003482 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3483 // while media is playing on a remote device, use the the sonification behavior.
3484 // Note that we test this usecase before testing if media is playing because
3485 // the isStreamActive() method only informs about the activity of a stream, not
3486 // if it's for local playback. Note also that we use the same delay between both tests
3487 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003488 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003489 // while media is playing (or has recently played), use the same device
3490 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3491 } else {
3492 // when media is not playing anymore, fall back on the sonification behavior
3493 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3494 }
3495
3496 break;
3497
3498 case STRATEGY_DTMF:
3499 if (!isInCall()) {
3500 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3501 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3502 break;
3503 }
3504 // when in call, DTMF and PHONE strategies follow the same rules
3505 // FALL THROUGH
3506
3507 case STRATEGY_PHONE:
3508 // for phone strategy, we first consider the forced use and then the available devices by order
3509 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003510 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3511 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003512 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003513 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003514 if (device) break;
3515 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003516 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003517 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003518 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003519 if (device) break;
3520 // if SCO device is requested but no SCO device is available, fall back to default case
3521 // FALL THROUGH
3522
3523 default: // FORCE_NONE
3524 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003525 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003526 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003527 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003528 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003529 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003530 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003531 if (device) break;
3532 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003533 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003534 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003535 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003536 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003537 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003538 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003539 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003540 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003541 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003542 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003543 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003544 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003545 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003546 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003547 if (device) break;
3548 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003549 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003550 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003551 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003552 if (device == AUDIO_DEVICE_NONE) {
3553 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3554 }
3555 break;
3556
Eric Laurent3b73df72014-03-11 09:06:29 -07003557 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003558 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3559 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003560 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003561 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003562 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003563 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003564 if (device) break;
3565 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003566 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003567 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003568 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003569 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003570 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003571 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003572 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003573 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003574 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003575 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003576 if (device) break;
3577 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003578 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003579 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003580 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003581 if (device == AUDIO_DEVICE_NONE) {
3582 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3583 }
3584 break;
3585 }
3586 break;
3587
3588 case STRATEGY_SONIFICATION:
3589
3590 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3591 // handleIncallSonification().
3592 if (isInCall()) {
3593 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3594 break;
3595 }
3596 // FALL THROUGH
3597
3598 case STRATEGY_ENFORCED_AUDIBLE:
3599 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3600 // except:
3601 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3602 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3603
3604 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003605 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003606 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003607 if (device == AUDIO_DEVICE_NONE) {
3608 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3609 }
3610 }
3611 // The second device used for sonification is the same as the device used by media strategy
3612 // FALL THROUGH
3613
3614 case STRATEGY_MEDIA: {
3615 uint32_t device2 = AUDIO_DEVICE_NONE;
3616 if (strategy != STRATEGY_SONIFICATION) {
3617 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003618 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003619 }
3620 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003621 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003622 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003623 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003624 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003625 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003626 }
3627 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003628 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003629 }
3630 }
3631 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003632 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003633 }
3634 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003635 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003636 }
3637 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003638 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003639 }
3640 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003641 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003642 }
3643 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003644 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003645 }
3646 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3647 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003648 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003649 }
3650 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003651 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003652 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003653 }
3654 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003655 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003656 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003657 int device3 = AUDIO_DEVICE_NONE;
3658 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003659 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003660 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3661 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003662 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003663 }
Eric Laurente552edb2014-03-10 17:42:56 -07003664
Jungshik Jang839e4f32014-06-26 17:23:40 +09003665 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003666 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3667 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3668 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003669
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003670 // If hdmi system audio mode is on, remove speaker out of output list.
3671 if ((strategy == STRATEGY_MEDIA) &&
3672 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3673 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3674 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3675 }
3676
Eric Laurente552edb2014-03-10 17:42:56 -07003677 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003678 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003679 if (device == AUDIO_DEVICE_NONE) {
3680 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3681 }
3682 } break;
3683
3684 default:
3685 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3686 break;
3687 }
3688
3689 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3690 return device;
3691}
3692
Eric Laurente0720872014-03-11 09:30:41 -07003693void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003694{
3695 for (int i = 0; i < NUM_STRATEGIES; i++) {
3696 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3697 }
3698 mPreviousOutputs = mOutputs;
3699}
3700
Eric Laurent1f2f2232014-06-02 12:01:23 -07003701uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003702 audio_devices_t prevDevice,
3703 uint32_t delayMs)
3704{
3705 // mute/unmute strategies using an incompatible device combination
3706 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3707 // if unmuting, unmute only after the specified delay
3708 if (outputDesc->isDuplicated()) {
3709 return 0;
3710 }
3711
3712 uint32_t muteWaitMs = 0;
3713 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003714 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003715
3716 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3717 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3718 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3719 bool doMute = false;
3720
3721 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3722 doMute = true;
3723 outputDesc->mStrategyMutedByDevice[i] = true;
3724 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3725 doMute = true;
3726 outputDesc->mStrategyMutedByDevice[i] = false;
3727 }
Eric Laurent99401132014-05-07 19:48:15 -07003728 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003729 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003730 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003731 // skip output if it does not share any device with current output
3732 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3733 == AUDIO_DEVICE_NONE) {
3734 continue;
3735 }
3736 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3737 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3738 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3739 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3740 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003741 if (mute) {
3742 // FIXME: should not need to double latency if volume could be applied
3743 // immediately by the audioflinger mixer. We must account for the delay
3744 // between now and the next time the audioflinger thread for this output
3745 // will process a buffer (which corresponds to one buffer size,
3746 // usually 1/2 or 1/4 of the latency).
3747 if (muteWaitMs < desc->latency() * 2) {
3748 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003749 }
3750 }
3751 }
3752 }
3753 }
3754 }
3755
Eric Laurent99401132014-05-07 19:48:15 -07003756 // temporary mute output if device selection changes to avoid volume bursts due to
3757 // different per device volumes
3758 if (outputDesc->isActive() && (device != prevDevice)) {
3759 if (muteWaitMs < outputDesc->latency() * 2) {
3760 muteWaitMs = outputDesc->latency() * 2;
3761 }
3762 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3763 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003765 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003766 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003767 muteWaitMs *2, device);
3768 }
3769 }
3770 }
3771
Eric Laurente552edb2014-03-10 17:42:56 -07003772 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3773 if (muteWaitMs > delayMs) {
3774 muteWaitMs -= delayMs;
3775 usleep(muteWaitMs * 1000);
3776 return muteWaitMs;
3777 }
3778 return 0;
3779}
3780
Eric Laurente0720872014-03-11 09:30:41 -07003781uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003782 audio_devices_t device,
3783 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003784 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003785 audio_patch_handle_t *patchHandle,
3786 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003787{
3788 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003789 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003790 AudioParameter param;
3791 uint32_t muteWaitMs;
3792
3793 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003794 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3795 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003796 return muteWaitMs;
3797 }
3798 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3799 // output profile
3800 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003801 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003802 return 0;
3803 }
3804
3805 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003806 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003807
3808 audio_devices_t prevDevice = outputDesc->mDevice;
3809
3810 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3811
3812 if (device != AUDIO_DEVICE_NONE) {
3813 outputDesc->mDevice = device;
3814 }
3815 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3816
3817 // Do not change the routing if:
3818 // - the requested device is AUDIO_DEVICE_NONE
3819 // - the requested device is the same as current device and force is not specified.
3820 // Doing this check here allows the caller to call setOutputDevice() without conditions
3821 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3822 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3823 return muteWaitMs;
3824 }
3825
3826 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003827
Eric Laurente552edb2014-03-10 17:42:56 -07003828 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003829 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003830 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003831 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003832 DeviceVector deviceList = (address == NULL) ?
3833 mAvailableOutputDevices.getDevicesFromType(device)
3834 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003835 if (!deviceList.isEmpty()) {
3836 struct audio_patch patch;
3837 outputDesc->toAudioPortConfig(&patch.sources[0]);
3838 patch.num_sources = 1;
3839 patch.num_sinks = 0;
3840 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3841 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003842 patch.num_sinks++;
3843 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003844 ssize_t index;
3845 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3846 index = mAudioPatches.indexOfKey(*patchHandle);
3847 } else {
3848 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3849 }
3850 sp< AudioPatch> patchDesc;
3851 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3852 if (index >= 0) {
3853 patchDesc = mAudioPatches.valueAt(index);
3854 afPatchHandle = patchDesc->mAfPatchHandle;
3855 }
3856
Eric Laurent1c333e22014-05-20 10:48:17 -07003857 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003858 &afPatchHandle,
3859 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003860 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3861 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003862 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003863 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003864 if (index < 0) {
3865 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3866 &patch, mUidCached);
3867 addAudioPatch(patchDesc->mHandle, patchDesc);
3868 } else {
3869 patchDesc->mPatch = patch;
3870 }
3871 patchDesc->mAfPatchHandle = afPatchHandle;
3872 patchDesc->mUid = mUidCached;
3873 if (patchHandle) {
3874 *patchHandle = patchDesc->mHandle;
3875 }
3876 outputDesc->mPatchHandle = patchDesc->mHandle;
3877 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003878 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003879 }
3880 }
3881 }
Eric Laurente552edb2014-03-10 17:42:56 -07003882
3883 // update stream volumes according to new device
3884 applyStreamVolumes(output, device, delayMs);
3885
3886 return muteWaitMs;
3887}
3888
Eric Laurent1c333e22014-05-20 10:48:17 -07003889status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003890 int delayMs,
3891 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003892{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003893 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003894 ssize_t index;
3895 if (patchHandle) {
3896 index = mAudioPatches.indexOfKey(*patchHandle);
3897 } else {
3898 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3899 }
3900 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003901 return INVALID_OPERATION;
3902 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003903 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3904 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003905 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3906 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003907 removeAudioPatch(patchDesc->mHandle);
3908 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003909 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003910 return status;
3911}
3912
3913status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3914 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003915 bool force,
3916 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003917{
3918 status_t status = NO_ERROR;
3919
Eric Laurent1f2f2232014-06-02 12:01:23 -07003920 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003921 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3922 inputDesc->mDevice = device;
3923
3924 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3925 if (!deviceList.isEmpty()) {
3926 struct audio_patch patch;
3927 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07003928 // AUDIO_SOURCE_HOTWORD is for internal use only:
3929 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
3930 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD) {
3931 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
3932 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003933 patch.num_sinks = 1;
3934 //only one input device for now
3935 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003936 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003937 ssize_t index;
3938 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3939 index = mAudioPatches.indexOfKey(*patchHandle);
3940 } else {
3941 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3942 }
3943 sp< AudioPatch> patchDesc;
3944 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3945 if (index >= 0) {
3946 patchDesc = mAudioPatches.valueAt(index);
3947 afPatchHandle = patchDesc->mAfPatchHandle;
3948 }
3949
Eric Laurent1c333e22014-05-20 10:48:17 -07003950 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003951 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003952 0);
3953 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003954 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003955 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003956 if (index < 0) {
3957 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3958 &patch, mUidCached);
3959 addAudioPatch(patchDesc->mHandle, patchDesc);
3960 } else {
3961 patchDesc->mPatch = patch;
3962 }
3963 patchDesc->mAfPatchHandle = afPatchHandle;
3964 patchDesc->mUid = mUidCached;
3965 if (patchHandle) {
3966 *patchHandle = patchDesc->mHandle;
3967 }
3968 inputDesc->mPatchHandle = patchDesc->mHandle;
3969 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003970 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003971 }
3972 }
3973 }
3974 return status;
3975}
3976
Eric Laurent6a94d692014-05-20 11:18:06 -07003977status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3978 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003979{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003980 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003981 ssize_t index;
3982 if (patchHandle) {
3983 index = mAudioPatches.indexOfKey(*patchHandle);
3984 } else {
3985 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3986 }
3987 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003988 return INVALID_OPERATION;
3989 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003990 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3991 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003992 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3993 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003994 removeAudioPatch(patchDesc->mHandle);
3995 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003996 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003997 return status;
3998}
3999
4000sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004001 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004002 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004003 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004004 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004005{
4006 // Choose an input profile based on the requested capture parameters: select the first available
4007 // profile supporting all requested parameters.
4008
4009 for (size_t i = 0; i < mHwModules.size(); i++)
4010 {
4011 if (mHwModules[i]->mHandle == 0) {
4012 continue;
4013 }
4014 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4015 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004016 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004017 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004018 if (profile->isCompatibleProfile(device, samplingRate,
4019 &samplingRate /*updatedSamplingRate*/,
4020 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004021 return profile;
4022 }
4023 }
4024 }
4025 return NULL;
4026}
4027
Eric Laurente0720872014-03-11 09:30:41 -07004028audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004029{
4030 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004031 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4032 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004033 switch (inputSource) {
4034 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004035 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004036 device = AUDIO_DEVICE_IN_VOICE_CALL;
4037 break;
4038 }
4039 // FALL THROUGH
4040
4041 case AUDIO_SOURCE_DEFAULT:
4042 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004043 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4044 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4045 break;
4046 }
4047 // FALL THROUGH
4048
Eric Laurente552edb2014-03-10 17:42:56 -07004049 case AUDIO_SOURCE_VOICE_RECOGNITION:
4050 case AUDIO_SOURCE_HOTWORD:
4051 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004052 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004053 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004054 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004055 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004056 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004057 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4058 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004060 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4061 }
4062 break;
4063 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004064 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004065 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004067 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4068 }
4069 break;
4070 case AUDIO_SOURCE_VOICE_DOWNLINK:
4071 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004072 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004073 device = AUDIO_DEVICE_IN_VOICE_CALL;
4074 }
4075 break;
4076 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004078 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4079 }
4080 break;
4081 default:
4082 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4083 break;
4084 }
4085 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4086 return device;
4087}
4088
Eric Laurente0720872014-03-11 09:30:41 -07004089bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004090{
4091 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4092 device &= ~AUDIO_DEVICE_BIT_IN;
4093 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4094 return true;
4095 }
4096 return false;
4097}
4098
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004099bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4100 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4101}
4102
Eric Laurente0720872014-03-11 09:30:41 -07004103audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004104{
4105 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004106 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004107 if ((input_descriptor->mRefCount > 0)
4108 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4109 return mInputs.keyAt(i);
4110 }
4111 }
4112 return 0;
4113}
4114
4115
Eric Laurente0720872014-03-11 09:30:41 -07004116audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004117{
4118 if (device == AUDIO_DEVICE_NONE) {
4119 // this happens when forcing a route update and no track is active on an output.
4120 // In this case the returned category is not important.
4121 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004122 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004123 // Multiple device selection is either:
4124 // - speaker + one other device: give priority to speaker in this case.
4125 // - one A2DP device + another device: happens with duplicated output. In this case
4126 // retain the device on the A2DP output as the other must not correspond to an active
4127 // selection if not the speaker.
4128 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4129 device = AUDIO_DEVICE_OUT_SPEAKER;
4130 } else {
4131 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4132 }
4133 }
4134
Eric Laurent3b73df72014-03-11 09:06:29 -07004135 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004136 "getDeviceForVolume() invalid device combination: %08x",
4137 device);
4138
4139 return device;
4140}
4141
Eric Laurente0720872014-03-11 09:30:41 -07004142AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004143{
4144 switch(getDeviceForVolume(device)) {
4145 case AUDIO_DEVICE_OUT_EARPIECE:
4146 return DEVICE_CATEGORY_EARPIECE;
4147 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4148 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4149 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4150 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4151 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4152 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4153 return DEVICE_CATEGORY_HEADSET;
4154 case AUDIO_DEVICE_OUT_SPEAKER:
4155 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4156 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4157 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4158 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4159 case AUDIO_DEVICE_OUT_USB_DEVICE:
4160 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4161 default:
4162 return DEVICE_CATEGORY_SPEAKER;
4163 }
4164}
4165
Eric Laurente0720872014-03-11 09:30:41 -07004166float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004167 int indexInUi)
4168{
4169 device_category deviceCategory = getDeviceCategory(device);
4170 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4171
4172 // the volume index in the UI is relative to the min and max volume indices for this stream type
4173 int nbSteps = 1 + curve[VOLMAX].mIndex -
4174 curve[VOLMIN].mIndex;
4175 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4176 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4177
4178 // find what part of the curve this index volume belongs to, or if it's out of bounds
4179 int segment = 0;
4180 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4181 return 0.0f;
4182 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4183 segment = 0;
4184 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4185 segment = 1;
4186 } else if (volIdx <= curve[VOLMAX].mIndex) {
4187 segment = 2;
4188 } else { // out of bounds
4189 return 1.0f;
4190 }
4191
4192 // linear interpolation in the attenuation table in dB
4193 float decibels = curve[segment].mDBAttenuation +
4194 ((float)(volIdx - curve[segment].mIndex)) *
4195 ( (curve[segment+1].mDBAttenuation -
4196 curve[segment].mDBAttenuation) /
4197 ((float)(curve[segment+1].mIndex -
4198 curve[segment].mIndex)) );
4199
4200 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4201
4202 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4203 curve[segment].mIndex, volIdx,
4204 curve[segment+1].mIndex,
4205 curve[segment].mDBAttenuation,
4206 decibels,
4207 curve[segment+1].mDBAttenuation,
4208 amplification);
4209
4210 return amplification;
4211}
4212
Eric Laurente0720872014-03-11 09:30:41 -07004213const AudioPolicyManager::VolumeCurvePoint
4214 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004215 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4216};
4217
Eric Laurente0720872014-03-11 09:30:41 -07004218const AudioPolicyManager::VolumeCurvePoint
4219 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004220 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4221};
4222
Eric Laurente0720872014-03-11 09:30:41 -07004223const AudioPolicyManager::VolumeCurvePoint
4224 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004225 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4226};
4227
Eric Laurente0720872014-03-11 09:30:41 -07004228const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004229 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004230 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004231};
4232
4233const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004234 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004235 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4236};
4237
Eric Laurente0720872014-03-11 09:30:41 -07004238const AudioPolicyManager::VolumeCurvePoint
4239 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004240 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4241};
4242
4243// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4244// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4245// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4246// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4247
Eric Laurente0720872014-03-11 09:30:41 -07004248const AudioPolicyManager::VolumeCurvePoint
4249 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004250 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4251};
4252
Eric Laurente0720872014-03-11 09:30:41 -07004253const AudioPolicyManager::VolumeCurvePoint
4254 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004255 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4256};
4257
Eric Laurente0720872014-03-11 09:30:41 -07004258const AudioPolicyManager::VolumeCurvePoint
4259 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004260 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4261};
4262
Eric Laurente0720872014-03-11 09:30:41 -07004263const AudioPolicyManager::VolumeCurvePoint
4264 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004265 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4266};
4267
Eric Laurente0720872014-03-11 09:30:41 -07004268const AudioPolicyManager::VolumeCurvePoint
4269 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004270 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4271};
4272
Eric Laurente0720872014-03-11 09:30:41 -07004273const AudioPolicyManager::VolumeCurvePoint
4274 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4275 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004276 { // AUDIO_STREAM_VOICE_CALL
4277 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4278 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4279 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4280 },
4281 { // AUDIO_STREAM_SYSTEM
4282 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4283 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4284 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4285 },
4286 { // AUDIO_STREAM_RING
4287 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4288 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4289 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4290 },
4291 { // AUDIO_STREAM_MUSIC
4292 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4293 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4294 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4295 },
4296 { // AUDIO_STREAM_ALARM
4297 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4298 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4299 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4300 },
4301 { // AUDIO_STREAM_NOTIFICATION
4302 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4303 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4304 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4305 },
4306 { // AUDIO_STREAM_BLUETOOTH_SCO
4307 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4308 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4309 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4310 },
4311 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4312 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4313 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4314 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4315 },
4316 { // AUDIO_STREAM_DTMF
4317 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4318 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4319 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4320 },
4321 { // AUDIO_STREAM_TTS
4322 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4323 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4324 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4325 },
4326};
4327
Eric Laurente0720872014-03-11 09:30:41 -07004328void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004329{
4330 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4331 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4332 mStreams[i].mVolumeCurve[j] =
4333 sVolumeProfiles[i][j];
4334 }
4335 }
4336
4337 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4338 if (mSpeakerDrcEnabled) {
4339 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4340 sDefaultSystemVolumeCurveDrc;
4341 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4342 sSpeakerSonificationVolumeCurveDrc;
4343 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4344 sSpeakerSonificationVolumeCurveDrc;
4345 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4346 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004347 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4348 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004349 }
4350}
4351
Eric Laurente0720872014-03-11 09:30:41 -07004352float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004353 int index,
4354 audio_io_handle_t output,
4355 audio_devices_t device)
4356{
4357 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004358 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004359 StreamDescriptor &streamDesc = mStreams[stream];
4360
4361 if (device == AUDIO_DEVICE_NONE) {
4362 device = outputDesc->device();
4363 }
4364
Eric Laurente552edb2014-03-10 17:42:56 -07004365 volume = volIndexToAmpl(device, streamDesc, index);
4366
4367 // if a headset is connected, apply the following rules to ring tones and notifications
4368 // to avoid sound level bursts in user's ears:
4369 // - always attenuate ring tones and notifications volume by 6dB
4370 // - if music is playing, always limit the volume to current music volume,
4371 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004372 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004373 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4374 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4375 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4376 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4377 ((stream_strategy == STRATEGY_SONIFICATION)
4378 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004379 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004380 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004381 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004382 streamDesc.mCanBeMuted) {
4383 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4384 // when the phone is ringing we must consider that music could have been paused just before
4385 // by the music application and behave as if music was active if the last music track was
4386 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004387 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004388 mLimitRingtoneVolume) {
4389 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004390 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4391 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004392 output,
4393 musicDevice);
4394 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4395 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4396 if (volume > minVol) {
4397 volume = minVol;
4398 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4399 }
4400 }
4401 }
4402
4403 return volume;
4404}
4405
Eric Laurente0720872014-03-11 09:30:41 -07004406status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004407 int index,
4408 audio_io_handle_t output,
4409 audio_devices_t device,
4410 int delayMs,
4411 bool force)
4412{
4413
4414 // do not change actual stream volume if the stream is muted
4415 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4416 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4417 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4418 return NO_ERROR;
4419 }
4420
4421 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004422 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4423 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4424 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4425 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004426 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004427 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004428 return INVALID_OPERATION;
4429 }
4430
4431 float volume = computeVolume(stream, index, output, device);
4432 // We actually change the volume if:
4433 // - the float value returned by computeVolume() changed
4434 // - the force flag is set
4435 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4436 force) {
4437 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4438 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4439 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4440 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004441 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4442 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004443 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004444 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004445 }
4446
Eric Laurent3b73df72014-03-11 09:06:29 -07004447 if (stream == AUDIO_STREAM_VOICE_CALL ||
4448 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004449 float voiceVolume;
4450 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004451 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004452 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4453 } else {
4454 voiceVolume = 1.0;
4455 }
4456
4457 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4458 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4459 mLastVoiceVolume = voiceVolume;
4460 }
4461 }
4462
4463 return NO_ERROR;
4464}
4465
Eric Laurente0720872014-03-11 09:30:41 -07004466void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004467 audio_devices_t device,
4468 int delayMs,
4469 bool force)
4470{
4471 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4472
Eric Laurent3b73df72014-03-11 09:06:29 -07004473 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4474 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004475 mStreams[stream].getVolumeIndex(device),
4476 output,
4477 device,
4478 delayMs,
4479 force);
4480 }
4481}
4482
Eric Laurente0720872014-03-11 09:30:41 -07004483void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004484 bool on,
4485 audio_io_handle_t output,
4486 int delayMs,
4487 audio_devices_t device)
4488{
4489 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004490 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4491 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4492 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004493 }
4494 }
4495}
4496
Eric Laurente0720872014-03-11 09:30:41 -07004497void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004498 bool on,
4499 audio_io_handle_t output,
4500 int delayMs,
4501 audio_devices_t device)
4502{
4503 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004504 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004505 if (device == AUDIO_DEVICE_NONE) {
4506 device = outputDesc->device();
4507 }
4508
4509 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4510 stream, on, output, outputDesc->mMuteCount[stream], device);
4511
4512 if (on) {
4513 if (outputDesc->mMuteCount[stream] == 0) {
4514 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004515 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4516 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004517 checkAndSetVolume(stream, 0, output, device, delayMs);
4518 }
4519 }
4520 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4521 outputDesc->mMuteCount[stream]++;
4522 } else {
4523 if (outputDesc->mMuteCount[stream] == 0) {
4524 ALOGV("setStreamMute() unmuting non muted stream!");
4525 return;
4526 }
4527 if (--outputDesc->mMuteCount[stream] == 0) {
4528 checkAndSetVolume(stream,
4529 streamDesc.getVolumeIndex(device),
4530 output,
4531 device,
4532 delayMs);
4533 }
4534 }
4535}
4536
Eric Laurente0720872014-03-11 09:30:41 -07004537void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004538 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004539{
4540 // if the stream pertains to sonification strategy and we are in call we must
4541 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4542 // in the device used for phone strategy and play the tone if the selected device does not
4543 // interfere with the device used for phone strategy
4544 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4545 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004546 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004547 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4548 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004549 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004550 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4551 stream, starting, outputDesc->mDevice, stateChange);
4552 if (outputDesc->mRefCount[stream]) {
4553 int muteCount = 1;
4554 if (stateChange) {
4555 muteCount = outputDesc->mRefCount[stream];
4556 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004557 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004558 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4559 for (int i = 0; i < muteCount; i++) {
4560 setStreamMute(stream, starting, mPrimaryOutput);
4561 }
4562 } else {
4563 ALOGV("handleIncallSonification() high visibility");
4564 if (outputDesc->device() &
4565 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4566 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4567 for (int i = 0; i < muteCount; i++) {
4568 setStreamMute(stream, starting, mPrimaryOutput);
4569 }
4570 }
4571 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004572 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4573 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004574 } else {
4575 mpClientInterface->stopTone();
4576 }
4577 }
4578 }
4579 }
4580}
4581
Eric Laurente0720872014-03-11 09:30:41 -07004582bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004583{
4584 return isStateInCall(mPhoneState);
4585}
4586
Eric Laurente0720872014-03-11 09:30:41 -07004587bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004588 return ((state == AUDIO_MODE_IN_CALL) ||
4589 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004590}
4591
Eric Laurente0720872014-03-11 09:30:41 -07004592uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004593{
4594 return MAX_EFFECTS_CPU_LOAD;
4595}
4596
Eric Laurente0720872014-03-11 09:30:41 -07004597uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004598{
4599 return MAX_EFFECTS_MEMORY;
4600}
4601
Eric Laurent6a94d692014-05-20 11:18:06 -07004602
Eric Laurente552edb2014-03-10 17:42:56 -07004603// --- AudioOutputDescriptor class implementation
4604
Eric Laurente0720872014-03-11 09:30:41 -07004605AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004606 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004607 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004608 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004609 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4610{
4611 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004612 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004613 mRefCount[i] = 0;
4614 mCurVolume[i] = -1.0;
4615 mMuteCount[i] = 0;
4616 mStopTime[i] = 0;
4617 }
4618 for (int i = 0; i < NUM_STRATEGIES; i++) {
4619 mStrategyMutedByDevice[i] = false;
4620 }
4621 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004622 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004623 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004624 mSamplingRate = profile->pickSamplingRate();
4625 mFormat = profile->pickFormat();
4626 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004627 if (profile->mGains.size() > 0) {
4628 profile->mGains[0]->getDefaultConfig(&mGain);
4629 }
Eric Laurente552edb2014-03-10 17:42:56 -07004630 }
4631}
4632
Eric Laurente0720872014-03-11 09:30:41 -07004633audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004634{
4635 if (isDuplicated()) {
4636 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4637 } else {
4638 return mDevice;
4639 }
4640}
4641
Eric Laurente0720872014-03-11 09:30:41 -07004642uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004643{
4644 if (isDuplicated()) {
4645 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4646 } else {
4647 return mLatency;
4648 }
4649}
4650
Eric Laurente0720872014-03-11 09:30:41 -07004651bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004652 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004653{
4654 if (isDuplicated()) {
4655 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4656 } else if (outputDesc->isDuplicated()){
4657 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4658 } else {
4659 return (mProfile->mModule == outputDesc->mProfile->mModule);
4660 }
4661}
4662
Eric Laurente0720872014-03-11 09:30:41 -07004663void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004664 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004665{
4666 // forward usage count change to attached outputs
4667 if (isDuplicated()) {
4668 mOutput1->changeRefCount(stream, delta);
4669 mOutput2->changeRefCount(stream, delta);
4670 }
4671 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004672 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4673 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004674 mRefCount[stream] = 0;
4675 return;
4676 }
4677 mRefCount[stream] += delta;
4678 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4679}
4680
Eric Laurente0720872014-03-11 09:30:41 -07004681audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004682{
4683 if (isDuplicated()) {
4684 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4685 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004686 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004687 }
4688}
4689
Eric Laurente0720872014-03-11 09:30:41 -07004690bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004691{
4692 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4693}
4694
Eric Laurente0720872014-03-11 09:30:41 -07004695bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004696 uint32_t inPastMs,
4697 nsecs_t sysTime) const
4698{
4699 if ((sysTime == 0) && (inPastMs != 0)) {
4700 sysTime = systemTime();
4701 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004702 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4703 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004704 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004705 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004706 return true;
4707 }
4708 }
4709 return false;
4710}
4711
Eric Laurente0720872014-03-11 09:30:41 -07004712bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004713 uint32_t inPastMs,
4714 nsecs_t sysTime) const
4715{
4716 if (mRefCount[stream] != 0) {
4717 return true;
4718 }
4719 if (inPastMs == 0) {
4720 return false;
4721 }
4722 if (sysTime == 0) {
4723 sysTime = systemTime();
4724 }
4725 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4726 return true;
4727 }
4728 return false;
4729}
4730
Eric Laurent1c333e22014-05-20 10:48:17 -07004731void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 struct audio_port_config *dstConfig,
4733 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004734{
Eric Laurent84c70242014-06-23 08:46:27 -07004735 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4736
Eric Laurent1f2f2232014-06-02 12:01:23 -07004737 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4738 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4739 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004740 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004741 }
4742 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4743
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 dstConfig->id = mId;
4745 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4746 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004747 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4748 dstConfig->ext.mix.handle = mIoHandle;
4749 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004750}
4751
4752void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4753 struct audio_port *port) const
4754{
Eric Laurent84c70242014-06-23 08:46:27 -07004755 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004756 mProfile->toAudioPort(port);
4757 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004758 toAudioPortConfig(&port->active_config);
4759 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004760 port->ext.mix.handle = mIoHandle;
4761 port->ext.mix.latency_class =
4762 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4763}
Eric Laurente552edb2014-03-10 17:42:56 -07004764
Eric Laurente0720872014-03-11 09:30:41 -07004765status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004766{
4767 const size_t SIZE = 256;
4768 char buffer[SIZE];
4769 String8 result;
4770
4771 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4772 result.append(buffer);
4773 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4774 result.append(buffer);
4775 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4776 result.append(buffer);
4777 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4778 result.append(buffer);
4779 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4780 result.append(buffer);
4781 snprintf(buffer, SIZE, " Devices %08x\n", device());
4782 result.append(buffer);
4783 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4784 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004785 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4786 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4787 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004788 result.append(buffer);
4789 }
4790 write(fd, result.string(), result.size());
4791
4792 return NO_ERROR;
4793}
4794
4795// --- AudioInputDescriptor class implementation
4796
Eric Laurent1c333e22014-05-20 10:48:17 -07004797AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004798 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004799 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004800 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004801{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004802 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004803 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004804 mSamplingRate = profile->pickSamplingRate();
4805 mFormat = profile->pickFormat();
4806 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004807 if (profile->mGains.size() > 0) {
4808 profile->mGains[0]->getDefaultConfig(&mGain);
4809 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004810 }
Eric Laurente552edb2014-03-10 17:42:56 -07004811}
4812
Eric Laurent1c333e22014-05-20 10:48:17 -07004813void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 struct audio_port_config *dstConfig,
4815 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004816{
Eric Laurent84c70242014-06-23 08:46:27 -07004817 ALOG_ASSERT(mProfile != 0,
4818 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004819 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4820 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4821 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004822 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004823 }
4824
4825 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4826
Eric Laurent6a94d692014-05-20 11:18:06 -07004827 dstConfig->id = mId;
4828 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4829 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004830 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4831 dstConfig->ext.mix.handle = mIoHandle;
4832 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004833}
4834
4835void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4836 struct audio_port *port) const
4837{
Eric Laurent84c70242014-06-23 08:46:27 -07004838 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4839
Eric Laurent1c333e22014-05-20 10:48:17 -07004840 mProfile->toAudioPort(port);
4841 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004842 toAudioPortConfig(&port->active_config);
4843 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004844 port->ext.mix.handle = mIoHandle;
4845 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4846}
4847
Eric Laurente0720872014-03-11 09:30:41 -07004848status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004849{
4850 const size_t SIZE = 256;
4851 char buffer[SIZE];
4852 String8 result;
4853
4854 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4855 result.append(buffer);
4856 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4857 result.append(buffer);
4858 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4859 result.append(buffer);
4860 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4861 result.append(buffer);
4862 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4863 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004864 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
4865 result.append(buffer);
4866
Eric Laurente552edb2014-03-10 17:42:56 -07004867 write(fd, result.string(), result.size());
4868
4869 return NO_ERROR;
4870}
4871
4872// --- StreamDescriptor class implementation
4873
Eric Laurente0720872014-03-11 09:30:41 -07004874AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004875 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4876{
4877 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4878}
4879
Eric Laurente0720872014-03-11 09:30:41 -07004880int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004881{
Eric Laurente0720872014-03-11 09:30:41 -07004882 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004883 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4884 if (mIndexCur.indexOfKey(device) < 0) {
4885 device = AUDIO_DEVICE_OUT_DEFAULT;
4886 }
4887 return mIndexCur.valueFor(device);
4888}
4889
Eric Laurente0720872014-03-11 09:30:41 -07004890void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004891{
4892 const size_t SIZE = 256;
4893 char buffer[SIZE];
4894 String8 result;
4895
4896 snprintf(buffer, SIZE, "%s %02d %02d ",
4897 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4898 result.append(buffer);
4899 for (size_t i = 0; i < mIndexCur.size(); i++) {
4900 snprintf(buffer, SIZE, "%04x : %02d, ",
4901 mIndexCur.keyAt(i),
4902 mIndexCur.valueAt(i));
4903 result.append(buffer);
4904 }
4905 result.append("\n");
4906
4907 write(fd, result.string(), result.size());
4908}
4909
4910// --- EffectDescriptor class implementation
4911
Eric Laurente0720872014-03-11 09:30:41 -07004912status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004913{
4914 const size_t SIZE = 256;
4915 char buffer[SIZE];
4916 String8 result;
4917
4918 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4919 result.append(buffer);
4920 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4921 result.append(buffer);
4922 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4923 result.append(buffer);
4924 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4925 result.append(buffer);
4926 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4927 result.append(buffer);
4928 write(fd, result.string(), result.size());
4929
4930 return NO_ERROR;
4931}
4932
Eric Laurent1c333e22014-05-20 10:48:17 -07004933// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004934
Eric Laurente0720872014-03-11 09:30:41 -07004935AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004936 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4937 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004938{
4939}
4940
Eric Laurente0720872014-03-11 09:30:41 -07004941AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004942{
4943 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004944 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004945 }
4946 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004947 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004948 }
4949 free((void *)mName);
4950}
4951
Eric Laurent1afeecb2014-05-14 08:52:28 -07004952status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4953{
4954 cnode *node = root->first_child;
4955
4956 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4957
4958 while (node) {
4959 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4960 profile->loadSamplingRates((char *)node->value);
4961 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4962 profile->loadFormats((char *)node->value);
4963 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4964 profile->loadInChannels((char *)node->value);
4965 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4966 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4967 mDeclaredDevices);
4968 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4969 profile->loadGains(node);
4970 }
4971 node = node->next;
4972 }
4973 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4974 "loadInput() invalid supported devices");
4975 ALOGW_IF(profile->mChannelMasks.size() == 0,
4976 "loadInput() invalid supported channel masks");
4977 ALOGW_IF(profile->mSamplingRates.size() == 0,
4978 "loadInput() invalid supported sampling rates");
4979 ALOGW_IF(profile->mFormats.size() == 0,
4980 "loadInput() invalid supported formats");
4981 if (!profile->mSupportedDevices.isEmpty() &&
4982 (profile->mChannelMasks.size() != 0) &&
4983 (profile->mSamplingRates.size() != 0) &&
4984 (profile->mFormats.size() != 0)) {
4985
4986 ALOGV("loadInput() adding input Supported Devices %04x",
4987 profile->mSupportedDevices.types());
4988
4989 mInputProfiles.add(profile);
4990 return NO_ERROR;
4991 } else {
4992 return BAD_VALUE;
4993 }
4994}
4995
4996status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4997{
4998 cnode *node = root->first_child;
4999
5000 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5001
5002 while (node) {
5003 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5004 profile->loadSamplingRates((char *)node->value);
5005 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5006 profile->loadFormats((char *)node->value);
5007 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5008 profile->loadOutChannels((char *)node->value);
5009 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5010 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5011 mDeclaredDevices);
5012 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5013 profile->mFlags = parseFlagNames((char *)node->value);
5014 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5015 profile->loadGains(node);
5016 }
5017 node = node->next;
5018 }
5019 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5020 "loadOutput() invalid supported devices");
5021 ALOGW_IF(profile->mChannelMasks.size() == 0,
5022 "loadOutput() invalid supported channel masks");
5023 ALOGW_IF(profile->mSamplingRates.size() == 0,
5024 "loadOutput() invalid supported sampling rates");
5025 ALOGW_IF(profile->mFormats.size() == 0,
5026 "loadOutput() invalid supported formats");
5027 if (!profile->mSupportedDevices.isEmpty() &&
5028 (profile->mChannelMasks.size() != 0) &&
5029 (profile->mSamplingRates.size() != 0) &&
5030 (profile->mFormats.size() != 0)) {
5031
5032 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5033 profile->mSupportedDevices.types(), profile->mFlags);
5034
5035 mOutputProfiles.add(profile);
5036 return NO_ERROR;
5037 } else {
5038 return BAD_VALUE;
5039 }
5040}
5041
5042status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5043{
5044 cnode *node = root->first_child;
5045
5046 audio_devices_t type = AUDIO_DEVICE_NONE;
5047 while (node) {
5048 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5049 type = parseDeviceNames((char *)node->value);
5050 break;
5051 }
5052 node = node->next;
5053 }
5054 if (type == AUDIO_DEVICE_NONE ||
5055 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5056 ALOGW("loadDevice() bad type %08x", type);
5057 return BAD_VALUE;
5058 }
5059 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5060 deviceDesc->mModule = this;
5061
5062 node = root->first_child;
5063 while (node) {
5064 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5065 deviceDesc->mAddress = String8((char *)node->value);
5066 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5067 if (audio_is_input_device(type)) {
5068 deviceDesc->loadInChannels((char *)node->value);
5069 } else {
5070 deviceDesc->loadOutChannels((char *)node->value);
5071 }
5072 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5073 deviceDesc->loadGains(node);
5074 }
5075 node = node->next;
5076 }
5077
5078 ALOGV("loadDevice() adding device name %s type %08x address %s",
5079 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5080
5081 mDeclaredDevices.add(deviceDesc);
5082
5083 return NO_ERROR;
5084}
5085
Eric Laurente0720872014-03-11 09:30:41 -07005086void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005087{
5088 const size_t SIZE = 256;
5089 char buffer[SIZE];
5090 String8 result;
5091
5092 snprintf(buffer, SIZE, " - name: %s\n", mName);
5093 result.append(buffer);
5094 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5095 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005096 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5097 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005098 write(fd, result.string(), result.size());
5099 if (mOutputProfiles.size()) {
5100 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5101 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005102 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005103 write(fd, buffer, strlen(buffer));
5104 mOutputProfiles[i]->dump(fd);
5105 }
5106 }
5107 if (mInputProfiles.size()) {
5108 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5109 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005110 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005111 write(fd, buffer, strlen(buffer));
5112 mInputProfiles[i]->dump(fd);
5113 }
5114 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005115 if (mDeclaredDevices.size()) {
5116 write(fd, " - devices:\n", strlen(" - devices:\n"));
5117 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5118 mDeclaredDevices[i]->dump(fd, 4, i);
5119 }
5120 }
Eric Laurente552edb2014-03-10 17:42:56 -07005121}
5122
Eric Laurent1c333e22014-05-20 10:48:17 -07005123// --- AudioPort class implementation
5124
Eric Laurenta121f902014-06-03 13:32:54 -07005125
5126AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5127 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005128 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005129{
5130 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5131 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5132}
5133
Eric Laurent1c333e22014-05-20 10:48:17 -07005134void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5135{
5136 port->role = mRole;
5137 port->type = mType;
5138 unsigned int i;
5139 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5140 port->sample_rates[i] = mSamplingRates[i];
5141 }
5142 port->num_sample_rates = i;
5143 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5144 port->channel_masks[i] = mChannelMasks[i];
5145 }
5146 port->num_channel_masks = i;
5147 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5148 port->formats[i] = mFormats[i];
5149 }
5150 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005151
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005152 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005153
5154 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5155 port->gains[i] = mGains[i]->mGain;
5156 }
5157 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005158}
5159
5160
5161void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5162{
5163 char *str = strtok(name, "|");
5164
5165 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5166 // rates should be read from the output stream after it is opened for the first time
5167 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5168 mSamplingRates.add(0);
5169 return;
5170 }
5171
5172 while (str != NULL) {
5173 uint32_t rate = atoi(str);
5174 if (rate != 0) {
5175 ALOGV("loadSamplingRates() adding rate %d", rate);
5176 mSamplingRates.add(rate);
5177 }
5178 str = strtok(NULL, "|");
5179 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005180}
5181
5182void AudioPolicyManager::AudioPort::loadFormats(char *name)
5183{
5184 char *str = strtok(name, "|");
5185
5186 // by convention, "0' in the first entry in mFormats indicates the supported formats
5187 // should be read from the output stream after it is opened for the first time
5188 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5189 mFormats.add(AUDIO_FORMAT_DEFAULT);
5190 return;
5191 }
5192
5193 while (str != NULL) {
5194 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5195 ARRAY_SIZE(sFormatNameToEnumTable),
5196 str);
5197 if (format != AUDIO_FORMAT_DEFAULT) {
5198 mFormats.add(format);
5199 }
5200 str = strtok(NULL, "|");
5201 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005202}
5203
5204void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5205{
5206 const char *str = strtok(name, "|");
5207
5208 ALOGV("loadInChannels() %s", name);
5209
5210 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5211 mChannelMasks.add(0);
5212 return;
5213 }
5214
5215 while (str != NULL) {
5216 audio_channel_mask_t channelMask =
5217 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5218 ARRAY_SIZE(sInChannelsNameToEnumTable),
5219 str);
5220 if (channelMask != 0) {
5221 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5222 mChannelMasks.add(channelMask);
5223 }
5224 str = strtok(NULL, "|");
5225 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005226}
5227
5228void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5229{
5230 const char *str = strtok(name, "|");
5231
5232 ALOGV("loadOutChannels() %s", name);
5233
5234 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5235 // masks should be read from the output stream after it is opened for the first time
5236 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5237 mChannelMasks.add(0);
5238 return;
5239 }
5240
5241 while (str != NULL) {
5242 audio_channel_mask_t channelMask =
5243 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5244 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5245 str);
5246 if (channelMask != 0) {
5247 mChannelMasks.add(channelMask);
5248 }
5249 str = strtok(NULL, "|");
5250 }
5251 return;
5252}
5253
Eric Laurent1afeecb2014-05-14 08:52:28 -07005254audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5255{
5256 const char *str = strtok(name, "|");
5257
5258 ALOGV("loadGainMode() %s", name);
5259 audio_gain_mode_t mode = 0;
5260 while (str != NULL) {
5261 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5262 ARRAY_SIZE(sGainModeNameToEnumTable),
5263 str);
5264 str = strtok(NULL, "|");
5265 }
5266 return mode;
5267}
5268
Eric Laurenta121f902014-06-03 13:32:54 -07005269void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005270{
5271 cnode *node = root->first_child;
5272
Eric Laurenta121f902014-06-03 13:32:54 -07005273 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005274
5275 while (node) {
5276 if (strcmp(node->name, GAIN_MODE) == 0) {
5277 gain->mGain.mode = loadGainMode((char *)node->value);
5278 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005279 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005280 gain->mGain.channel_mask =
5281 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5282 ARRAY_SIZE(sInChannelsNameToEnumTable),
5283 (char *)node->value);
5284 } else {
5285 gain->mGain.channel_mask =
5286 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5287 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5288 (char *)node->value);
5289 }
5290 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5291 gain->mGain.min_value = atoi((char *)node->value);
5292 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5293 gain->mGain.max_value = atoi((char *)node->value);
5294 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5295 gain->mGain.default_value = atoi((char *)node->value);
5296 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5297 gain->mGain.step_value = atoi((char *)node->value);
5298 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5299 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5300 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5301 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5302 }
5303 node = node->next;
5304 }
5305
5306 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5307 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5308
5309 if (gain->mGain.mode == 0) {
5310 return;
5311 }
5312 mGains.add(gain);
5313}
5314
5315void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5316{
5317 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005318 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005319 while (node) {
5320 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005321 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005322 node = node->next;
5323 }
5324}
5325
Glenn Kastencbd48022014-07-24 13:46:44 -07005326status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005327{
5328 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5329 if (mSamplingRates[i] == samplingRate) {
5330 return NO_ERROR;
5331 }
5332 }
5333 return BAD_VALUE;
5334}
5335
Glenn Kastencbd48022014-07-24 13:46:44 -07005336status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5337 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005338{
Glenn Kastencbd48022014-07-24 13:46:44 -07005339 // Search for the closest supported sampling rate that is above (preferred)
5340 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5341 // The sampling rates do not need to be sorted in ascending order.
5342 ssize_t maxBelow = -1;
5343 ssize_t minAbove = -1;
5344 uint32_t candidate;
5345 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5346 candidate = mSamplingRates[i];
5347 if (candidate == samplingRate) {
5348 if (updatedSamplingRate != NULL) {
5349 *updatedSamplingRate = candidate;
5350 }
5351 return NO_ERROR;
5352 }
5353 // candidate < desired
5354 if (candidate < samplingRate) {
5355 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5356 maxBelow = i;
5357 }
5358 // candidate > desired
5359 } else {
5360 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5361 minAbove = i;
5362 }
5363 }
5364 }
5365 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5366 // TODO Move these assumptions out.
5367 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5368 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5369 // due to approximation by an int32_t of the
5370 // phase increments
5371 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5372 if (minAbove >= 0) {
5373 candidate = mSamplingRates[minAbove];
5374 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5375 if (updatedSamplingRate != NULL) {
5376 *updatedSamplingRate = candidate;
5377 }
5378 return NO_ERROR;
5379 }
5380 }
5381 // But if we have to up-sample from a lower sampling rate, that's OK.
5382 if (maxBelow >= 0) {
5383 candidate = mSamplingRates[maxBelow];
5384 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5385 if (updatedSamplingRate != NULL) {
5386 *updatedSamplingRate = candidate;
5387 }
5388 return NO_ERROR;
5389 }
5390 }
5391 // leave updatedSamplingRate unmodified
5392 return BAD_VALUE;
5393}
5394
5395status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5396{
5397 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005398 if (mChannelMasks[i] == channelMask) {
5399 return NO_ERROR;
5400 }
5401 }
5402 return BAD_VALUE;
5403}
5404
Glenn Kastencbd48022014-07-24 13:46:44 -07005405status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5406 const
5407{
5408 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5409 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5410 // FIXME Does not handle multi-channel automatic conversions yet
5411 audio_channel_mask_t supported = mChannelMasks[i];
5412 if (supported == channelMask) {
5413 return NO_ERROR;
5414 }
5415 if (isRecordThread) {
5416 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5417 // FIXME Abstract this out to a table.
5418 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5419 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5420 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5421 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5422 return NO_ERROR;
5423 }
5424 }
5425 }
5426 return BAD_VALUE;
5427}
5428
Eric Laurenta121f902014-06-03 13:32:54 -07005429status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5430{
5431 for (size_t i = 0; i < mFormats.size(); i ++) {
5432 if (mFormats[i] == format) {
5433 return NO_ERROR;
5434 }
5435 }
5436 return BAD_VALUE;
5437}
5438
Eric Laurent1e693b52014-07-09 15:03:28 -07005439
5440uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5441{
5442 // special case for uninitialized dynamic profile
5443 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5444 return 0;
5445 }
5446
5447 uint32_t samplingRate = 0;
5448 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5449
5450 // For mixed output and inputs, use max mixer sampling rates. Do not
5451 // limit sampling rate otherwise
5452 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5453 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5454 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5455 maxRate = UINT_MAX;
5456 }
5457 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5458 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5459 samplingRate = mSamplingRates[i];
5460 }
5461 }
5462 return samplingRate;
5463}
5464
5465audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5466{
5467 // special case for uninitialized dynamic profile
5468 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5469 return AUDIO_CHANNEL_NONE;
5470 }
5471
5472 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5473 uint32_t channelCount = 0;
5474 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5475
5476 // For mixed output and inputs, use max mixer channel count. Do not
5477 // limit channel count otherwise
5478 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5479 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5480 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5481 maxCount = UINT_MAX;
5482 }
5483 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5484 uint32_t cnlCount;
5485 if (mUseInChannelMask) {
5486 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5487 } else {
5488 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5489 }
5490 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5491 channelMask = mChannelMasks[i];
5492 }
5493 }
5494 return channelMask;
5495}
5496
Andy Hung9a605382014-07-28 16:16:31 -07005497/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005498const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5499 AUDIO_FORMAT_DEFAULT,
5500 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005501 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005502 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005503 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005504 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005505};
5506
5507int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5508 audio_format_t format2)
5509{
5510 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5511 // compressed format and better than any PCM format. This is by design of pickFormat()
5512 if (!audio_is_linear_pcm(format1)) {
5513 if (!audio_is_linear_pcm(format2)) {
5514 return 0;
5515 }
5516 return 1;
5517 }
5518 if (!audio_is_linear_pcm(format2)) {
5519 return -1;
5520 }
5521
5522 int index1 = -1, index2 = -1;
5523 for (size_t i = 0;
5524 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5525 i ++) {
5526 if (sPcmFormatCompareTable[i] == format1) {
5527 index1 = i;
5528 }
5529 if (sPcmFormatCompareTable[i] == format2) {
5530 index2 = i;
5531 }
5532 }
5533 // format1 not found => index1 < 0 => format2 > format1
5534 // format2 not found => index2 < 0 => format2 < format1
5535 return index1 - index2;
5536}
5537
5538audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5539{
5540 // special case for uninitialized dynamic profile
5541 if (mFormats.size() == 1 && mFormats[0] == 0) {
5542 return AUDIO_FORMAT_DEFAULT;
5543 }
5544
5545 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005546 audio_format_t bestFormat =
5547 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5548 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005549 // For mixed output and inputs, use best mixer output format. Do not
5550 // limit format otherwise
5551 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5552 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005553 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005554 bestFormat = AUDIO_FORMAT_INVALID;
5555 }
5556
5557 for (size_t i = 0; i < mFormats.size(); i ++) {
5558 if ((compareFormats(mFormats[i], format) > 0) &&
5559 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5560 format = mFormats[i];
5561 }
5562 }
5563 return format;
5564}
5565
Eric Laurenta121f902014-06-03 13:32:54 -07005566status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5567 int index) const
5568{
5569 if (index < 0 || (size_t)index >= mGains.size()) {
5570 return BAD_VALUE;
5571 }
5572 return mGains[index]->checkConfig(gainConfig);
5573}
5574
Eric Laurent1afeecb2014-05-14 08:52:28 -07005575void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5576{
5577 const size_t SIZE = 256;
5578 char buffer[SIZE];
5579 String8 result;
5580
5581 if (mName.size() != 0) {
5582 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5583 result.append(buffer);
5584 }
5585
5586 if (mSamplingRates.size() != 0) {
5587 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5588 result.append(buffer);
5589 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005590 if (i == 0 && mSamplingRates[i] == 0) {
5591 snprintf(buffer, SIZE, "Dynamic");
5592 } else {
5593 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5594 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005595 result.append(buffer);
5596 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5597 }
5598 result.append("\n");
5599 }
5600
5601 if (mChannelMasks.size() != 0) {
5602 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5603 result.append(buffer);
5604 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005605 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5606
5607 if (i == 0 && mChannelMasks[i] == 0) {
5608 snprintf(buffer, SIZE, "Dynamic");
5609 } else {
5610 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5611 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005612 result.append(buffer);
5613 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5614 }
5615 result.append("\n");
5616 }
5617
5618 if (mFormats.size() != 0) {
5619 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5620 result.append(buffer);
5621 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005622 const char *formatStr = enumToString(sFormatNameToEnumTable,
5623 ARRAY_SIZE(sFormatNameToEnumTable),
5624 mFormats[i]);
5625 if (i == 0 && strcmp(formatStr, "") == 0) {
5626 snprintf(buffer, SIZE, "Dynamic");
5627 } else {
5628 snprintf(buffer, SIZE, "%-48s", formatStr);
5629 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005630 result.append(buffer);
5631 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5632 }
5633 result.append("\n");
5634 }
5635 write(fd, result.string(), result.size());
5636 if (mGains.size() != 0) {
5637 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5638 write(fd, buffer, strlen(buffer) + 1);
5639 result.append(buffer);
5640 for (size_t i = 0; i < mGains.size(); i++) {
5641 mGains[i]->dump(fd, spaces + 2, i);
5642 }
5643 }
5644}
5645
5646// --- AudioGain class implementation
5647
Eric Laurenta121f902014-06-03 13:32:54 -07005648AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005649{
Eric Laurenta121f902014-06-03 13:32:54 -07005650 mIndex = index;
5651 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005652 memset(&mGain, 0, sizeof(struct audio_gain));
5653}
5654
Eric Laurenta121f902014-06-03 13:32:54 -07005655void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5656{
5657 config->index = mIndex;
5658 config->mode = mGain.mode;
5659 config->channel_mask = mGain.channel_mask;
5660 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5661 config->values[0] = mGain.default_value;
5662 } else {
5663 uint32_t numValues;
5664 if (mUseInChannelMask) {
5665 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5666 } else {
5667 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5668 }
5669 for (size_t i = 0; i < numValues; i++) {
5670 config->values[i] = mGain.default_value;
5671 }
5672 }
5673 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5674 config->ramp_duration_ms = mGain.min_ramp_ms;
5675 }
5676}
5677
5678status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5679{
5680 if ((config->mode & ~mGain.mode) != 0) {
5681 return BAD_VALUE;
5682 }
5683 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5684 if ((config->values[0] < mGain.min_value) ||
5685 (config->values[0] > mGain.max_value)) {
5686 return BAD_VALUE;
5687 }
5688 } else {
5689 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5690 return BAD_VALUE;
5691 }
5692 uint32_t numValues;
5693 if (mUseInChannelMask) {
5694 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5695 } else {
5696 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5697 }
5698 for (size_t i = 0; i < numValues; i++) {
5699 if ((config->values[i] < mGain.min_value) ||
5700 (config->values[i] > mGain.max_value)) {
5701 return BAD_VALUE;
5702 }
5703 }
5704 }
5705 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5706 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5707 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5708 return BAD_VALUE;
5709 }
5710 }
5711 return NO_ERROR;
5712}
5713
Eric Laurent1afeecb2014-05-14 08:52:28 -07005714void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5715{
5716 const size_t SIZE = 256;
5717 char buffer[SIZE];
5718 String8 result;
5719
5720 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5721 result.append(buffer);
5722 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5723 result.append(buffer);
5724 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5725 result.append(buffer);
5726 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5727 result.append(buffer);
5728 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5729 result.append(buffer);
5730 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5731 result.append(buffer);
5732 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5733 result.append(buffer);
5734 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5735 result.append(buffer);
5736 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5737 result.append(buffer);
5738
5739 write(fd, result.string(), result.size());
5740}
5741
Eric Laurent1f2f2232014-06-02 12:01:23 -07005742// --- AudioPortConfig class implementation
5743
5744AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5745{
5746 mSamplingRate = 0;
5747 mChannelMask = AUDIO_CHANNEL_NONE;
5748 mFormat = AUDIO_FORMAT_INVALID;
5749 mGain.index = -1;
5750}
5751
Eric Laurenta121f902014-06-03 13:32:54 -07005752status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5753 const struct audio_port_config *config,
5754 struct audio_port_config *backupConfig)
5755{
5756 struct audio_port_config localBackupConfig;
5757 status_t status = NO_ERROR;
5758
5759 localBackupConfig.config_mask = config->config_mask;
5760 toAudioPortConfig(&localBackupConfig);
5761
5762 if (mAudioPort == 0) {
5763 status = NO_INIT;
5764 goto exit;
5765 }
5766 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005767 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005768 if (status != NO_ERROR) {
5769 goto exit;
5770 }
5771 mSamplingRate = config->sample_rate;
5772 }
5773 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005774 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005775 if (status != NO_ERROR) {
5776 goto exit;
5777 }
5778 mChannelMask = config->channel_mask;
5779 }
5780 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5781 status = mAudioPort->checkFormat(config->format);
5782 if (status != NO_ERROR) {
5783 goto exit;
5784 }
5785 mFormat = config->format;
5786 }
5787 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5788 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5789 if (status != NO_ERROR) {
5790 goto exit;
5791 }
5792 mGain = config->gain;
5793 }
5794
5795exit:
5796 if (status != NO_ERROR) {
5797 applyAudioPortConfig(&localBackupConfig);
5798 }
5799 if (backupConfig != NULL) {
5800 *backupConfig = localBackupConfig;
5801 }
5802 return status;
5803}
5804
Eric Laurent1f2f2232014-06-02 12:01:23 -07005805void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5806 struct audio_port_config *dstConfig,
5807 const struct audio_port_config *srcConfig) const
5808{
5809 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5810 dstConfig->sample_rate = mSamplingRate;
5811 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5812 dstConfig->sample_rate = srcConfig->sample_rate;
5813 }
5814 } else {
5815 dstConfig->sample_rate = 0;
5816 }
5817 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5818 dstConfig->channel_mask = mChannelMask;
5819 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5820 dstConfig->channel_mask = srcConfig->channel_mask;
5821 }
5822 } else {
5823 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5824 }
5825 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5826 dstConfig->format = mFormat;
5827 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5828 dstConfig->format = srcConfig->format;
5829 }
5830 } else {
5831 dstConfig->format = AUDIO_FORMAT_INVALID;
5832 }
5833 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5834 dstConfig->gain = mGain;
5835 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5836 dstConfig->gain = srcConfig->gain;
5837 }
5838 } else {
5839 dstConfig->gain.index = -1;
5840 }
5841 if (dstConfig->gain.index != -1) {
5842 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5843 } else {
5844 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5845 }
5846}
5847
Eric Laurent1c333e22014-05-20 10:48:17 -07005848// --- IOProfile class implementation
5849
Eric Laurent1afeecb2014-05-14 08:52:28 -07005850AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005851 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07005852 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07005853{
5854}
5855
Eric Laurente0720872014-03-11 09:30:41 -07005856AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005857{
5858}
5859
5860// checks if the IO profile is compatible with specified parameters.
5861// Sampling rate, format and channel mask must be specified in order to
5862// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005863bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005864 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005865 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005866 audio_format_t format,
5867 audio_channel_mask_t channelMask,
5868 audio_output_flags_t flags) const
5869{
Glenn Kastencbd48022014-07-24 13:46:44 -07005870 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
5871 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5872 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07005873
Glenn Kastencbd48022014-07-24 13:46:44 -07005874 if ((mSupportedDevices.types() & device) != device) {
5875 return false;
5876 }
5877
5878 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005879 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005880 }
5881 uint32_t myUpdatedSamplingRate = samplingRate;
5882 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005883 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005884 }
5885 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
5886 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005887 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005888 }
5889
5890 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
5891 return false;
5892 }
5893
5894 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
5895 checkExactChannelMask(channelMask) != NO_ERROR)) {
5896 return false;
5897 }
5898 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
5899 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
5900 return false;
5901 }
5902
5903 if (isPlaybackThread && (mFlags & flags) != flags) {
5904 return false;
5905 }
5906 // The only input flag that is allowed to be different is the fast flag.
5907 // An existing fast stream is compatible with a normal track request.
5908 // An existing normal stream is compatible with a fast track request,
5909 // but the fast request will be denied by AudioFlinger and converted to normal track.
5910 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
5911 ~AUDIO_INPUT_FLAG_FAST)) {
5912 return false;
5913 }
5914
5915 if (updatedSamplingRate != NULL) {
5916 *updatedSamplingRate = myUpdatedSamplingRate;
5917 }
5918 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07005919}
5920
Eric Laurente0720872014-03-11 09:30:41 -07005921void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005922{
5923 const size_t SIZE = 256;
5924 char buffer[SIZE];
5925 String8 result;
5926
Eric Laurent1afeecb2014-05-14 08:52:28 -07005927 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005928
Eric Laurente552edb2014-03-10 17:42:56 -07005929 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5930 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005931 snprintf(buffer, SIZE, " - devices:\n");
5932 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005933 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005934 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5935 mSupportedDevices[i]->dump(fd, 6, i);
5936 }
Eric Laurente552edb2014-03-10 17:42:56 -07005937}
5938
Eric Laurentd4692962014-05-05 18:13:44 -07005939void AudioPolicyManager::IOProfile::log()
5940{
5941 const size_t SIZE = 256;
5942 char buffer[SIZE];
5943 String8 result;
5944
5945 ALOGV(" - sampling rates: ");
5946 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5947 ALOGV(" %d", mSamplingRates[i]);
5948 }
5949
5950 ALOGV(" - channel masks: ");
5951 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5952 ALOGV(" 0x%04x", mChannelMasks[i]);
5953 }
5954
5955 ALOGV(" - formats: ");
5956 for (size_t i = 0; i < mFormats.size(); i++) {
5957 ALOGV(" 0x%08x", mFormats[i]);
5958 }
5959
5960 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5961 ALOGV(" - flags: 0x%04x\n", mFlags);
5962}
5963
5964
Eric Laurent3a4311c2014-03-17 12:00:47 -07005965// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005966
Eric Laurent1f2f2232014-06-02 12:01:23 -07005967
5968AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5969 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5970 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5971 AUDIO_PORT_ROLE_SOURCE,
5972 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07005973 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005974{
5975 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005976 if (mGains.size() > 0) {
5977 mGains[0]->getDefaultConfig(&mGain);
5978 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005979}
5980
Eric Laurent3a4311c2014-03-17 12:00:47 -07005981bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005982{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005983 // Devices are considered equal if they:
5984 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5985 // - have the same address or one device does not specify the address
5986 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005987 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005988 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005989 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005990 mChannelMask == other->mChannelMask);
5991}
5992
5993void AudioPolicyManager::DeviceVector::refreshTypes()
5994{
Eric Laurent1c333e22014-05-20 10:48:17 -07005995 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005996 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005997 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005998 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005999 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006000}
6001
6002ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6003{
6004 for(size_t i = 0; i < size(); i++) {
6005 if (item->equals(itemAt(i))) {
6006 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006007 }
6008 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006009 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006010}
6011
Eric Laurent3a4311c2014-03-17 12:00:47 -07006012ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006013{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006014 ssize_t ret = indexOf(item);
6015
6016 if (ret < 0) {
6017 ret = SortedVector::add(item);
6018 if (ret >= 0) {
6019 refreshTypes();
6020 }
6021 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006022 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006023 ret = -1;
6024 }
6025 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006026}
6027
Eric Laurent3a4311c2014-03-17 12:00:47 -07006028ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6029{
6030 size_t i;
6031 ssize_t ret = indexOf(item);
6032
6033 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006034 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006035 } else {
6036 ret = SortedVector::removeAt(ret);
6037 if (ret >= 0) {
6038 refreshTypes();
6039 }
6040 }
6041 return ret;
6042}
6043
6044void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6045{
6046 DeviceVector deviceList;
6047
6048 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6049 types &= ~role_bit;
6050
6051 while (types) {
6052 uint32_t i = 31 - __builtin_clz(types);
6053 uint32_t type = 1 << i;
6054 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006055 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006056 }
6057}
6058
Eric Laurent1afeecb2014-05-14 08:52:28 -07006059void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6060 const DeviceVector& declaredDevices)
6061{
6062 char *devName = strtok(name, "|");
6063 while (devName != NULL) {
6064 if (strlen(devName) != 0) {
6065 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6066 ARRAY_SIZE(sDeviceNameToEnumTable),
6067 devName);
6068 if (type != AUDIO_DEVICE_NONE) {
6069 add(new DeviceDescriptor(String8(""), type));
6070 } else {
6071 sp<DeviceDescriptor> deviceDesc =
6072 declaredDevices.getDeviceFromName(String8(devName));
6073 if (deviceDesc != 0) {
6074 add(deviceDesc);
6075 }
6076 }
6077 }
6078 devName = strtok(NULL, "|");
6079 }
6080}
6081
Eric Laurent1c333e22014-05-20 10:48:17 -07006082sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6083 audio_devices_t type, String8 address) const
6084{
6085 sp<DeviceDescriptor> device;
6086 for (size_t i = 0; i < size(); i++) {
6087 if (itemAt(i)->mDeviceType == type) {
6088 device = itemAt(i);
6089 if (itemAt(i)->mAddress = address) {
6090 break;
6091 }
6092 }
6093 }
6094 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6095 type, address.string(), device.get());
6096 return device;
6097}
6098
Eric Laurent6a94d692014-05-20 11:18:06 -07006099sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6100 audio_port_handle_t id) const
6101{
6102 sp<DeviceDescriptor> device;
6103 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006104 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006105 if (itemAt(i)->mId == id) {
6106 device = itemAt(i);
6107 break;
6108 }
6109 }
6110 return device;
6111}
6112
Eric Laurent1c333e22014-05-20 10:48:17 -07006113AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6114 audio_devices_t type) const
6115{
6116 DeviceVector devices;
6117 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6118 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6119 devices.add(itemAt(i));
6120 type &= ~itemAt(i)->mDeviceType;
6121 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6122 itemAt(i)->mDeviceType, itemAt(i).get());
6123 }
6124 }
6125 return devices;
6126}
6127
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006128AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6129 audio_devices_t type, String8 address) const
6130{
6131 DeviceVector devices;
6132 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6133 for (size_t i = 0; i < size(); i++) {
6134 //ALOGV(" at i=%d: device=%x, addr=%s",
6135 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6136 if (itemAt(i)->mDeviceType == type) {
6137 if (itemAt(i)->mAddress == address) {
6138 //ALOGV(" found matching address %s", address.string());
6139 devices.add(itemAt(i));
6140 }
6141 }
6142 }
6143 return devices;
6144}
6145
Eric Laurent1afeecb2014-05-14 08:52:28 -07006146sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6147 const String8& name) const
6148{
6149 sp<DeviceDescriptor> device;
6150 for (size_t i = 0; i < size(); i++) {
6151 if (itemAt(i)->mName == name) {
6152 device = itemAt(i);
6153 break;
6154 }
6155 }
6156 return device;
6157}
6158
Eric Laurent6a94d692014-05-20 11:18:06 -07006159void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6160 struct audio_port_config *dstConfig,
6161 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006162{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006163 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6164 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006165 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006166 }
6167
6168 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6169
Eric Laurent6a94d692014-05-20 11:18:06 -07006170 dstConfig->id = mId;
6171 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006172 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006173 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006174 dstConfig->ext.device.type = mDeviceType;
6175 dstConfig->ext.device.hw_module = mModule->mHandle;
6176 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006177}
6178
6179void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6180{
Eric Laurent83b88082014-06-20 18:31:16 -07006181 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006182 AudioPort::toAudioPort(port);
6183 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006184 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006185 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006186 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006187 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6188}
6189
Eric Laurent1afeecb2014-05-14 08:52:28 -07006190status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006191{
6192 const size_t SIZE = 256;
6193 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006194 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006195
Eric Laurent1afeecb2014-05-14 08:52:28 -07006196 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6197 result.append(buffer);
6198 if (mId != 0) {
6199 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6200 result.append(buffer);
6201 }
6202 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6203 enumToString(sDeviceNameToEnumTable,
6204 ARRAY_SIZE(sDeviceNameToEnumTable),
6205 mDeviceType));
6206 result.append(buffer);
6207 if (mAddress.size() != 0) {
6208 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6209 result.append(buffer);
6210 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006211 write(fd, result.string(), result.size());
6212 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006213
6214 return NO_ERROR;
6215}
6216
6217
6218// --- audio_policy.conf file parsing
6219
Eric Laurente0720872014-03-11 09:30:41 -07006220audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006221{
6222 uint32_t flag = 0;
6223
6224 // it is OK to cast name to non const here as we are not going to use it after
6225 // strtok() modifies it
6226 char *flagName = strtok(name, "|");
6227 while (flagName != NULL) {
6228 if (strlen(flagName) != 0) {
6229 flag |= stringToEnum(sFlagNameToEnumTable,
6230 ARRAY_SIZE(sFlagNameToEnumTable),
6231 flagName);
6232 }
6233 flagName = strtok(NULL, "|");
6234 }
6235 //force direct flag if offload flag is set: offloading implies a direct output stream
6236 // and all common behaviors are driven by checking only the direct flag
6237 // this should normally be set appropriately in the policy configuration file
6238 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6239 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6240 }
6241
6242 return (audio_output_flags_t)flag;
6243}
6244
Eric Laurente0720872014-03-11 09:30:41 -07006245audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006246{
6247 uint32_t device = 0;
6248
6249 char *devName = strtok(name, "|");
6250 while (devName != NULL) {
6251 if (strlen(devName) != 0) {
6252 device |= stringToEnum(sDeviceNameToEnumTable,
6253 ARRAY_SIZE(sDeviceNameToEnumTable),
6254 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006255 }
Eric Laurente552edb2014-03-10 17:42:56 -07006256 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006257 }
Eric Laurente552edb2014-03-10 17:42:56 -07006258 return device;
6259}
6260
Eric Laurente0720872014-03-11 09:30:41 -07006261void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006262{
Eric Laurente552edb2014-03-10 17:42:56 -07006263 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006264 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006265 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006266
Eric Laurent1afeecb2014-05-14 08:52:28 -07006267 node = config_find(root, DEVICES_TAG);
6268 if (node != NULL) {
6269 node = node->first_child;
6270 while (node) {
6271 ALOGV("loadHwModule() loading device %s", node->name);
6272 status_t tmpStatus = module->loadDevice(node);
6273 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6274 status = tmpStatus;
6275 }
6276 node = node->next;
6277 }
6278 }
6279 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006280 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006281 node = node->first_child;
6282 while (node) {
6283 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006284 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006285 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6286 status = tmpStatus;
6287 }
6288 node = node->next;
6289 }
6290 }
6291 node = config_find(root, INPUTS_TAG);
6292 if (node != NULL) {
6293 node = node->first_child;
6294 while (node) {
6295 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006296 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006297 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6298 status = tmpStatus;
6299 }
6300 node = node->next;
6301 }
6302 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006303 loadGlobalConfig(root, module);
6304
Eric Laurente552edb2014-03-10 17:42:56 -07006305 if (status == NO_ERROR) {
6306 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006307 }
6308}
6309
Eric Laurente0720872014-03-11 09:30:41 -07006310void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006311{
6312 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6313 if (node == NULL) {
6314 return;
6315 }
6316
6317 node = node->first_child;
6318 while (node) {
6319 ALOGV("loadHwModules() loading module %s", node->name);
6320 loadHwModule(node);
6321 node = node->next;
6322 }
6323}
6324
Eric Laurent1f2f2232014-06-02 12:01:23 -07006325void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006326{
6327 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006328
Eric Laurente552edb2014-03-10 17:42:56 -07006329 if (node == NULL) {
6330 return;
6331 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006332 DeviceVector declaredDevices;
6333 if (module != NULL) {
6334 declaredDevices = module->mDeclaredDevices;
6335 }
6336
Eric Laurente552edb2014-03-10 17:42:56 -07006337 node = node->first_child;
6338 while (node) {
6339 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006340 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6341 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006342 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6343 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006344 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006345 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006346 ARRAY_SIZE(sDeviceNameToEnumTable),
6347 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006348 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006349 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006350 } else {
6351 ALOGW("loadGlobalConfig() default device not specified");
6352 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006353 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006354 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006355 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6356 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006357 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006358 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6359 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6360 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006361 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6362 uint32_t major, minor;
6363 sscanf((char *)node->value, "%u.%u", &major, &minor);
6364 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6365 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6366 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006367 }
6368 node = node->next;
6369 }
6370}
6371
Eric Laurente0720872014-03-11 09:30:41 -07006372status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006373{
6374 cnode *root;
6375 char *data;
6376
6377 data = (char *)load_file(path, NULL);
6378 if (data == NULL) {
6379 return -ENODEV;
6380 }
6381 root = config_node("", "");
6382 config_load(root, data);
6383
Eric Laurente552edb2014-03-10 17:42:56 -07006384 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006385 // legacy audio_policy.conf files have one global_configuration section
6386 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006387 config_free(root);
6388 free(root);
6389 free(data);
6390
6391 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6392
6393 return NO_ERROR;
6394}
6395
Eric Laurente0720872014-03-11 09:30:41 -07006396void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006397{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006398 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006399 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006400 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6401 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006402 mAvailableOutputDevices.add(mDefaultOutputDevice);
6403 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006404
6405 module = new HwModule("primary");
6406
Eric Laurent1afeecb2014-05-14 08:52:28 -07006407 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006408 profile->mSamplingRates.add(44100);
6409 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6410 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006411 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006412 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6413 module->mOutputProfiles.add(profile);
6414
Eric Laurent1afeecb2014-05-14 08:52:28 -07006415 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006416 profile->mSamplingRates.add(8000);
6417 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6418 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006419 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006420 module->mInputProfiles.add(profile);
6421
6422 mHwModules.add(module);
6423}
6424
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006425audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6426{
6427 // flags to stream type mapping
6428 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6429 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6430 }
6431 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6432 return AUDIO_STREAM_BLUETOOTH_SCO;
6433 }
6434
6435 // usage to stream type mapping
6436 switch (attr->usage) {
6437 case AUDIO_USAGE_MEDIA:
6438 case AUDIO_USAGE_GAME:
6439 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6440 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6441 return AUDIO_STREAM_MUSIC;
6442 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6443 return AUDIO_STREAM_SYSTEM;
6444 case AUDIO_USAGE_VOICE_COMMUNICATION:
6445 return AUDIO_STREAM_VOICE_CALL;
6446
6447 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6448 return AUDIO_STREAM_DTMF;
6449
6450 case AUDIO_USAGE_ALARM:
6451 return AUDIO_STREAM_ALARM;
6452 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6453 return AUDIO_STREAM_RING;
6454
6455 case AUDIO_USAGE_NOTIFICATION:
6456 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6457 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6458 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6459 case AUDIO_USAGE_NOTIFICATION_EVENT:
6460 return AUDIO_STREAM_NOTIFICATION;
6461
6462 case AUDIO_USAGE_UNKNOWN:
6463 default:
6464 return AUDIO_STREAM_MUSIC;
6465 }
6466}
Eric Laurente552edb2014-03-10 17:42:56 -07006467}; // namespace android