blob: b09300b8d2506f24f2e8b66b978224b92edde42b [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 Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070085 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070090 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050091 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700110 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900111 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112};
113
114const StringToEnum sFlagNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
121};
122
123const StringToEnum sFormatNameToEnumTable[] = {
124 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
128 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
129 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
130 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
131 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700142 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700143 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
144 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
145 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
146 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
147 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700148};
149
150const StringToEnum sOutChannelsNameToEnumTable[] = {
151 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
155 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
156};
157
158const StringToEnum sInChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
161 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
162};
163
Eric Laurent1afeecb2014-05-14 08:52:28 -0700164const StringToEnum sGainModeNameToEnumTable[] = {
165 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
166 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
167 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
168};
169
Eric Laurent3a4311c2014-03-17 12:00:47 -0700170
171uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
172 size_t size,
173 const char *name)
174{
175 for (size_t i = 0; i < size; i++) {
176 if (strcmp(table[i].name, name) == 0) {
177 ALOGV("stringToEnum() found %s", table[i].name);
178 return table[i].value;
179 }
180 }
181 return 0;
182}
183
184const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
185 size_t size,
186 uint32_t value)
187{
188 for (size_t i = 0; i < size; i++) {
189 if (table[i].value == value) {
190 return table[i].name;
191 }
192 }
193 return "";
194}
195
196bool AudioPolicyManager::stringToBool(const char *value)
197{
198 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
199}
200
201
202// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700203// AudioPolicyInterface implementation
204// ----------------------------------------------------------------------------
205
206
Eric Laurente0720872014-03-11 09:30:41 -0700207status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700208 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700209 const char *device_address)
210{
Eric Laurent22226012014-08-01 17:00:54 -0700211 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700212
Eric Laurent22226012014-08-01 17:00:54 -0700213 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
214 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700215
216 // connect/disconnect only 1 device at a time
217 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
218
Eric Laurente552edb2014-03-10 17:42:56 -0700219 // handle output devices
220 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700221 SortedVector <audio_io_handle_t> outputs;
222
Eric Laurent1afeecb2014-05-14 08:52:28 -0700223 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
224 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
226
Eric Laurente552edb2014-03-10 17:42:56 -0700227 // save a copy of the opened output descriptors before any output is opened or closed
228 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
229 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700230 switch (state)
231 {
232 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700233 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700234 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700235 ALOGW("setDeviceConnectionState() device already connected: %x", device);
236 return INVALID_OPERATION;
237 }
238 ALOGV("setDeviceConnectionState() connecting device %x", device);
239
Eric Laurente552edb2014-03-10 17:42:56 -0700240 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700241 index = mAvailableOutputDevices.add(devDesc);
242 if (index >= 0) {
243 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700244 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700245 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
246 "could not find HW module for device %08x", device);
247 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 } else {
249 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700250 }
251
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700252 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
253 mAvailableOutputDevices.remove(devDesc);
254 return INVALID_OPERATION;
255 }
256 // outputs should never be empty here
257 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
258 "checkOutputsForDevice() returned no outputs but status OK");
259 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
260 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700261 break;
262 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700263 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700265 ALOGW("setDeviceConnectionState() device not connected: %x", device);
266 return INVALID_OPERATION;
267 }
268
269 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
270 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700271 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700272
Eric Laurent3a4311c2014-03-17 12:00:47 -0700273 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700274 } break;
275
276 default:
277 ALOGE("setDeviceConnectionState() invalid state: %x", state);
278 return BAD_VALUE;
279 }
280
Eric Laurent3a4311c2014-03-17 12:00:47 -0700281 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
282 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700283 checkA2dpSuspend();
284 checkOutputForAllStrategies();
285 // outputs must be closed after checkOutputForAllStrategies() is executed
286 if (!outputs.isEmpty()) {
287 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700288 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700289 // close unused outputs after device disconnection or direct outputs that have been
290 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700291 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700292 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
293 (desc->mDirectOpenCount == 0))) {
294 closeOutput(outputs[i]);
295 }
296 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700297 // check again after closing A2DP output to reset mA2dpSuspended if needed
298 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
300
301 updateDevicesAndOutputs();
302 for (size_t i = 0; i < mOutputs.size(); i++) {
303 // do not force device change on duplicated output because if device is 0, it will
304 // also force a device 0 for the two outputs it is duplicated to which may override
305 // a valid device selection on those outputs.
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700306 bool force = !mOutputs.valueAt(i)->isDuplicated()
307 && (!deviceDistinguishesOnAddress(device)
308 // always force when disconnecting (a non-duplicated device)
309 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurente552edb2014-03-10 17:42:56 -0700310 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700311 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700312 force, 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700313 }
314
Eric Laurent72aa32f2014-05-30 18:51:48 -0700315 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700316 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700317 } // end if is output device
318
Eric Laurente552edb2014-03-10 17:42:56 -0700319 // handle input devices
320 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700321 SortedVector <audio_io_handle_t> inputs;
322
Eric Laurent1afeecb2014-05-14 08:52:28 -0700323 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
324 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700326 switch (state)
327 {
328 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700329 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700330 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700331 ALOGW("setDeviceConnectionState() device already connected: %d", device);
332 return INVALID_OPERATION;
333 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700334 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700335 if (module == NULL) {
336 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
337 device);
338 return INVALID_OPERATION;
339 }
Eric Laurentd4692962014-05-05 18:13:44 -0700340 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
341 return INVALID_OPERATION;
342 }
343
Eric Laurent3a4311c2014-03-17 12:00:47 -0700344 index = mAvailableInputDevices.add(devDesc);
345 if (index >= 0) {
346 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700347 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 } else {
349 return NO_MEMORY;
350 }
Eric Laurentd4692962014-05-05 18:13:44 -0700351 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700352
353 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700354 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700355 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700356 ALOGW("setDeviceConnectionState() device not connected: %d", device);
357 return INVALID_OPERATION;
358 }
Eric Laurentd4692962014-05-05 18:13:44 -0700359 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700361 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700362
363 default:
364 ALOGE("setDeviceConnectionState() invalid state: %x", state);
365 return BAD_VALUE;
366 }
367
Eric Laurentd4692962014-05-05 18:13:44 -0700368 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentb52c1522014-05-20 11:27:36 -0700370 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700371 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700372 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700373
374 ALOGW("setDeviceConnectionState() invalid device: %x", device);
375 return BAD_VALUE;
376}
377
Eric Laurente0720872014-03-11 09:30:41 -0700378audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700379 const char *device_address)
380{
Eric Laurent3b73df72014-03-11 09:06:29 -0700381 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700382 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700383 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700384 ssize_t index;
385 DeviceVector *deviceVector;
386
Eric Laurente552edb2014-03-10 17:42:56 -0700387 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700389 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700390 deviceVector = &mAvailableInputDevices;
391 } else {
392 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
393 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700394 }
395
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 index = deviceVector->indexOf(devDesc);
397 if (index >= 0) {
398 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
399 } else {
400 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
401 }
Eric Laurente552edb2014-03-10 17:42:56 -0700402}
403
Eric Laurente0720872014-03-11 09:30:41 -0700404void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700405{
406 ALOGV("setPhoneState() state %d", state);
407 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700408 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700409 ALOGW("setPhoneState() invalid state %d", state);
410 return;
411 }
412
413 if (state == mPhoneState ) {
414 ALOGW("setPhoneState() setting same state %d", state);
415 return;
416 }
417
418 // if leaving call state, handle special case of active streams
419 // pertaining to sonification strategy see handleIncallSonification()
420 if (isInCall()) {
421 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700422 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
423 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700424 }
425 }
426
427 // store previous phone state for management of sonification strategy below
428 int oldState = mPhoneState;
429 mPhoneState = state;
430 bool force = false;
431
432 // are we entering or starting a call
433 if (!isStateInCall(oldState) && isStateInCall(state)) {
434 ALOGV(" Entering call in setPhoneState()");
435 // force routing command to audio hardware when starting a call
436 // even if no device change is needed
437 force = true;
438 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
439 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
440 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
441 }
442 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
443 ALOGV(" Exiting call in setPhoneState()");
444 // force routing command to audio hardware when exiting a call
445 // even if no device change is needed
446 force = true;
447 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
448 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
449 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
450 }
451 } else if (isStateInCall(state) && (state != oldState)) {
452 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
453 // force routing command to audio hardware when switching between telephony and VoIP
454 // even if no device change is needed
455 force = true;
456 }
457
458 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700459 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700460 checkA2dpSuspend();
461 checkOutputForAllStrategies();
462 updateDevicesAndOutputs();
463
Eric Laurent1f2f2232014-06-02 12:01:23 -0700464 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700465
466 // force routing command to audio hardware when ending call
467 // even if no device change is needed
468 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
469 newDevice = hwOutputDesc->device();
470 }
471
472 int delayMs = 0;
473 if (isStateInCall(state)) {
474 nsecs_t sysTime = systemTime();
475 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700476 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700477 // mute media and sonification strategies and delay device switch by the largest
478 // latency of any output where either strategy is active.
479 // This avoid sending the ring tone or music tail into the earpiece or headset.
480 if ((desc->isStrategyActive(STRATEGY_MEDIA,
481 SONIFICATION_HEADSET_MUSIC_DELAY,
482 sysTime) ||
483 desc->isStrategyActive(STRATEGY_SONIFICATION,
484 SONIFICATION_HEADSET_MUSIC_DELAY,
485 sysTime)) &&
486 (delayMs < (int)desc->mLatency*2)) {
487 delayMs = desc->mLatency*2;
488 }
489 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
490 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
491 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
492 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
493 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
494 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
495 }
496 }
497
498 // change routing is necessary
499 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
500
501 // if entering in call state, handle special case of active streams
502 // pertaining to sonification strategy see handleIncallSonification()
503 if (isStateInCall(state)) {
504 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700505 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
506 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700507 }
508 }
509
510 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700511 if (state == AUDIO_MODE_RINGTONE &&
512 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700513 mLimitRingtoneVolume = true;
514 } else {
515 mLimitRingtoneVolume = false;
516 }
517}
518
Eric Laurente0720872014-03-11 09:30:41 -0700519void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700520 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700521{
522 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
523
524 bool forceVolumeReeval = false;
525 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700526 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
527 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
528 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700529 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
530 return;
531 }
532 forceVolumeReeval = true;
533 mForceUse[usage] = config;
534 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700535 case AUDIO_POLICY_FORCE_FOR_MEDIA:
536 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
537 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
538 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
539 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900540 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700541 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
542 return;
543 }
544 mForceUse[usage] = config;
545 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700546 case AUDIO_POLICY_FORCE_FOR_RECORD:
547 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
548 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700549 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
550 return;
551 }
552 mForceUse[usage] = config;
553 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700554 case AUDIO_POLICY_FORCE_FOR_DOCK:
555 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
556 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
557 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
558 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
559 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700560 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
561 }
562 forceVolumeReeval = true;
563 mForceUse[usage] = config;
564 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700565 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
566 if (config != AUDIO_POLICY_FORCE_NONE &&
567 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700568 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
569 }
570 forceVolumeReeval = true;
571 mForceUse[usage] = config;
572 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900573 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
574 if (config != AUDIO_POLICY_FORCE_NONE &&
575 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
576 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
577 }
578 mForceUse[usage] = config;
579 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700580 default:
581 ALOGW("setForceUse() invalid usage %d", usage);
582 break;
583 }
584
585 // check for device and output changes triggered by new force usage
586 checkA2dpSuspend();
587 checkOutputForAllStrategies();
588 updateDevicesAndOutputs();
589 for (size_t i = 0; i < mOutputs.size(); i++) {
590 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700591 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700592 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
593 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
594 applyStreamVolumes(output, newDevice, 0, true);
595 }
596 }
597
598 audio_io_handle_t activeInput = getActiveInput();
599 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700600 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700601 }
602
603}
604
Eric Laurente0720872014-03-11 09:30:41 -0700605audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700606{
607 return mForceUse[usage];
608}
609
Eric Laurente0720872014-03-11 09:30:41 -0700610void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700611{
612 ALOGV("setSystemProperty() property %s, value %s", property, value);
613}
614
615// Find a direct output profile compatible with the parameters passed, even if the input flags do
616// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700617sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700618 audio_devices_t device,
619 uint32_t samplingRate,
620 audio_format_t format,
621 audio_channel_mask_t channelMask,
622 audio_output_flags_t flags)
623{
624 for (size_t i = 0; i < mHwModules.size(); i++) {
625 if (mHwModules[i]->mHandle == 0) {
626 continue;
627 }
628 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700629 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700630 bool found = profile->isCompatibleProfile(device, samplingRate,
631 NULL /*updatedSamplingRate*/, format, channelMask,
632 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
633 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700634 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
635 return profile;
636 }
Eric Laurente552edb2014-03-10 17:42:56 -0700637 }
638 }
639 return 0;
640}
641
Eric Laurente0720872014-03-11 09:30:41 -0700642audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700643 uint32_t samplingRate,
644 audio_format_t format,
645 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700646 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700647 const audio_offload_info_t *offloadInfo)
648{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700649
Eric Laurent3b73df72014-03-11 09:06:29 -0700650 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700651 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
652 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
653 device, stream, samplingRate, format, channelMask, flags);
654
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700655 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
656 offloadInfo);
657}
658
659audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
660 uint32_t samplingRate,
661 audio_format_t format,
662 audio_channel_mask_t channelMask,
663 audio_output_flags_t flags,
664 const audio_offload_info_t *offloadInfo)
665{
666 if (attr == NULL) {
667 ALOGE("getOutputForAttr() called with NULL audio attributes");
668 return 0;
669 }
670 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
671 attr->usage, attr->content_type, attr->tags);
672
673 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
674 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
675 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
676 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
677 device, samplingRate, format, channelMask, flags);
678
679 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
680 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
681 offloadInfo);
682}
683
684audio_io_handle_t AudioPolicyManager::getOutputForDevice(
685 audio_devices_t device,
686 audio_stream_type_t stream,
687 uint32_t samplingRate,
688 audio_format_t format,
689 audio_channel_mask_t channelMask,
690 audio_output_flags_t flags,
691 const audio_offload_info_t *offloadInfo)
692{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700693 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700694 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700695 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700696
Eric Laurente552edb2014-03-10 17:42:56 -0700697#ifdef AUDIO_POLICY_TEST
698 if (mCurOutput != 0) {
699 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
700 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
701
702 if (mTestOutputs[mCurOutput] == 0) {
703 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700704 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700705 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700706 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700707 outputDesc->mFlags =
708 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700709 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700710 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
711 config.sample_rate = mTestSamplingRate;
712 config.channel_mask = mTestChannels;
713 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700714 if (offloadInfo != NULL) {
715 config.offload_info = *offloadInfo;
716 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700717 status = mpClientInterface->openOutput(0,
718 &mTestOutputs[mCurOutput],
719 &config,
720 &outputDesc->mDevice,
721 String8(""),
722 &outputDesc->mLatency,
723 outputDesc->mFlags);
724 if (status == NO_ERROR) {
725 outputDesc->mSamplingRate = config.sample_rate;
726 outputDesc->mFormat = config.format;
727 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700728 AudioParameter outputCmd = AudioParameter();
729 outputCmd.addInt(String8("set_id"),mCurOutput);
730 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
731 addOutput(mTestOutputs[mCurOutput], outputDesc);
732 }
733 }
734 return mTestOutputs[mCurOutput];
735 }
736#endif //AUDIO_POLICY_TEST
737
738 // open a direct output if required by specified parameters
739 //force direct flag if offload flag is set: offloading implies a direct output stream
740 // and all common behaviors are driven by checking only the direct flag
741 // this should normally be set appropriately in the policy configuration file
742 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700743 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700744 }
745
746 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
747 // creating an offloaded track and tearing it down immediately after start when audioflinger
748 // detects there is an active non offloadable effect.
749 // FIXME: We should check the audio session here but we do not have it in this context.
750 // This may prevent offloading in rare situations where effects are left active by apps
751 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700752 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700753 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
754 !isNonOffloadableEffectEnabled()) {
755 profile = getProfileForDirectOutput(device,
756 samplingRate,
757 format,
758 channelMask,
759 (audio_output_flags_t)flags);
760 }
761
Eric Laurent1c333e22014-05-20 10:48:17 -0700762 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700763 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700764
765 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700766 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700767 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
768 outputDesc = desc;
769 // reuse direct output if currently open and configured with same parameters
770 if ((samplingRate == outputDesc->mSamplingRate) &&
771 (format == outputDesc->mFormat) &&
772 (channelMask == outputDesc->mChannelMask)) {
773 outputDesc->mDirectOpenCount++;
774 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
775 return mOutputs.keyAt(i);
776 }
777 }
778 }
779 // close direct output if currently open and configured with different parameters
780 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700781 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700782 }
783 outputDesc = new AudioOutputDescriptor(profile);
784 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700785 outputDesc->mLatency = 0;
786 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700787 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
788 config.sample_rate = samplingRate;
789 config.channel_mask = channelMask;
790 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700791 if (offloadInfo != NULL) {
792 config.offload_info = *offloadInfo;
793 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700794 status = mpClientInterface->openOutput(profile->mModule->mHandle,
795 &output,
796 &config,
797 &outputDesc->mDevice,
798 String8(""),
799 &outputDesc->mLatency,
800 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700801
802 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700803 if (status != NO_ERROR ||
804 (samplingRate != 0 && samplingRate != config.sample_rate) ||
805 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
806 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700807 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
808 "format %d %d, channelMask %04x %04x", output, samplingRate,
809 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
810 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700811 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700812 mpClientInterface->closeOutput(output);
813 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700814 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700815 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700816 outputDesc->mSamplingRate = config.sample_rate;
817 outputDesc->mChannelMask = config.channel_mask;
818 outputDesc->mFormat = config.format;
819 outputDesc->mRefCount[stream] = 0;
820 outputDesc->mStopTime[stream] = 0;
821 outputDesc->mDirectOpenCount = 1;
822
Eric Laurente552edb2014-03-10 17:42:56 -0700823 audio_io_handle_t srcOutput = getOutputForEffect();
824 addOutput(output, outputDesc);
825 audio_io_handle_t dstOutput = getOutputForEffect();
826 if (dstOutput == output) {
827 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
828 }
829 mPreviousOutputs = mOutputs;
830 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700831 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700832 return output;
833 }
834
835 // ignoring channel mask due to downmix capability in mixer
836
837 // open a non direct output
838
839 // for non direct outputs, only PCM is supported
840 if (audio_is_linear_pcm(format)) {
841 // get which output is suitable for the specified stream. The actual
842 // routing change will happen when startOutput() will be called
843 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
844
845 output = selectOutput(outputs, flags);
846 }
847 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
848 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
849
850 ALOGV("getOutput() returns output %d", output);
851
852 return output;
853}
854
Eric Laurente0720872014-03-11 09:30:41 -0700855audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700856 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700857{
858 // select one output among several that provide a path to a particular device or set of
859 // devices (the list was previously build by getOutputsForDevice()).
860 // The priority is as follows:
861 // 1: the output with the highest number of requested policy flags
862 // 2: the primary output
863 // 3: the first output in the list
864
865 if (outputs.size() == 0) {
866 return 0;
867 }
868 if (outputs.size() == 1) {
869 return outputs[0];
870 }
871
872 int maxCommonFlags = 0;
873 audio_io_handle_t outputFlags = 0;
874 audio_io_handle_t outputPrimary = 0;
875
876 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700877 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700878 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700879 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700880 if (commonFlags > maxCommonFlags) {
881 outputFlags = outputs[i];
882 maxCommonFlags = commonFlags;
883 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
884 }
885 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
886 outputPrimary = outputs[i];
887 }
888 }
889 }
890
891 if (outputFlags != 0) {
892 return outputFlags;
893 }
894 if (outputPrimary != 0) {
895 return outputPrimary;
896 }
897
898 return outputs[0];
899}
900
Eric Laurente0720872014-03-11 09:30:41 -0700901status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700902 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700903 int session)
904{
905 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
906 ssize_t index = mOutputs.indexOfKey(output);
907 if (index < 0) {
908 ALOGW("startOutput() unknown output %d", output);
909 return BAD_VALUE;
910 }
911
Eric Laurent1f2f2232014-06-02 12:01:23 -0700912 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700913
914 // increment usage count for this stream on the requested output:
915 // NOTE that the usage count is the same for duplicated output and hardware output which is
916 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
917 outputDesc->changeRefCount(stream, 1);
918
919 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700920 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700921 routing_strategy strategy = getStrategy(stream);
922 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
923 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
924 uint32_t waitMs = 0;
925 bool force = false;
926 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700927 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700928 if (desc != outputDesc) {
929 // force a device change if any other output is managed by the same hw
930 // module and has a current device selection that differs from selected device.
931 // In this case, the audio HAL must receive the new device selection so that it can
932 // change the device currently selected by the other active output.
933 if (outputDesc->sharesHwModuleWith(desc) &&
934 desc->device() != newDevice) {
935 force = true;
936 }
937 // wait for audio on other active outputs to be presented when starting
938 // a notification so that audio focus effect can propagate.
939 uint32_t latency = desc->latency();
940 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
941 waitMs = latency;
942 }
943 }
944 }
945 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
946
947 // handle special case for sonification while in call
948 if (isInCall()) {
949 handleIncallSonification(stream, true, false);
950 }
951
952 // apply volume rules for current stream and device if necessary
953 checkAndSetVolume(stream,
954 mStreams[stream].getVolumeIndex(newDevice),
955 output,
956 newDevice);
957
958 // update the outputs if starting an output with a stream that can affect notification
959 // routing
960 handleNotificationRoutingForStream(stream);
961 if (waitMs > muteWaitMs) {
962 usleep((waitMs - muteWaitMs) * 2 * 1000);
963 }
964 }
965 return NO_ERROR;
966}
967
968
Eric Laurente0720872014-03-11 09:30:41 -0700969status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700970 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700971 int session)
972{
973 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
974 ssize_t index = mOutputs.indexOfKey(output);
975 if (index < 0) {
976 ALOGW("stopOutput() unknown output %d", output);
977 return BAD_VALUE;
978 }
979
Eric Laurent1f2f2232014-06-02 12:01:23 -0700980 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700981
982 // handle special case for sonification while in call
983 if (isInCall()) {
984 handleIncallSonification(stream, false, false);
985 }
986
987 if (outputDesc->mRefCount[stream] > 0) {
988 // decrement usage count of this stream on the output
989 outputDesc->changeRefCount(stream, -1);
990 // store time at which the stream was stopped - see isStreamActive()
991 if (outputDesc->mRefCount[stream] == 0) {
992 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700993 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700994 // delay the device switch by twice the latency because stopOutput() is executed when
995 // the track stop() command is received and at that time the audio track buffer can
996 // still contain data that needs to be drained. The latency only covers the audio HAL
997 // and kernel buffers. Also the latency does not always include additional delay in the
998 // audio path (audio DSP, CODEC ...)
999 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1000
1001 // force restoring the device selection on other active outputs if it differs from the
1002 // one being selected for this output
1003 for (size_t i = 0; i < mOutputs.size(); i++) {
1004 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001005 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001006 if (curOutput != output &&
1007 desc->isActive() &&
1008 outputDesc->sharesHwModuleWith(desc) &&
1009 (newDevice != desc->device())) {
1010 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001011 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001012 true,
1013 outputDesc->mLatency*2);
1014 }
1015 }
1016 // update the outputs if stopping one with a stream that can affect notification routing
1017 handleNotificationRoutingForStream(stream);
1018 }
1019 return NO_ERROR;
1020 } else {
1021 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1022 return INVALID_OPERATION;
1023 }
1024}
1025
Eric Laurente0720872014-03-11 09:30:41 -07001026void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001027{
1028 ALOGV("releaseOutput() %d", output);
1029 ssize_t index = mOutputs.indexOfKey(output);
1030 if (index < 0) {
1031 ALOGW("releaseOutput() releasing unknown output %d", output);
1032 return;
1033 }
1034
1035#ifdef AUDIO_POLICY_TEST
1036 int testIndex = testOutputIndex(output);
1037 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001038 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001039 if (outputDesc->isActive()) {
1040 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001041 mOutputs.removeItem(output);
1042 mTestOutputs[testIndex] = 0;
1043 }
1044 return;
1045 }
1046#endif //AUDIO_POLICY_TEST
1047
Eric Laurent1f2f2232014-06-02 12:01:23 -07001048 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001049 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001050 if (desc->mDirectOpenCount <= 0) {
1051 ALOGW("releaseOutput() invalid open count %d for output %d",
1052 desc->mDirectOpenCount, output);
1053 return;
1054 }
1055 if (--desc->mDirectOpenCount == 0) {
1056 closeOutput(output);
1057 // If effects where present on the output, audioflinger moved them to the primary
1058 // output by default: move them back to the appropriate output.
1059 audio_io_handle_t dstOutput = getOutputForEffect();
1060 if (dstOutput != mPrimaryOutput) {
1061 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1062 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001063 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001064 }
1065 }
1066}
1067
1068
Eric Laurente0720872014-03-11 09:30:41 -07001069audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001070 uint32_t samplingRate,
1071 audio_format_t format,
1072 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001073 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001074 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001075{
Eric Laurent4dc68062014-07-28 17:26:49 -07001076 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001077 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001078 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001079
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001080 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001081
1082 if (device == AUDIO_DEVICE_NONE) {
1083 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001084 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
1086
1087 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001088 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001089 case AUDIO_SOURCE_VOICE_UPLINK:
1090 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1091 break;
1092 case AUDIO_SOURCE_VOICE_DOWNLINK:
1093 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1094 break;
1095 case AUDIO_SOURCE_VOICE_CALL:
1096 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1097 break;
1098 default:
1099 break;
1100 }
1101
Eric Laurent1c333e22014-05-20 10:48:17 -07001102 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001103 samplingRate,
1104 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001105 channelMask,
1106 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001107 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001108 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1109 "channelMask 0x%X, flags %#x",
1110 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001111 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001112 }
1113
1114 if (profile->mModule->mHandle == 0) {
1115 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001116 return AUDIO_IO_HANDLE_NONE;
1117 }
1118
1119 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1120 config.sample_rate = samplingRate;
1121 config.channel_mask = channelMask;
1122 config.format = format;
1123 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001124
1125 bool isSoundTrigger = false;
1126 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1127 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1128 if (index >= 0) {
1129 input = mSoundTriggerSessions.valueFor(session);
1130 isSoundTrigger = true;
1131 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1132 }
1133 }
1134
Eric Laurentcf2c0212014-07-25 16:20:43 -07001135 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1136 &input,
1137 &config,
1138 &device,
1139 String8(""),
1140 inputSource,
1141 flags);
1142
1143 // only accept input with the exact requested set of parameters
1144 if (status != NO_ERROR ||
1145 (samplingRate != config.sample_rate) ||
1146 (format != config.format) ||
1147 (channelMask != config.channel_mask)) {
1148 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1149 samplingRate, format, channelMask);
1150 if (input != AUDIO_IO_HANDLE_NONE) {
1151 mpClientInterface->closeInput(input);
1152 }
1153 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001154 }
1155
Eric Laurent1f2f2232014-06-02 12:01:23 -07001156 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001157 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001158 inputDesc->mRefCount = 0;
1159 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001160 inputDesc->mSamplingRate = samplingRate;
1161 inputDesc->mFormat = format;
1162 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001163 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001164 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001165 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001166
Eric Laurentd4692962014-05-05 18:13:44 -07001167 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001168 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001169 return input;
1170}
1171
Eric Laurent4dc68062014-07-28 17:26:49 -07001172status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1173 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001174{
1175 ALOGV("startInput() input %d", input);
1176 ssize_t index = mInputs.indexOfKey(input);
1177 if (index < 0) {
1178 ALOGW("startInput() unknown input %d", input);
1179 return BAD_VALUE;
1180 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001181 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001182
Eric Laurent4dc68062014-07-28 17:26:49 -07001183 index = inputDesc->mSessions.indexOf(session);
1184 if (index < 0) {
1185 ALOGW("startInput() unknown session %d on input %d", session, input);
1186 return BAD_VALUE;
1187 }
1188
Glenn Kasten74a8e252014-07-24 14:09:55 -07001189 // virtual input devices are compatible with other input devices
1190 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1191
1192 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001193 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001194 if (activeInput != 0 && activeInput != input) {
1195
1196 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1197 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001198 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001199 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001200 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001201 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1202 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001203 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001204 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001205 return INVALID_OPERATION;
1206 }
1207 }
1208 }
1209
Glenn Kasten74a8e252014-07-24 14:09:55 -07001210 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001211 if (activeInputsCount() == 0) {
1212 SoundTrigger::setCaptureState(true);
1213 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001214 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001215
Glenn Kasten74a8e252014-07-24 14:09:55 -07001216 // Automatically enable the remote submix output when input is started.
1217 // For remote submix (a virtual device), we open only one input per capture request.
1218 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1219 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1220 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1221 }
Eric Laurente552edb2014-03-10 17:42:56 -07001222 }
1223
Eric Laurente552edb2014-03-10 17:42:56 -07001224 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1225
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001226 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001227 return NO_ERROR;
1228}
1229
Eric Laurent4dc68062014-07-28 17:26:49 -07001230status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1231 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001232{
1233 ALOGV("stopInput() input %d", input);
1234 ssize_t index = mInputs.indexOfKey(input);
1235 if (index < 0) {
1236 ALOGW("stopInput() unknown input %d", input);
1237 return BAD_VALUE;
1238 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001239 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001240
Eric Laurent4dc68062014-07-28 17:26:49 -07001241 index = inputDesc->mSessions.indexOf(session);
1242 if (index < 0) {
1243 ALOGW("stopInput() unknown session %d on input %d", session, input);
1244 return BAD_VALUE;
1245 }
1246
Eric Laurente552edb2014-03-10 17:42:56 -07001247 if (inputDesc->mRefCount == 0) {
1248 ALOGW("stopInput() input %d already stopped", input);
1249 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001250 }
1251
1252 inputDesc->mRefCount--;
1253 if (inputDesc->mRefCount == 0) {
1254
Eric Laurente552edb2014-03-10 17:42:56 -07001255 // automatically disable the remote submix output when input is stopped
1256 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1257 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001258 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001259 }
1260
Eric Laurent1c333e22014-05-20 10:48:17 -07001261 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001262
1263 if (activeInputsCount() == 0) {
1264 SoundTrigger::setCaptureState(false);
1265 }
Eric Laurente552edb2014-03-10 17:42:56 -07001266 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001267 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001268}
1269
Eric Laurent4dc68062014-07-28 17:26:49 -07001270void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1271 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001272{
1273 ALOGV("releaseInput() %d", input);
1274 ssize_t index = mInputs.indexOfKey(input);
1275 if (index < 0) {
1276 ALOGW("releaseInput() releasing unknown input %d", input);
1277 return;
1278 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001279 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1280 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001281
1282 index = inputDesc->mSessions.indexOf(session);
1283 if (index < 0) {
1284 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1285 return;
1286 }
1287 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001288 if (inputDesc->mOpenRefCount == 0) {
1289 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1290 return;
1291 }
1292 inputDesc->mOpenRefCount--;
1293 if (inputDesc->mOpenRefCount > 0) {
1294 ALOGV("releaseInput() exit > 0");
1295 return;
1296 }
1297
Eric Laurente552edb2014-03-10 17:42:56 -07001298 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001299 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001300 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001301 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001302 ALOGV("releaseInput() exit");
1303}
1304
Eric Laurentd4692962014-05-05 18:13:44 -07001305void AudioPolicyManager::closeAllInputs() {
1306 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1307 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1308 }
1309 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001310 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001311}
1312
Eric Laurente0720872014-03-11 09:30:41 -07001313void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001314 int indexMin,
1315 int indexMax)
1316{
1317 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1318 if (indexMin < 0 || indexMin >= indexMax) {
1319 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1320 return;
1321 }
1322 mStreams[stream].mIndexMin = indexMin;
1323 mStreams[stream].mIndexMax = indexMax;
1324}
1325
Eric Laurente0720872014-03-11 09:30:41 -07001326status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001327 int index,
1328 audio_devices_t device)
1329{
1330
1331 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1332 return BAD_VALUE;
1333 }
1334 if (!audio_is_output_device(device)) {
1335 return BAD_VALUE;
1336 }
1337
1338 // Force max volume if stream cannot be muted
1339 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1340
1341 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1342 stream, device, index);
1343
1344 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1345 // clear all device specific values
1346 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1347 mStreams[stream].mIndexCur.clear();
1348 }
1349 mStreams[stream].mIndexCur.add(device, index);
1350
1351 // compute and apply stream volume on all outputs according to connected device
1352 status_t status = NO_ERROR;
1353 for (size_t i = 0; i < mOutputs.size(); i++) {
1354 audio_devices_t curDevice =
1355 getDeviceForVolume(mOutputs.valueAt(i)->device());
1356 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1357 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1358 if (volStatus != NO_ERROR) {
1359 status = volStatus;
1360 }
1361 }
1362 }
1363 return status;
1364}
1365
Eric Laurente0720872014-03-11 09:30:41 -07001366status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001367 int *index,
1368 audio_devices_t device)
1369{
1370 if (index == NULL) {
1371 return BAD_VALUE;
1372 }
1373 if (!audio_is_output_device(device)) {
1374 return BAD_VALUE;
1375 }
1376 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1377 // the strategy the stream belongs to.
1378 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1379 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1380 }
1381 device = getDeviceForVolume(device);
1382
1383 *index = mStreams[stream].getVolumeIndex(device);
1384 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1385 return NO_ERROR;
1386}
1387
Eric Laurente0720872014-03-11 09:30:41 -07001388audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001389 const SortedVector<audio_io_handle_t>& outputs)
1390{
1391 // select one output among several suitable for global effects.
1392 // The priority is as follows:
1393 // 1: An offloaded output. If the effect ends up not being offloadable,
1394 // AudioFlinger will invalidate the track and the offloaded output
1395 // will be closed causing the effect to be moved to a PCM output.
1396 // 2: A deep buffer output
1397 // 3: the first output in the list
1398
1399 if (outputs.size() == 0) {
1400 return 0;
1401 }
1402
1403 audio_io_handle_t outputOffloaded = 0;
1404 audio_io_handle_t outputDeepBuffer = 0;
1405
1406 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001407 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001408 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001409 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1410 outputOffloaded = outputs[i];
1411 }
1412 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1413 outputDeepBuffer = outputs[i];
1414 }
1415 }
1416
1417 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1418 outputOffloaded, outputDeepBuffer);
1419 if (outputOffloaded != 0) {
1420 return outputOffloaded;
1421 }
1422 if (outputDeepBuffer != 0) {
1423 return outputDeepBuffer;
1424 }
1425
1426 return outputs[0];
1427}
1428
Eric Laurente0720872014-03-11 09:30:41 -07001429audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001430{
1431 // apply simple rule where global effects are attached to the same output as MUSIC streams
1432
Eric Laurent3b73df72014-03-11 09:06:29 -07001433 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001434 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1435 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1436
1437 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1438 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1439 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1440
1441 return output;
1442}
1443
Eric Laurente0720872014-03-11 09:30:41 -07001444status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001445 audio_io_handle_t io,
1446 uint32_t strategy,
1447 int session,
1448 int id)
1449{
1450 ssize_t index = mOutputs.indexOfKey(io);
1451 if (index < 0) {
1452 index = mInputs.indexOfKey(io);
1453 if (index < 0) {
1454 ALOGW("registerEffect() unknown io %d", io);
1455 return INVALID_OPERATION;
1456 }
1457 }
1458
1459 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1460 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1461 desc->name, desc->memoryUsage);
1462 return INVALID_OPERATION;
1463 }
1464 mTotalEffectsMemory += desc->memoryUsage;
1465 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1466 desc->name, io, strategy, session, id);
1467 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1468
Eric Laurent1f2f2232014-06-02 12:01:23 -07001469 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1470 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1471 effectDesc->mIo = io;
1472 effectDesc->mStrategy = (routing_strategy)strategy;
1473 effectDesc->mSession = session;
1474 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001475
Eric Laurent1f2f2232014-06-02 12:01:23 -07001476 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001477
1478 return NO_ERROR;
1479}
1480
Eric Laurente0720872014-03-11 09:30:41 -07001481status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001482{
1483 ssize_t index = mEffects.indexOfKey(id);
1484 if (index < 0) {
1485 ALOGW("unregisterEffect() unknown effect ID %d", id);
1486 return INVALID_OPERATION;
1487 }
1488
Eric Laurent1f2f2232014-06-02 12:01:23 -07001489 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001490
Eric Laurent1f2f2232014-06-02 12:01:23 -07001491 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001492
Eric Laurent1f2f2232014-06-02 12:01:23 -07001493 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001494 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001495 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1496 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001497 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001498 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001499 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001500 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001501
1502 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001503
1504 return NO_ERROR;
1505}
1506
Eric Laurente0720872014-03-11 09:30:41 -07001507status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001508{
1509 ssize_t index = mEffects.indexOfKey(id);
1510 if (index < 0) {
1511 ALOGW("unregisterEffect() unknown effect ID %d", id);
1512 return INVALID_OPERATION;
1513 }
1514
1515 return setEffectEnabled(mEffects.valueAt(index), enabled);
1516}
1517
Eric Laurent1f2f2232014-06-02 12:01:23 -07001518status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001519{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001520 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001521 ALOGV("setEffectEnabled(%s) effect already %s",
1522 enabled?"true":"false", enabled?"enabled":"disabled");
1523 return INVALID_OPERATION;
1524 }
1525
1526 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001527 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001528 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001529 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001530 return INVALID_OPERATION;
1531 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001532 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001533 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1534 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001535 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001536 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001537 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1538 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001539 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001540 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001541 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1542 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001543 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001544 return NO_ERROR;
1545}
1546
Eric Laurente0720872014-03-11 09:30:41 -07001547bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001548{
1549 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001550 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1551 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1552 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001553 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001554 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001555 return true;
1556 }
1557 }
1558 return false;
1559}
1560
Eric Laurente0720872014-03-11 09:30:41 -07001561bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001562{
1563 nsecs_t sysTime = systemTime();
1564 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001565 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001566 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001567 return true;
1568 }
1569 }
1570 return false;
1571}
1572
Eric Laurente0720872014-03-11 09:30:41 -07001573bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001574 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001575{
1576 nsecs_t sysTime = systemTime();
1577 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001578 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001579 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001580 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001581 return true;
1582 }
1583 }
1584 return false;
1585}
1586
Eric Laurente0720872014-03-11 09:30:41 -07001587bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001588{
1589 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001590 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001591 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001592 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001593 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1594 && (inputDescriptor->mRefCount > 0)) {
1595 return true;
1596 }
1597 }
1598 return false;
1599}
1600
1601
Eric Laurente0720872014-03-11 09:30:41 -07001602status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001603{
1604 const size_t SIZE = 256;
1605 char buffer[SIZE];
1606 String8 result;
1607
1608 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1609 result.append(buffer);
1610
1611 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1612 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001613 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1614 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001615 snprintf(buffer, SIZE, " Force use for communications %d\n",
1616 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001617 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001618 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001619 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001620 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001621 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001622 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001623 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001624 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001625 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001626 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1627 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1628 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001629
Eric Laurent3a4311c2014-03-17 12:00:47 -07001630 snprintf(buffer, SIZE, " Available output devices:\n");
1631 result.append(buffer);
1632 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001633 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001634 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001635 }
1636 snprintf(buffer, SIZE, "\n Available input devices:\n");
1637 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001638 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001639 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001640 }
Eric Laurente552edb2014-03-10 17:42:56 -07001641
1642 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1643 write(fd, buffer, strlen(buffer));
1644 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001645 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001646 write(fd, buffer, strlen(buffer));
1647 mHwModules[i]->dump(fd);
1648 }
1649
1650 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1651 write(fd, buffer, strlen(buffer));
1652 for (size_t i = 0; i < mOutputs.size(); i++) {
1653 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1654 write(fd, buffer, strlen(buffer));
1655 mOutputs.valueAt(i)->dump(fd);
1656 }
1657
1658 snprintf(buffer, SIZE, "\nInputs dump:\n");
1659 write(fd, buffer, strlen(buffer));
1660 for (size_t i = 0; i < mInputs.size(); i++) {
1661 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1662 write(fd, buffer, strlen(buffer));
1663 mInputs.valueAt(i)->dump(fd);
1664 }
1665
1666 snprintf(buffer, SIZE, "\nStreams dump:\n");
1667 write(fd, buffer, strlen(buffer));
1668 snprintf(buffer, SIZE,
1669 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1670 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001671 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001672 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001673 write(fd, buffer, strlen(buffer));
1674 mStreams[i].dump(fd);
1675 }
1676
1677 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1678 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1679 write(fd, buffer, strlen(buffer));
1680
1681 snprintf(buffer, SIZE, "Registered effects:\n");
1682 write(fd, buffer, strlen(buffer));
1683 for (size_t i = 0; i < mEffects.size(); i++) {
1684 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1685 write(fd, buffer, strlen(buffer));
1686 mEffects.valueAt(i)->dump(fd);
1687 }
1688
1689
1690 return NO_ERROR;
1691}
1692
1693// This function checks for the parameters which can be offloaded.
1694// This can be enhanced depending on the capability of the DSP and policy
1695// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001696bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001697{
1698 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001699 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001700 offloadInfo.sample_rate, offloadInfo.channel_mask,
1701 offloadInfo.format,
1702 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1703 offloadInfo.has_video);
1704
1705 // Check if offload has been disabled
1706 char propValue[PROPERTY_VALUE_MAX];
1707 if (property_get("audio.offload.disable", propValue, "0")) {
1708 if (atoi(propValue) != 0) {
1709 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1710 return false;
1711 }
1712 }
1713
1714 // Check if stream type is music, then only allow offload as of now.
1715 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1716 {
1717 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1718 return false;
1719 }
1720
1721 //TODO: enable audio offloading with video when ready
1722 if (offloadInfo.has_video)
1723 {
1724 ALOGV("isOffloadSupported: has_video == true, returning false");
1725 return false;
1726 }
1727
1728 //If duration is less than minimum value defined in property, return false
1729 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1730 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1731 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1732 return false;
1733 }
1734 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1735 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1736 return false;
1737 }
1738
1739 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1740 // creating an offloaded track and tearing it down immediately after start when audioflinger
1741 // detects there is an active non offloadable effect.
1742 // FIXME: We should check the audio session here but we do not have it in this context.
1743 // This may prevent offloading in rare situations where effects are left active by apps
1744 // in the background.
1745 if (isNonOffloadableEffectEnabled()) {
1746 return false;
1747 }
1748
1749 // See if there is a profile to support this.
1750 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001751 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001752 offloadInfo.sample_rate,
1753 offloadInfo.format,
1754 offloadInfo.channel_mask,
1755 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001756 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1757 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001758}
1759
Eric Laurent6a94d692014-05-20 11:18:06 -07001760status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1761 audio_port_type_t type,
1762 unsigned int *num_ports,
1763 struct audio_port *ports,
1764 unsigned int *generation)
1765{
1766 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1767 generation == NULL) {
1768 return BAD_VALUE;
1769 }
1770 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1771 if (ports == NULL) {
1772 *num_ports = 0;
1773 }
1774
1775 size_t portsWritten = 0;
1776 size_t portsMax = *num_ports;
1777 *num_ports = 0;
1778 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1779 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1780 for (size_t i = 0;
1781 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1782 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1783 }
1784 *num_ports += mAvailableOutputDevices.size();
1785 }
1786 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1787 for (size_t i = 0;
1788 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1789 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1790 }
1791 *num_ports += mAvailableInputDevices.size();
1792 }
1793 }
1794 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1795 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1796 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1797 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1798 }
1799 *num_ports += mInputs.size();
1800 }
1801 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001802 size_t numOutputs = 0;
1803 for (size_t i = 0; i < mOutputs.size(); i++) {
1804 if (!mOutputs[i]->isDuplicated()) {
1805 numOutputs++;
1806 if (portsWritten < portsMax) {
1807 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1808 }
1809 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001810 }
Eric Laurent84c70242014-06-23 08:46:27 -07001811 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001812 }
1813 }
1814 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001815 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001816 return NO_ERROR;
1817}
1818
1819status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1820{
1821 return NO_ERROR;
1822}
1823
Eric Laurent1f2f2232014-06-02 12:01:23 -07001824sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001825 audio_port_handle_t id) const
1826{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001827 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001828 for (size_t i = 0; i < mOutputs.size(); i++) {
1829 outputDesc = mOutputs.valueAt(i);
1830 if (outputDesc->mId == id) {
1831 break;
1832 }
1833 }
1834 return outputDesc;
1835}
1836
Eric Laurent1f2f2232014-06-02 12:01:23 -07001837sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001838 audio_port_handle_t id) const
1839{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001840 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001841 for (size_t i = 0; i < mInputs.size(); i++) {
1842 inputDesc = mInputs.valueAt(i);
1843 if (inputDesc->mId == id) {
1844 break;
1845 }
1846 }
1847 return inputDesc;
1848}
1849
Eric Laurent1f2f2232014-06-02 12:01:23 -07001850sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1851 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001852{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001853 sp <HwModule> module;
1854
Eric Laurent6a94d692014-05-20 11:18:06 -07001855 for (size_t i = 0; i < mHwModules.size(); i++) {
1856 if (mHwModules[i]->mHandle == 0) {
1857 continue;
1858 }
1859 if (audio_is_output_device(device)) {
1860 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1861 {
1862 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1863 return mHwModules[i];
1864 }
1865 }
1866 } else {
1867 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1868 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1869 device & ~AUDIO_DEVICE_BIT_IN) {
1870 return mHwModules[i];
1871 }
1872 }
1873 }
1874 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001875 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001876}
1877
Eric Laurent1f2f2232014-06-02 12:01:23 -07001878sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001879{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001880 sp <HwModule> module;
1881
Eric Laurent1afeecb2014-05-14 08:52:28 -07001882 for (size_t i = 0; i < mHwModules.size(); i++)
1883 {
1884 if (strcmp(mHwModules[i]->mName, name) == 0) {
1885 return mHwModules[i];
1886 }
1887 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001888 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001889}
1890
1891
Eric Laurent6a94d692014-05-20 11:18:06 -07001892status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1893 audio_patch_handle_t *handle,
1894 uid_t uid)
1895{
1896 ALOGV("createAudioPatch()");
1897
1898 if (handle == NULL || patch == NULL) {
1899 return BAD_VALUE;
1900 }
1901 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1902
1903 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1904 return INVALID_OPERATION;
1905 }
1906 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1907 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1908 return INVALID_OPERATION;
1909 }
1910
1911 sp<AudioPatch> patchDesc;
1912 ssize_t index = mAudioPatches.indexOfKey(*handle);
1913
1914 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1915 patch->sinks[0].type);
1916 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1917 patch->sources[0].role,
1918 patch->sources[0].type);
1919
1920 if (index >= 0) {
1921 patchDesc = mAudioPatches.valueAt(index);
1922 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1923 mUidCached, patchDesc->mUid, uid);
1924 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1925 return INVALID_OPERATION;
1926 }
1927 } else {
1928 *handle = 0;
1929 }
1930
1931 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1932 // TODO add support for mix to mix connection
1933 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1934 ALOGV("createAudioPatch() source mix sink not device");
1935 return BAD_VALUE;
1936 }
1937 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001938 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001939 if (outputDesc == NULL) {
1940 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1941 return BAD_VALUE;
1942 }
Eric Laurent84c70242014-06-23 08:46:27 -07001943 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1944 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001945 if (patchDesc != 0) {
1946 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1947 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1948 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1949 return BAD_VALUE;
1950 }
1951 }
1952 sp<DeviceDescriptor> devDesc =
1953 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1954 if (devDesc == 0) {
1955 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1956 return BAD_VALUE;
1957 }
1958
Eric Laurent84c70242014-06-23 08:46:27 -07001959 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001960 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07001961 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07001962 patch->sources[0].format,
1963 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001964 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001965 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001966 return INVALID_OPERATION;
1967 }
1968 // TODO: reconfigure output format and channels here
1969 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001970 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001971 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001972 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001973 true,
1974 0,
1975 handle);
1976 index = mAudioPatches.indexOfKey(*handle);
1977 if (index >= 0) {
1978 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1979 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1980 }
1981 patchDesc = mAudioPatches.valueAt(index);
1982 patchDesc->mUid = uid;
1983 ALOGV("createAudioPatch() success");
1984 } else {
1985 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1986 return INVALID_OPERATION;
1987 }
1988 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1989 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1990 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001991 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001992 if (inputDesc == NULL) {
1993 return BAD_VALUE;
1994 }
1995 if (patchDesc != 0) {
1996 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1997 return BAD_VALUE;
1998 }
1999 }
2000 sp<DeviceDescriptor> devDesc =
2001 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2002 if (devDesc == 0) {
2003 return BAD_VALUE;
2004 }
2005
Eric Laurent84c70242014-06-23 08:46:27 -07002006 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002007 patch->sinks[0].sample_rate,
2008 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002009 patch->sinks[0].format,
2010 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002011 // FIXME for the parameter type,
2012 // and the NONE
2013 (audio_output_flags_t)
2014 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002015 return INVALID_OPERATION;
2016 }
2017 // TODO: reconfigure output format and channels here
2018 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002019 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002020 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07002021 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07002022 true,
2023 handle);
2024 index = mAudioPatches.indexOfKey(*handle);
2025 if (index >= 0) {
2026 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2027 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2028 }
2029 patchDesc = mAudioPatches.valueAt(index);
2030 patchDesc->mUid = uid;
2031 ALOGV("createAudioPatch() success");
2032 } else {
2033 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2034 return INVALID_OPERATION;
2035 }
2036 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2037 // device to device connection
2038 if (patchDesc != 0) {
2039 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2040 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2041 return BAD_VALUE;
2042 }
2043 }
2044
2045 sp<DeviceDescriptor> srcDeviceDesc =
2046 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2047 sp<DeviceDescriptor> sinkDeviceDesc =
2048 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2049 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2050 return BAD_VALUE;
2051 }
2052 //update source and sink with our own data as the data passed in the patch may
2053 // be incomplete.
2054 struct audio_patch newPatch = *patch;
2055 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2056 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2057
Eric Laurent6a94d692014-05-20 11:18:06 -07002058 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002059 SortedVector<audio_io_handle_t> outputs =
2060 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2061 // if the sink device is reachable via an opened output stream, request to go via
2062 // this output stream by adding a second source to the patch description
2063 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2064 if (output != AUDIO_IO_HANDLE_NONE) {
2065 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2066 if (outputDesc->isDuplicated()) {
2067 return INVALID_OPERATION;
2068 }
2069 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2070 newPatch.num_sources = 2;
2071 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002072 }
2073 // TODO: check from routing capabilities in config file and other conflicting patches
2074
2075 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2076 if (index >= 0) {
2077 afPatchHandle = patchDesc->mAfPatchHandle;
2078 }
2079
2080 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2081 &afPatchHandle,
2082 0);
2083 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2084 status, afPatchHandle);
2085 if (status == NO_ERROR) {
2086 if (index < 0) {
2087 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2088 &newPatch, uid);
2089 addAudioPatch(patchDesc->mHandle, patchDesc);
2090 } else {
2091 patchDesc->mPatch = newPatch;
2092 }
2093 patchDesc->mAfPatchHandle = afPatchHandle;
2094 *handle = patchDesc->mHandle;
2095 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002096 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002097 } else {
2098 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2099 status);
2100 return INVALID_OPERATION;
2101 }
2102 } else {
2103 return BAD_VALUE;
2104 }
2105 } else {
2106 return BAD_VALUE;
2107 }
2108 return NO_ERROR;
2109}
2110
2111status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2112 uid_t uid)
2113{
2114 ALOGV("releaseAudioPatch() patch %d", handle);
2115
2116 ssize_t index = mAudioPatches.indexOfKey(handle);
2117
2118 if (index < 0) {
2119 return BAD_VALUE;
2120 }
2121 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2122 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2123 mUidCached, patchDesc->mUid, uid);
2124 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2125 return INVALID_OPERATION;
2126 }
2127
2128 struct audio_patch *patch = &patchDesc->mPatch;
2129 patchDesc->mUid = mUidCached;
2130 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002131 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002132 if (outputDesc == NULL) {
2133 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2134 return BAD_VALUE;
2135 }
2136
2137 setOutputDevice(outputDesc->mIoHandle,
2138 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2139 true,
2140 0,
2141 NULL);
2142 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2143 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002144 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002145 if (inputDesc == NULL) {
2146 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2147 return BAD_VALUE;
2148 }
2149 setInputDevice(inputDesc->mIoHandle,
2150 getNewInputDevice(inputDesc->mIoHandle),
2151 true,
2152 NULL);
2153 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2154 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2155 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2156 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2157 status, patchDesc->mAfPatchHandle);
2158 removeAudioPatch(patchDesc->mHandle);
2159 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002160 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002161 } else {
2162 return BAD_VALUE;
2163 }
2164 } else {
2165 return BAD_VALUE;
2166 }
2167 return NO_ERROR;
2168}
2169
2170status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2171 struct audio_patch *patches,
2172 unsigned int *generation)
2173{
2174 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2175 generation == NULL) {
2176 return BAD_VALUE;
2177 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002178 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002179 *num_patches, patches, mAudioPatches.size());
2180 if (patches == NULL) {
2181 *num_patches = 0;
2182 }
2183
2184 size_t patchesWritten = 0;
2185 size_t patchesMax = *num_patches;
2186 for (size_t i = 0;
2187 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2188 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2189 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002190 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002191 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2192 }
2193 *num_patches = mAudioPatches.size();
2194
2195 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002196 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002197 return NO_ERROR;
2198}
2199
Eric Laurente1715a42014-05-20 11:30:42 -07002200status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002201{
Eric Laurente1715a42014-05-20 11:30:42 -07002202 ALOGV("setAudioPortConfig()");
2203
2204 if (config == NULL) {
2205 return BAD_VALUE;
2206 }
2207 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2208 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002209 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2210 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002211 }
2212
Eric Laurenta121f902014-06-03 13:32:54 -07002213 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002214 if (config->type == AUDIO_PORT_TYPE_MIX) {
2215 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002216 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002217 if (outputDesc == NULL) {
2218 return BAD_VALUE;
2219 }
Eric Laurent84c70242014-06-23 08:46:27 -07002220 ALOG_ASSERT(!outputDesc->isDuplicated(),
2221 "setAudioPortConfig() called on duplicated output %d",
2222 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002223 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002224 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002225 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002226 if (inputDesc == NULL) {
2227 return BAD_VALUE;
2228 }
Eric Laurenta121f902014-06-03 13:32:54 -07002229 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002230 } else {
2231 return BAD_VALUE;
2232 }
2233 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2234 sp<DeviceDescriptor> deviceDesc;
2235 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2236 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2237 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2238 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2239 } else {
2240 return BAD_VALUE;
2241 }
2242 if (deviceDesc == NULL) {
2243 return BAD_VALUE;
2244 }
Eric Laurenta121f902014-06-03 13:32:54 -07002245 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002246 } else {
2247 return BAD_VALUE;
2248 }
2249
Eric Laurenta121f902014-06-03 13:32:54 -07002250 struct audio_port_config backupConfig;
2251 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2252 if (status == NO_ERROR) {
2253 struct audio_port_config newConfig;
2254 audioPortConfig->toAudioPortConfig(&newConfig, config);
2255 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002256 }
Eric Laurenta121f902014-06-03 13:32:54 -07002257 if (status != NO_ERROR) {
2258 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002259 }
Eric Laurente1715a42014-05-20 11:30:42 -07002260
2261 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002262}
2263
2264void AudioPolicyManager::clearAudioPatches(uid_t uid)
2265{
2266 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2267 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2268 if (patchDesc->mUid == uid) {
2269 // releaseAudioPatch() removes the patch from mAudioPatches
2270 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2271 i--;
2272 }
2273 }
2274 }
2275}
2276
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002277status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2278 audio_io_handle_t *ioHandle,
2279 audio_devices_t *device)
2280{
2281 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2282 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2283 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2284
2285 mSoundTriggerSessions.add(*session, *ioHandle);
2286
2287 return NO_ERROR;
2288}
2289
2290status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2291{
2292 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2293 if (index < 0) {
2294 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2295 return BAD_VALUE;
2296 }
2297
2298 mSoundTriggerSessions.removeItem(session);
2299 return NO_ERROR;
2300}
2301
Eric Laurent6a94d692014-05-20 11:18:06 -07002302status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2303 const sp<AudioPatch>& patch)
2304{
2305 ssize_t index = mAudioPatches.indexOfKey(handle);
2306
2307 if (index >= 0) {
2308 ALOGW("addAudioPatch() patch %d already in", handle);
2309 return ALREADY_EXISTS;
2310 }
2311 mAudioPatches.add(handle, patch);
2312 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2313 "sink handle %d",
2314 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2315 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2316 return NO_ERROR;
2317}
2318
2319status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2320{
2321 ssize_t index = mAudioPatches.indexOfKey(handle);
2322
2323 if (index < 0) {
2324 ALOGW("removeAudioPatch() patch %d not in", handle);
2325 return ALREADY_EXISTS;
2326 }
2327 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2328 mAudioPatches.valueAt(index)->mAfPatchHandle);
2329 mAudioPatches.removeItemsAt(index);
2330 return NO_ERROR;
2331}
2332
Eric Laurente552edb2014-03-10 17:42:56 -07002333// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002334// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002335// ----------------------------------------------------------------------------
2336
Eric Laurent3a4311c2014-03-17 12:00:47 -07002337uint32_t AudioPolicyManager::nextUniqueId()
2338{
2339 return android_atomic_inc(&mNextUniqueId);
2340}
2341
Eric Laurent6a94d692014-05-20 11:18:06 -07002342uint32_t AudioPolicyManager::nextAudioPortGeneration()
2343{
2344 return android_atomic_inc(&mAudioPortGeneration);
2345}
2346
Eric Laurente0720872014-03-11 09:30:41 -07002347AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002348 :
2349#ifdef AUDIO_POLICY_TEST
2350 Thread(false),
2351#endif //AUDIO_POLICY_TEST
2352 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002353 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002354 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2355 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002356 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002357 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2358 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002359{
Eric Laurent6a94d692014-05-20 11:18:06 -07002360 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002361 mpClientInterface = clientInterface;
2362
Eric Laurent3b73df72014-03-11 09:06:29 -07002363 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2364 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002365 }
2366
Eric Laurent1afeecb2014-05-14 08:52:28 -07002367 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002368 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2369 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2370 ALOGE("could not load audio policy configuration file, setting defaults");
2371 defaultAudioPolicyConfig();
2372 }
2373 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002374 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002375
2376 // must be done after reading the policy
2377 initializeVolumeCurves();
2378
2379 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002380 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2381 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002382 for (size_t i = 0; i < mHwModules.size(); i++) {
2383 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2384 if (mHwModules[i]->mHandle == 0) {
2385 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2386 continue;
2387 }
2388 // open all output streams needed to access attached devices
2389 // except for direct output streams that are only opened when they are actually
2390 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002391 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002392 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2393 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002394 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002395
Eric Laurent3a4311c2014-03-17 12:00:47 -07002396 if (outProfile->mSupportedDevices.isEmpty()) {
2397 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2398 continue;
2399 }
2400
Eric Laurent83b88082014-06-20 18:31:16 -07002401 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2402 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2403 profileType = mDefaultOutputDevice->mDeviceType;
2404 } else {
2405 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2406 }
2407 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002408 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002409 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002410
Eric Laurent83b88082014-06-20 18:31:16 -07002411 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002412 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2413 config.sample_rate = outputDesc->mSamplingRate;
2414 config.channel_mask = outputDesc->mChannelMask;
2415 config.format = outputDesc->mFormat;
2416 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2417 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2418 &output,
2419 &config,
2420 &outputDesc->mDevice,
2421 String8(""),
2422 &outputDesc->mLatency,
2423 outputDesc->mFlags);
2424
2425 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002426 ALOGW("Cannot open output stream for device %08x on hw module %s",
2427 outputDesc->mDevice,
2428 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002429 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002430 outputDesc->mSamplingRate = config.sample_rate;
2431 outputDesc->mChannelMask = config.channel_mask;
2432 outputDesc->mFormat = config.format;
2433
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002434 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002435 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002436 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002437 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002438 // give a valid ID to an attached device once confirmed it is reachable
2439 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2440 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002441 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002442 }
2443 }
Eric Laurente552edb2014-03-10 17:42:56 -07002444 if (mPrimaryOutput == 0 &&
2445 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2446 mPrimaryOutput = output;
2447 }
2448 addOutput(output, outputDesc);
2449 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002450 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002451 true);
2452 }
2453 }
2454 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002455 // open input streams needed to access attached devices to validate
2456 // mAvailableInputDevices list
2457 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2458 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002459 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002460
Eric Laurent3a4311c2014-03-17 12:00:47 -07002461 if (inProfile->mSupportedDevices.isEmpty()) {
2462 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2463 continue;
2464 }
2465
Eric Laurent83b88082014-06-20 18:31:16 -07002466 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2467 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002468 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002469
2470 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002471 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002472
Eric Laurentcf2c0212014-07-25 16:20:43 -07002473 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2474 config.sample_rate = inputDesc->mSamplingRate;
2475 config.channel_mask = inputDesc->mChannelMask;
2476 config.format = inputDesc->mFormat;
2477 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2478 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2479 &input,
2480 &config,
2481 &inputDesc->mDevice,
2482 String8(""),
2483 AUDIO_SOURCE_MIC,
2484 AUDIO_INPUT_FLAG_NONE);
2485
2486 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002487 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002488 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002489 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002490 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002491 // give a valid ID to an attached device once confirmed it is reachable
2492 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2493 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002494 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002495 }
2496 }
2497 mpClientInterface->closeInput(input);
2498 } else {
2499 ALOGW("Cannot open input stream for device %08x on hw module %s",
2500 inputDesc->mDevice,
2501 mHwModules[i]->mName);
2502 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002503 }
2504 }
2505 }
2506 // make sure all attached devices have been allocated a unique ID
2507 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2508 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002509 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002510 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2511 continue;
2512 }
2513 i++;
2514 }
2515 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2516 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002517 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002518 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2519 continue;
2520 }
2521 i++;
2522 }
2523 // make sure default device is reachable
2524 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002525 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002526 }
Eric Laurente552edb2014-03-10 17:42:56 -07002527
2528 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2529
2530 updateDevicesAndOutputs();
2531
2532#ifdef AUDIO_POLICY_TEST
2533 if (mPrimaryOutput != 0) {
2534 AudioParameter outputCmd = AudioParameter();
2535 outputCmd.addInt(String8("set_id"), 0);
2536 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2537
2538 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2539 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002540 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2541 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002542 mTestLatencyMs = 0;
2543 mCurOutput = 0;
2544 mDirectOutput = false;
2545 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2546 mTestOutputs[i] = 0;
2547 }
2548
2549 const size_t SIZE = 256;
2550 char buffer[SIZE];
2551 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2552 run(buffer, ANDROID_PRIORITY_AUDIO);
2553 }
2554#endif //AUDIO_POLICY_TEST
2555}
2556
Eric Laurente0720872014-03-11 09:30:41 -07002557AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002558{
2559#ifdef AUDIO_POLICY_TEST
2560 exit();
2561#endif //AUDIO_POLICY_TEST
2562 for (size_t i = 0; i < mOutputs.size(); i++) {
2563 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002564 }
2565 for (size_t i = 0; i < mInputs.size(); i++) {
2566 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002567 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002568 mAvailableOutputDevices.clear();
2569 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002570 mOutputs.clear();
2571 mInputs.clear();
2572 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002573}
2574
Eric Laurente0720872014-03-11 09:30:41 -07002575status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002576{
2577 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2578}
2579
2580#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002581bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002582{
2583 ALOGV("entering threadLoop()");
2584 while (!exitPending())
2585 {
2586 String8 command;
2587 int valueInt;
2588 String8 value;
2589
2590 Mutex::Autolock _l(mLock);
2591 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2592
2593 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2594 AudioParameter param = AudioParameter(command);
2595
2596 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2597 valueInt != 0) {
2598 ALOGV("Test command %s received", command.string());
2599 String8 target;
2600 if (param.get(String8("target"), target) != NO_ERROR) {
2601 target = "Manager";
2602 }
2603 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2604 param.remove(String8("test_cmd_policy_output"));
2605 mCurOutput = valueInt;
2606 }
2607 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2608 param.remove(String8("test_cmd_policy_direct"));
2609 if (value == "false") {
2610 mDirectOutput = false;
2611 } else if (value == "true") {
2612 mDirectOutput = true;
2613 }
2614 }
2615 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2616 param.remove(String8("test_cmd_policy_input"));
2617 mTestInput = valueInt;
2618 }
2619
2620 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2621 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002622 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002623 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002624 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002625 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002626 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002627 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002628 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002629 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002630 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002631 if (target == "Manager") {
2632 mTestFormat = format;
2633 } else if (mTestOutputs[mCurOutput] != 0) {
2634 AudioParameter outputParam = AudioParameter();
2635 outputParam.addInt(String8("format"), format);
2636 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2637 }
2638 }
2639 }
2640 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2641 param.remove(String8("test_cmd_policy_channels"));
2642 int channels = 0;
2643
2644 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002645 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002646 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002647 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002648 }
2649 if (channels != 0) {
2650 if (target == "Manager") {
2651 mTestChannels = channels;
2652 } else if (mTestOutputs[mCurOutput] != 0) {
2653 AudioParameter outputParam = AudioParameter();
2654 outputParam.addInt(String8("channels"), channels);
2655 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2656 }
2657 }
2658 }
2659 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2660 param.remove(String8("test_cmd_policy_sampleRate"));
2661 if (valueInt >= 0 && valueInt <= 96000) {
2662 int samplingRate = valueInt;
2663 if (target == "Manager") {
2664 mTestSamplingRate = samplingRate;
2665 } else if (mTestOutputs[mCurOutput] != 0) {
2666 AudioParameter outputParam = AudioParameter();
2667 outputParam.addInt(String8("sampling_rate"), samplingRate);
2668 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2669 }
2670 }
2671 }
2672
2673 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2674 param.remove(String8("test_cmd_policy_reopen"));
2675
Eric Laurent1f2f2232014-06-02 12:01:23 -07002676 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002677 mpClientInterface->closeOutput(mPrimaryOutput);
2678
2679 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2680
Eric Laurente552edb2014-03-10 17:42:56 -07002681 mOutputs.removeItem(mPrimaryOutput);
2682
Eric Laurent1f2f2232014-06-02 12:01:23 -07002683 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002684 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002685 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2686 config.sample_rate = outputDesc->mSamplingRate;
2687 config.channel_mask = outputDesc->mChannelMask;
2688 config.format = outputDesc->mFormat;
2689 status_t status = mpClientInterface->openOutput(moduleHandle,
2690 &mPrimaryOutput,
2691 &config,
2692 &outputDesc->mDevice,
2693 String8(""),
2694 &outputDesc->mLatency,
2695 outputDesc->mFlags);
2696 if (status != NO_ERROR) {
2697 ALOGE("Failed to reopen hardware output stream, "
2698 "samplingRate: %d, format %d, channels %d",
2699 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002700 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002701 outputDesc->mSamplingRate = config.sample_rate;
2702 outputDesc->mChannelMask = config.channel_mask;
2703 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002704 AudioParameter outputCmd = AudioParameter();
2705 outputCmd.addInt(String8("set_id"), 0);
2706 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2707 addOutput(mPrimaryOutput, outputDesc);
2708 }
2709 }
2710
2711
2712 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2713 }
2714 }
2715 return false;
2716}
2717
Eric Laurente0720872014-03-11 09:30:41 -07002718void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002719{
2720 {
2721 AutoMutex _l(mLock);
2722 requestExit();
2723 mWaitWorkCV.signal();
2724 }
2725 requestExitAndWait();
2726}
2727
Eric Laurente0720872014-03-11 09:30:41 -07002728int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002729{
2730 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2731 if (output == mTestOutputs[i]) return i;
2732 }
2733 return 0;
2734}
2735#endif //AUDIO_POLICY_TEST
2736
2737// ---
2738
Eric Laurent1f2f2232014-06-02 12:01:23 -07002739void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002740{
Eric Laurent1c333e22014-05-20 10:48:17 -07002741 outputDesc->mIoHandle = output;
2742 outputDesc->mId = nextUniqueId();
2743 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002744 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002745}
2746
Eric Laurent1f2f2232014-06-02 12:01:23 -07002747void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002748{
Eric Laurent1c333e22014-05-20 10:48:17 -07002749 inputDesc->mIoHandle = input;
2750 inputDesc->mId = nextUniqueId();
2751 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002752 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002753}
Eric Laurente552edb2014-03-10 17:42:56 -07002754
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002755void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2756 const String8 address /*in*/,
2757 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2758 // look for a match on the given address on the addresses of the outputs:
2759 // find the address by finding the patch that maps to this output
2760 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2761 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2762 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2763 if (patchIdx >= 0) {
2764 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2765 const int numSinks = patchDesc->mPatch.num_sinks;
2766 for (ssize_t j=0; j < numSinks; j++) {
2767 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2768 const char* patchAddr =
2769 patchDesc->mPatch.sinks[j].ext.device.address;
2770 if (strncmp(patchAddr,
2771 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2772 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2773 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2774 outputs.add(desc->mIoHandle);
2775 break;
2776 }
2777 }
2778 }
2779 }
2780}
2781
Eric Laurente0720872014-03-11 09:30:41 -07002782status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002783 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002784 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002785 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002786{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002787 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002788
Eric Laurent3b73df72014-03-11 09:06:29 -07002789 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002790 // first list already open outputs that can be routed to this device
2791 for (size_t i = 0; i < mOutputs.size(); i++) {
2792 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002793 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002794 if (!deviceDistinguishesOnAddress(device)) {
2795 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2796 outputs.add(mOutputs.keyAt(i));
2797 } else {
2798 ALOGV(" checking address match due to device 0x%x", device);
2799 findIoHandlesByAddress(desc, address, outputs);
2800 }
Eric Laurente552edb2014-03-10 17:42:56 -07002801 }
2802 }
2803 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002804 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002805 for (size_t i = 0; i < mHwModules.size(); i++)
2806 {
2807 if (mHwModules[i]->mHandle == 0) {
2808 continue;
2809 }
2810 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2811 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002812 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002813 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002814 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2815 }
2816 }
2817 }
2818
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002819 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2820
Eric Laurente552edb2014-03-10 17:42:56 -07002821 if (profiles.isEmpty() && outputs.isEmpty()) {
2822 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2823 return BAD_VALUE;
2824 }
2825
2826 // open outputs for matching profiles if needed. Direct outputs are also opened to
2827 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2828 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002829 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002830
2831 // nothing to do if one output is already opened for this profile
2832 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002833 for (j = 0; j < outputs.size(); j++) {
2834 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002835 if (!desc->isDuplicated() && desc->mProfile == profile) {
2836 break;
2837 }
2838 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002839 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002840 continue;
2841 }
2842
Eric Laurent83b88082014-06-20 18:31:16 -07002843 ALOGV("opening output for device %08x with params %s profile %p",
2844 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002845 desc = new AudioOutputDescriptor(profile);
2846 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002847 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2848 config.sample_rate = desc->mSamplingRate;
2849 config.channel_mask = desc->mChannelMask;
2850 config.format = desc->mFormat;
2851 config.offload_info.sample_rate = desc->mSamplingRate;
2852 config.offload_info.channel_mask = desc->mChannelMask;
2853 config.offload_info.format = desc->mFormat;
2854 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2855 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
2856 &output,
2857 &config,
2858 &desc->mDevice,
2859 address,
2860 &desc->mLatency,
2861 desc->mFlags);
2862 if (status == NO_ERROR) {
2863 desc->mSamplingRate = config.sample_rate;
2864 desc->mChannelMask = config.channel_mask;
2865 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002866
Eric Laurentd4692962014-05-05 18:13:44 -07002867 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002868 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002869 char *param = audio_device_address_to_parameter(device, address);
2870 mpClientInterface->setParameters(output, String8(param));
2871 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07002872 }
2873
Eric Laurentd4692962014-05-05 18:13:44 -07002874 // Here is where we step through and resolve any "dynamic" fields
2875 String8 reply;
2876 char *value;
2877 if (profile->mSamplingRates[0] == 0) {
2878 reply = mpClientInterface->getParameters(output,
2879 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002880 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002881 reply.string());
2882 value = strpbrk((char *)reply.string(), "=");
2883 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002884 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002885 }
Eric Laurentd4692962014-05-05 18:13:44 -07002886 }
2887 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2888 reply = mpClientInterface->getParameters(output,
2889 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002890 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002891 reply.string());
2892 value = strpbrk((char *)reply.string(), "=");
2893 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002894 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002895 }
Eric Laurentd4692962014-05-05 18:13:44 -07002896 }
2897 if (profile->mChannelMasks[0] == 0) {
2898 reply = mpClientInterface->getParameters(output,
2899 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002900 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002901 reply.string());
2902 value = strpbrk((char *)reply.string(), "=");
2903 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002904 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002905 }
Eric Laurentd4692962014-05-05 18:13:44 -07002906 }
2907 if (((profile->mSamplingRates[0] == 0) &&
2908 (profile->mSamplingRates.size() < 2)) ||
2909 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2910 (profile->mFormats.size() < 2)) ||
2911 ((profile->mChannelMasks[0] == 0) &&
2912 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002913 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002914 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002915 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07002916 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2917 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002918 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002919 config.sample_rate = profile->pickSamplingRate();
2920 config.channel_mask = profile->pickChannelMask();
2921 config.format = profile->pickFormat();
2922 config.offload_info.sample_rate = config.sample_rate;
2923 config.offload_info.channel_mask = config.channel_mask;
2924 config.offload_info.format = config.format;
2925 status = mpClientInterface->openOutput(profile->mModule->mHandle,
2926 &output,
2927 &config,
2928 &desc->mDevice,
2929 address,
2930 &desc->mLatency,
2931 desc->mFlags);
2932 if (status == NO_ERROR) {
2933 desc->mSamplingRate = config.sample_rate;
2934 desc->mChannelMask = config.channel_mask;
2935 desc->mFormat = config.format;
2936 } else {
2937 output = AUDIO_IO_HANDLE_NONE;
2938 }
Eric Laurentd4692962014-05-05 18:13:44 -07002939 }
2940
Eric Laurentcf2c0212014-07-25 16:20:43 -07002941 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002942 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002943 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002944 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002945
Eric Laurentd4692962014-05-05 18:13:44 -07002946 // set initial stream volume for device
2947 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002948
Eric Laurentd4692962014-05-05 18:13:44 -07002949 //TODO: configure audio effect output stage here
2950
2951 // open a duplicating output thread for the new output and the primary output
2952 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2953 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002954 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07002955 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07002956 sp<AudioOutputDescriptor> dupOutputDesc =
2957 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002958 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2959 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2960 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2961 dupOutputDesc->mFormat = desc->mFormat;
2962 dupOutputDesc->mChannelMask = desc->mChannelMask;
2963 dupOutputDesc->mLatency = desc->mLatency;
2964 addOutput(duplicatedOutput, dupOutputDesc);
2965 applyStreamVolumes(duplicatedOutput, device, 0, true);
2966 } else {
2967 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2968 mPrimaryOutput, output);
2969 mpClientInterface->closeOutput(output);
2970 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002972 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07002973 }
Eric Laurente552edb2014-03-10 17:42:56 -07002974 }
2975 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002976 } else {
2977 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002978 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002979 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002980 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002981 profiles.removeAt(profile_index);
2982 profile_index--;
2983 } else {
2984 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002985 if (deviceDistinguishesOnAddress(device)) {
2986 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2987 device, address.string());
2988 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2989 NULL/*patch handle*/, address.string());
2990 }
Eric Laurente552edb2014-03-10 17:42:56 -07002991 ALOGV("checkOutputsForDevice(): adding output %d", output);
2992 }
2993 }
2994
2995 if (profiles.isEmpty()) {
2996 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2997 return BAD_VALUE;
2998 }
Eric Laurentd4692962014-05-05 18:13:44 -07002999 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003000 // check if one opened output is not needed any more after disconnecting one device
3001 for (size_t i = 0; i < mOutputs.size(); i++) {
3002 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003003 if (!desc->isDuplicated()) {
3004 if (!(desc->mProfile->mSupportedDevices.types()
3005 & mAvailableOutputDevices.types())) {
3006 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3007 mOutputs.keyAt(i));
3008 outputs.add(mOutputs.keyAt(i));
3009 } else if (deviceDistinguishesOnAddress(device) &&
3010 // exact match on device
3011 (desc->mProfile->mSupportedDevices.types() == device)) {
3012 findIoHandlesByAddress(desc, address, outputs);
3013 }
Eric Laurente552edb2014-03-10 17:42:56 -07003014 }
3015 }
Eric Laurentd4692962014-05-05 18:13:44 -07003016 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003017 for (size_t i = 0; i < mHwModules.size(); i++)
3018 {
3019 if (mHwModules[i]->mHandle == 0) {
3020 continue;
3021 }
3022 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3023 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003024 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003025 if (profile->mSupportedDevices.types() & device) {
3026 ALOGV("checkOutputsForDevice(): "
3027 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003028 if (profile->mSamplingRates[0] == 0) {
3029 profile->mSamplingRates.clear();
3030 profile->mSamplingRates.add(0);
3031 }
3032 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3033 profile->mFormats.clear();
3034 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3035 }
3036 if (profile->mChannelMasks[0] == 0) {
3037 profile->mChannelMasks.clear();
3038 profile->mChannelMasks.add(0);
3039 }
3040 }
3041 }
3042 }
3043 }
3044 return NO_ERROR;
3045}
3046
Eric Laurentd4692962014-05-05 18:13:44 -07003047status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3048 audio_policy_dev_state_t state,
3049 SortedVector<audio_io_handle_t>& inputs,
3050 const String8 address)
3051{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003052 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003053 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3054 // first list already open inputs that can be routed to this device
3055 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3056 desc = mInputs.valueAt(input_index);
3057 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3058 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3059 inputs.add(mInputs.keyAt(input_index));
3060 }
3061 }
3062
3063 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003064 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003065 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3066 {
3067 if (mHwModules[module_idx]->mHandle == 0) {
3068 continue;
3069 }
3070 for (size_t profile_index = 0;
3071 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3072 profile_index++)
3073 {
3074 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3075 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003076 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003077 profile_index, module_idx);
3078 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3079 }
3080 }
3081 }
3082
3083 if (profiles.isEmpty() && inputs.isEmpty()) {
3084 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3085 return BAD_VALUE;
3086 }
3087
3088 // open inputs for matching profiles if needed. Direct inputs are also opened to
3089 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3090 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3091
Eric Laurent1c333e22014-05-20 10:48:17 -07003092 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003093 // nothing to do if one input is already opened for this profile
3094 size_t input_index;
3095 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3096 desc = mInputs.valueAt(input_index);
3097 if (desc->mProfile == profile) {
3098 break;
3099 }
3100 }
3101 if (input_index != mInputs.size()) {
3102 continue;
3103 }
3104
3105 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3106 desc = new AudioInputDescriptor(profile);
3107 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003108 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3109 config.sample_rate = desc->mSamplingRate;
3110 config.channel_mask = desc->mChannelMask;
3111 config.format = desc->mFormat;
3112 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3113 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3114 &input,
3115 &config,
3116 &desc->mDevice,
3117 address,
3118 AUDIO_SOURCE_MIC,
3119 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003120
Eric Laurentcf2c0212014-07-25 16:20:43 -07003121 if (status == NO_ERROR) {
3122 desc->mSamplingRate = config.sample_rate;
3123 desc->mChannelMask = config.channel_mask;
3124 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003125
Eric Laurentd4692962014-05-05 18:13:44 -07003126 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003127 char *param = audio_device_address_to_parameter(device, address);
3128 mpClientInterface->setParameters(input, String8(param));
3129 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003130 }
3131
3132 // Here is where we step through and resolve any "dynamic" fields
3133 String8 reply;
3134 char *value;
3135 if (profile->mSamplingRates[0] == 0) {
3136 reply = mpClientInterface->getParameters(input,
3137 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3138 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3139 reply.string());
3140 value = strpbrk((char *)reply.string(), "=");
3141 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003142 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003143 }
3144 }
3145 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3146 reply = mpClientInterface->getParameters(input,
3147 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3148 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3149 value = strpbrk((char *)reply.string(), "=");
3150 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003151 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003152 }
3153 }
3154 if (profile->mChannelMasks[0] == 0) {
3155 reply = mpClientInterface->getParameters(input,
3156 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3157 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3158 reply.string());
3159 value = strpbrk((char *)reply.string(), "=");
3160 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003161 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003162 }
3163 }
3164 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3165 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3166 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3167 ALOGW("checkInputsForDevice() direct input missing param");
3168 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003169 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003170 }
3171
3172 if (input != 0) {
3173 addInput(input, desc);
3174 }
3175 } // endif input != 0
3176
Eric Laurentcf2c0212014-07-25 16:20:43 -07003177 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003178 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003179 profiles.removeAt(profile_index);
3180 profile_index--;
3181 } else {
3182 inputs.add(input);
3183 ALOGV("checkInputsForDevice(): adding input %d", input);
3184 }
3185 } // end scan profiles
3186
3187 if (profiles.isEmpty()) {
3188 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3189 return BAD_VALUE;
3190 }
3191 } else {
3192 // Disconnect
3193 // check if one opened input is not needed any more after disconnecting one device
3194 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3195 desc = mInputs.valueAt(input_index);
3196 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3197 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3198 mInputs.keyAt(input_index));
3199 inputs.add(mInputs.keyAt(input_index));
3200 }
3201 }
3202 // Clear any profiles associated with the disconnected device.
3203 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3204 if (mHwModules[module_index]->mHandle == 0) {
3205 continue;
3206 }
3207 for (size_t profile_index = 0;
3208 profile_index < mHwModules[module_index]->mInputProfiles.size();
3209 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003210 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003211 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003212 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003213 profile_index, module_index);
3214 if (profile->mSamplingRates[0] == 0) {
3215 profile->mSamplingRates.clear();
3216 profile->mSamplingRates.add(0);
3217 }
3218 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3219 profile->mFormats.clear();
3220 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3221 }
3222 if (profile->mChannelMasks[0] == 0) {
3223 profile->mChannelMasks.clear();
3224 profile->mChannelMasks.add(0);
3225 }
3226 }
3227 }
3228 }
3229 } // end disconnect
3230
3231 return NO_ERROR;
3232}
3233
3234
Eric Laurente0720872014-03-11 09:30:41 -07003235void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003236{
3237 ALOGV("closeOutput(%d)", output);
3238
Eric Laurent1f2f2232014-06-02 12:01:23 -07003239 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003240 if (outputDesc == NULL) {
3241 ALOGW("closeOutput() unknown output %d", output);
3242 return;
3243 }
3244
3245 // look for duplicated outputs connected to the output being removed.
3246 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003247 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003248 if (dupOutputDesc->isDuplicated() &&
3249 (dupOutputDesc->mOutput1 == outputDesc ||
3250 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003251 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003252 if (dupOutputDesc->mOutput1 == outputDesc) {
3253 outputDesc2 = dupOutputDesc->mOutput2;
3254 } else {
3255 outputDesc2 = dupOutputDesc->mOutput1;
3256 }
3257 // As all active tracks on duplicated output will be deleted,
3258 // and as they were also referenced on the other output, the reference
3259 // count for their stream type must be adjusted accordingly on
3260 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003261 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003262 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003263 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003264 }
3265 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3266 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3267
3268 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003269 mOutputs.removeItem(duplicatedOutput);
3270 }
3271 }
3272
3273 AudioParameter param;
3274 param.add(String8("closing"), String8("true"));
3275 mpClientInterface->setParameters(output, param.toString());
3276
3277 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003278 mOutputs.removeItem(output);
3279 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003280 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003281}
3282
Eric Laurente0720872014-03-11 09:30:41 -07003283SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003284 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003285{
3286 SortedVector<audio_io_handle_t> outputs;
3287
3288 ALOGVV("getOutputsForDevice() device %04x", device);
3289 for (size_t i = 0; i < openOutputs.size(); i++) {
3290 ALOGVV("output %d isDuplicated=%d device=%04x",
3291 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3292 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3293 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3294 outputs.add(openOutputs.keyAt(i));
3295 }
3296 }
3297 return outputs;
3298}
3299
Eric Laurente0720872014-03-11 09:30:41 -07003300bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003301 SortedVector<audio_io_handle_t>& outputs2)
3302{
3303 if (outputs1.size() != outputs2.size()) {
3304 return false;
3305 }
3306 for (size_t i = 0; i < outputs1.size(); i++) {
3307 if (outputs1[i] != outputs2[i]) {
3308 return false;
3309 }
3310 }
3311 return true;
3312}
3313
Eric Laurente0720872014-03-11 09:30:41 -07003314void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003315{
3316 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3317 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3318 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3319 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3320
3321 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3322 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3323 strategy, srcOutputs[0], dstOutputs[0]);
3324 // mute strategy while moving tracks from one output to another
3325 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003326 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003327 if (desc->isStrategyActive(strategy)) {
3328 setStrategyMute(strategy, true, srcOutputs[i]);
3329 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3330 }
3331 }
3332
3333 // Move effects associated to this strategy from previous output to new output
3334 if (strategy == STRATEGY_MEDIA) {
3335 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3336 SortedVector<audio_io_handle_t> moved;
3337 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003338 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3339 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3340 effectDesc->mIo != fxOutput) {
3341 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003342 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3343 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003344 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003345 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003346 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003347 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003348 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003349 }
3350 }
3351 }
3352 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003353 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3354 if (getStrategy((audio_stream_type_t)i) == strategy) {
3355 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003356 }
3357 }
3358 }
3359}
3360
Eric Laurente0720872014-03-11 09:30:41 -07003361void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003362{
3363 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3364 checkOutputForStrategy(STRATEGY_PHONE);
3365 checkOutputForStrategy(STRATEGY_SONIFICATION);
3366 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3367 checkOutputForStrategy(STRATEGY_MEDIA);
3368 checkOutputForStrategy(STRATEGY_DTMF);
3369}
3370
Eric Laurente0720872014-03-11 09:30:41 -07003371audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003372{
Eric Laurente552edb2014-03-10 17:42:56 -07003373 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003374 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003375 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3376 return mOutputs.keyAt(i);
3377 }
3378 }
3379
3380 return 0;
3381}
3382
Eric Laurente0720872014-03-11 09:30:41 -07003383void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003384{
Eric Laurente552edb2014-03-10 17:42:56 -07003385 audio_io_handle_t a2dpOutput = getA2dpOutput();
3386 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003387 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003388 return;
3389 }
3390
Eric Laurent3a4311c2014-03-17 12:00:47 -07003391 bool isScoConnected =
3392 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003393 // suspend A2DP output if:
3394 // (NOT already suspended) &&
3395 // ((SCO device is connected &&
3396 // (forced usage for communication || for record is SCO))) ||
3397 // (phone state is ringing || in call)
3398 //
3399 // restore A2DP output if:
3400 // (Already suspended) &&
3401 // ((SCO device is NOT connected ||
3402 // (forced usage NOT for communication && NOT for record is SCO))) &&
3403 // (phone state is NOT ringing && NOT in call)
3404 //
3405 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003406 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003407 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3408 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3409 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3410 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003411
3412 mpClientInterface->restoreOutput(a2dpOutput);
3413 mA2dpSuspended = false;
3414 }
3415 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003416 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003417 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3418 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3419 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3420 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003421
3422 mpClientInterface->suspendOutput(a2dpOutput);
3423 mA2dpSuspended = true;
3424 }
3425 }
3426}
3427
Eric Laurent1c333e22014-05-20 10:48:17 -07003428audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003429{
3430 audio_devices_t device = AUDIO_DEVICE_NONE;
3431
Eric Laurent1f2f2232014-06-02 12:01:23 -07003432 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003433
3434 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3435 if (index >= 0) {
3436 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3437 if (patchDesc->mUid != mUidCached) {
3438 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3439 outputDesc->device(), outputDesc->mPatchHandle);
3440 return outputDesc->device();
3441 }
3442 }
3443
Eric Laurente552edb2014-03-10 17:42:56 -07003444 // check the following by order of priority to request a routing change if necessary:
3445 // 1: the strategy enforced audible is active on the output:
3446 // use device for strategy enforced audible
3447 // 2: we are in call or the strategy phone is active on the output:
3448 // use device for strategy phone
3449 // 3: the strategy sonification is active on the output:
3450 // use device for strategy sonification
3451 // 4: the strategy "respectful" sonification is active on the output:
3452 // use device for strategy "respectful" sonification
3453 // 5: the strategy media is active on the output:
3454 // use device for strategy media
3455 // 6: the strategy DTMF is active on the output:
3456 // use device for strategy DTMF
3457 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3458 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3459 } else if (isInCall() ||
3460 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3461 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3462 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3463 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3464 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3465 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3466 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3467 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3468 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3469 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3470 }
3471
Eric Laurent1c333e22014-05-20 10:48:17 -07003472 ALOGV("getNewOutputDevice() selected device %x", device);
3473 return device;
3474}
3475
3476audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3477{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003478 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003479
3480 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3481 if (index >= 0) {
3482 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3483 if (patchDesc->mUid != mUidCached) {
3484 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3485 inputDesc->mDevice, inputDesc->mPatchHandle);
3486 return inputDesc->mDevice;
3487 }
3488 }
3489
Eric Laurent1c333e22014-05-20 10:48:17 -07003490 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3491
3492 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003493 return device;
3494}
3495
Eric Laurente0720872014-03-11 09:30:41 -07003496uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003497 return (uint32_t)getStrategy(stream);
3498}
3499
Eric Laurente0720872014-03-11 09:30:41 -07003500audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003501 // By checking the range of stream before calling getStrategy, we avoid
3502 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3503 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003504 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003505 return AUDIO_DEVICE_NONE;
3506 }
3507 audio_devices_t devices;
3508 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3509 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3510 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3511 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003512 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003513 if (outputDesc->isStrategyActive(strategy)) {
3514 devices = outputDesc->device();
3515 break;
3516 }
Eric Laurente552edb2014-03-10 17:42:56 -07003517 }
3518 return devices;
3519}
3520
Eric Laurente0720872014-03-11 09:30:41 -07003521AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003522 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003523 // stream to strategy mapping
3524 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003525 case AUDIO_STREAM_VOICE_CALL:
3526 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003527 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003528 case AUDIO_STREAM_RING:
3529 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003530 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003531 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003532 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003533 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003534 return STRATEGY_DTMF;
3535 default:
3536 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003537 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003538 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3539 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003540 case AUDIO_STREAM_TTS:
3541 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003542 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003543 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003544 return STRATEGY_ENFORCED_AUDIBLE;
3545 }
3546}
3547
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003548uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3549 // flags to strategy mapping
3550 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3551 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3552 }
3553
3554 // usage to strategy mapping
3555 switch (attr->usage) {
3556 case AUDIO_USAGE_MEDIA:
3557 case AUDIO_USAGE_GAME:
3558 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3559 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3560 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3561 return (uint32_t) STRATEGY_MEDIA;
3562
3563 case AUDIO_USAGE_VOICE_COMMUNICATION:
3564 return (uint32_t) STRATEGY_PHONE;
3565
3566 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3567 return (uint32_t) STRATEGY_DTMF;
3568
3569 case AUDIO_USAGE_ALARM:
3570 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3571 return (uint32_t) STRATEGY_SONIFICATION;
3572
3573 case AUDIO_USAGE_NOTIFICATION:
3574 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3575 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3576 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3577 case AUDIO_USAGE_NOTIFICATION_EVENT:
3578 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3579
3580 case AUDIO_USAGE_UNKNOWN:
3581 default:
3582 return (uint32_t) STRATEGY_MEDIA;
3583 }
3584}
3585
Eric Laurente0720872014-03-11 09:30:41 -07003586void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003587 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003588 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003589 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3590 updateDevicesAndOutputs();
3591 break;
3592 default:
3593 break;
3594 }
3595}
3596
Eric Laurente0720872014-03-11 09:30:41 -07003597audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003598 bool fromCache)
3599{
3600 uint32_t device = AUDIO_DEVICE_NONE;
3601
3602 if (fromCache) {
3603 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3604 strategy, mDeviceForStrategy[strategy]);
3605 return mDeviceForStrategy[strategy];
3606 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003607 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003608 switch (strategy) {
3609
3610 case STRATEGY_SONIFICATION_RESPECTFUL:
3611 if (isInCall()) {
3612 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003613 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003614 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3615 // while media is playing on a remote device, use the the sonification behavior.
3616 // Note that we test this usecase before testing if media is playing because
3617 // the isStreamActive() method only informs about the activity of a stream, not
3618 // if it's for local playback. Note also that we use the same delay between both tests
3619 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003620 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003621 // while media is playing (or has recently played), use the same device
3622 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3623 } else {
3624 // when media is not playing anymore, fall back on the sonification behavior
3625 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3626 }
3627
3628 break;
3629
3630 case STRATEGY_DTMF:
3631 if (!isInCall()) {
3632 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3633 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3634 break;
3635 }
3636 // when in call, DTMF and PHONE strategies follow the same rules
3637 // FALL THROUGH
3638
3639 case STRATEGY_PHONE:
3640 // for phone strategy, we first consider the forced use and then the available devices by order
3641 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003642 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3643 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003644 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003645 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003646 if (device) break;
3647 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003648 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003649 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003650 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003651 if (device) break;
3652 // if SCO device is requested but no SCO device is available, fall back to default case
3653 // FALL THROUGH
3654
3655 default: // FORCE_NONE
3656 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003657 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003658 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003659 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003660 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003661 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003662 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003663 if (device) break;
3664 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003665 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003666 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003667 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003668 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003669 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003670 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003671 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003672 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003673 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003674 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003675 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003676 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003677 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003678 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003679 if (device) break;
3680 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003681 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003682 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003683 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003684 if (device == AUDIO_DEVICE_NONE) {
3685 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3686 }
3687 break;
3688
Eric Laurent3b73df72014-03-11 09:06:29 -07003689 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003690 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3691 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003692 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003693 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003694 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003695 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003696 if (device) break;
3697 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003698 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003699 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003700 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003701 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003702 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003703 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003704 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003705 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003706 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003707 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003708 if (device) break;
3709 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003710 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3711 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003712 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003713 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003714 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003715 if (device == AUDIO_DEVICE_NONE) {
3716 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3717 }
3718 break;
3719 }
3720 break;
3721
3722 case STRATEGY_SONIFICATION:
3723
3724 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3725 // handleIncallSonification().
3726 if (isInCall()) {
3727 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3728 break;
3729 }
3730 // FALL THROUGH
3731
3732 case STRATEGY_ENFORCED_AUDIBLE:
3733 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3734 // except:
3735 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3736 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3737
3738 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003739 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003740 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003741 if (device == AUDIO_DEVICE_NONE) {
3742 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3743 }
3744 }
3745 // The second device used for sonification is the same as the device used by media strategy
3746 // FALL THROUGH
3747
3748 case STRATEGY_MEDIA: {
3749 uint32_t device2 = AUDIO_DEVICE_NONE;
3750 if (strategy != STRATEGY_SONIFICATION) {
3751 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003752 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003753 }
3754 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003755 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003756 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003757 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003758 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003759 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003760 }
3761 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003762 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003763 }
3764 }
3765 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003766 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003767 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003768 if ((device2 == AUDIO_DEVICE_NONE)) {
3769 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3770 }
Eric Laurente552edb2014-03-10 17:42:56 -07003771 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003772 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003773 }
3774 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003775 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003776 }
3777 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003778 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003779 }
3780 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003781 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003782 }
3783 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3784 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003785 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003786 }
3787 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003788 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003789 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003790 }
3791 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003792 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003793 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003794 int device3 = AUDIO_DEVICE_NONE;
3795 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003796 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003797 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3798 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003799 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003800 }
Eric Laurente552edb2014-03-10 17:42:56 -07003801
Jungshik Jang839e4f32014-06-26 17:23:40 +09003802 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003803 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3804 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3805 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003806
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003807 // If hdmi system audio mode is on, remove speaker out of output list.
3808 if ((strategy == STRATEGY_MEDIA) &&
3809 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3810 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3811 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3812 }
3813
Eric Laurente552edb2014-03-10 17:42:56 -07003814 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003815 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003816 if (device == AUDIO_DEVICE_NONE) {
3817 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3818 }
3819 } break;
3820
3821 default:
3822 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3823 break;
3824 }
3825
3826 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3827 return device;
3828}
3829
Eric Laurente0720872014-03-11 09:30:41 -07003830void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003831{
3832 for (int i = 0; i < NUM_STRATEGIES; i++) {
3833 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3834 }
3835 mPreviousOutputs = mOutputs;
3836}
3837
Eric Laurent1f2f2232014-06-02 12:01:23 -07003838uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003839 audio_devices_t prevDevice,
3840 uint32_t delayMs)
3841{
3842 // mute/unmute strategies using an incompatible device combination
3843 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3844 // if unmuting, unmute only after the specified delay
3845 if (outputDesc->isDuplicated()) {
3846 return 0;
3847 }
3848
3849 uint32_t muteWaitMs = 0;
3850 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003851 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003852
3853 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3854 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3855 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3856 bool doMute = false;
3857
3858 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3859 doMute = true;
3860 outputDesc->mStrategyMutedByDevice[i] = true;
3861 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3862 doMute = true;
3863 outputDesc->mStrategyMutedByDevice[i] = false;
3864 }
Eric Laurent99401132014-05-07 19:48:15 -07003865 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003866 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003867 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003868 // skip output if it does not share any device with current output
3869 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3870 == AUDIO_DEVICE_NONE) {
3871 continue;
3872 }
3873 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3874 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3875 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3876 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3877 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003878 if (mute) {
3879 // FIXME: should not need to double latency if volume could be applied
3880 // immediately by the audioflinger mixer. We must account for the delay
3881 // between now and the next time the audioflinger thread for this output
3882 // will process a buffer (which corresponds to one buffer size,
3883 // usually 1/2 or 1/4 of the latency).
3884 if (muteWaitMs < desc->latency() * 2) {
3885 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003886 }
3887 }
3888 }
3889 }
3890 }
3891 }
3892
Eric Laurent99401132014-05-07 19:48:15 -07003893 // temporary mute output if device selection changes to avoid volume bursts due to
3894 // different per device volumes
3895 if (outputDesc->isActive() && (device != prevDevice)) {
3896 if (muteWaitMs < outputDesc->latency() * 2) {
3897 muteWaitMs = outputDesc->latency() * 2;
3898 }
3899 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3900 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003901 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003902 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003903 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003904 muteWaitMs *2, device);
3905 }
3906 }
3907 }
3908
Eric Laurente552edb2014-03-10 17:42:56 -07003909 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3910 if (muteWaitMs > delayMs) {
3911 muteWaitMs -= delayMs;
3912 usleep(muteWaitMs * 1000);
3913 return muteWaitMs;
3914 }
3915 return 0;
3916}
3917
Eric Laurente0720872014-03-11 09:30:41 -07003918uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003919 audio_devices_t device,
3920 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003921 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003922 audio_patch_handle_t *patchHandle,
3923 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003924{
3925 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003926 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003927 AudioParameter param;
3928 uint32_t muteWaitMs;
3929
3930 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003931 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3932 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003933 return muteWaitMs;
3934 }
3935 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3936 // output profile
3937 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003938 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003939 return 0;
3940 }
3941
3942 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003943 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003944
3945 audio_devices_t prevDevice = outputDesc->mDevice;
3946
3947 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3948
3949 if (device != AUDIO_DEVICE_NONE) {
3950 outputDesc->mDevice = device;
3951 }
3952 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3953
3954 // Do not change the routing if:
3955 // - the requested device is AUDIO_DEVICE_NONE
3956 // - the requested device is the same as current device and force is not specified.
3957 // Doing this check here allows the caller to call setOutputDevice() without conditions
3958 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3959 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3960 return muteWaitMs;
3961 }
3962
3963 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003964
Eric Laurente552edb2014-03-10 17:42:56 -07003965 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003966 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003967 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003968 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003969 DeviceVector deviceList = (address == NULL) ?
3970 mAvailableOutputDevices.getDevicesFromType(device)
3971 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003972 if (!deviceList.isEmpty()) {
3973 struct audio_patch patch;
3974 outputDesc->toAudioPortConfig(&patch.sources[0]);
3975 patch.num_sources = 1;
3976 patch.num_sinks = 0;
3977 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3978 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003979 patch.num_sinks++;
3980 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003981 ssize_t index;
3982 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3983 index = mAudioPatches.indexOfKey(*patchHandle);
3984 } else {
3985 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3986 }
3987 sp< AudioPatch> patchDesc;
3988 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3989 if (index >= 0) {
3990 patchDesc = mAudioPatches.valueAt(index);
3991 afPatchHandle = patchDesc->mAfPatchHandle;
3992 }
3993
Eric Laurent1c333e22014-05-20 10:48:17 -07003994 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 &afPatchHandle,
3996 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003997 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3998 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003999 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004000 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004001 if (index < 0) {
4002 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4003 &patch, mUidCached);
4004 addAudioPatch(patchDesc->mHandle, patchDesc);
4005 } else {
4006 patchDesc->mPatch = patch;
4007 }
4008 patchDesc->mAfPatchHandle = afPatchHandle;
4009 patchDesc->mUid = mUidCached;
4010 if (patchHandle) {
4011 *patchHandle = patchDesc->mHandle;
4012 }
4013 outputDesc->mPatchHandle = patchDesc->mHandle;
4014 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004015 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004016 }
4017 }
4018 }
Eric Laurente552edb2014-03-10 17:42:56 -07004019
4020 // update stream volumes according to new device
4021 applyStreamVolumes(output, device, delayMs);
4022
4023 return muteWaitMs;
4024}
4025
Eric Laurent1c333e22014-05-20 10:48:17 -07004026status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004027 int delayMs,
4028 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004029{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004030 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004031 ssize_t index;
4032 if (patchHandle) {
4033 index = mAudioPatches.indexOfKey(*patchHandle);
4034 } else {
4035 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4036 }
4037 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004038 return INVALID_OPERATION;
4039 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4041 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004042 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4043 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004044 removeAudioPatch(patchDesc->mHandle);
4045 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004046 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004047 return status;
4048}
4049
4050status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4051 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004052 bool force,
4053 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004054{
4055 status_t status = NO_ERROR;
4056
Eric Laurent1f2f2232014-06-02 12:01:23 -07004057 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004058 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4059 inputDesc->mDevice = device;
4060
4061 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4062 if (!deviceList.isEmpty()) {
4063 struct audio_patch patch;
4064 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004065 // AUDIO_SOURCE_HOTWORD is for internal use only:
4066 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004067 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4068 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004069 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4070 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004071 patch.num_sinks = 1;
4072 //only one input device for now
4073 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004074 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004075 ssize_t index;
4076 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4077 index = mAudioPatches.indexOfKey(*patchHandle);
4078 } else {
4079 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4080 }
4081 sp< AudioPatch> patchDesc;
4082 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4083 if (index >= 0) {
4084 patchDesc = mAudioPatches.valueAt(index);
4085 afPatchHandle = patchDesc->mAfPatchHandle;
4086 }
4087
Eric Laurent1c333e22014-05-20 10:48:17 -07004088 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004089 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004090 0);
4091 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004092 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004093 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004094 if (index < 0) {
4095 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4096 &patch, mUidCached);
4097 addAudioPatch(patchDesc->mHandle, patchDesc);
4098 } else {
4099 patchDesc->mPatch = patch;
4100 }
4101 patchDesc->mAfPatchHandle = afPatchHandle;
4102 patchDesc->mUid = mUidCached;
4103 if (patchHandle) {
4104 *patchHandle = patchDesc->mHandle;
4105 }
4106 inputDesc->mPatchHandle = patchDesc->mHandle;
4107 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004108 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004109 }
4110 }
4111 }
4112 return status;
4113}
4114
Eric Laurent6a94d692014-05-20 11:18:06 -07004115status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4116 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004117{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004118 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004119 ssize_t index;
4120 if (patchHandle) {
4121 index = mAudioPatches.indexOfKey(*patchHandle);
4122 } else {
4123 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4124 }
4125 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004126 return INVALID_OPERATION;
4127 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004128 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4129 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004130 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4131 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004132 removeAudioPatch(patchDesc->mHandle);
4133 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004134 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004135 return status;
4136}
4137
4138sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004139 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004140 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004141 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004142 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004143{
4144 // Choose an input profile based on the requested capture parameters: select the first available
4145 // profile supporting all requested parameters.
4146
4147 for (size_t i = 0; i < mHwModules.size(); i++)
4148 {
4149 if (mHwModules[i]->mHandle == 0) {
4150 continue;
4151 }
4152 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4153 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004154 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004155 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004156 if (profile->isCompatibleProfile(device, samplingRate,
4157 &samplingRate /*updatedSamplingRate*/,
4158 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004159 return profile;
4160 }
4161 }
4162 }
4163 return NULL;
4164}
4165
Eric Laurente0720872014-03-11 09:30:41 -07004166audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004167{
4168 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004169 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4170 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004171 switch (inputSource) {
4172 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004173 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004174 device = AUDIO_DEVICE_IN_VOICE_CALL;
4175 break;
4176 }
4177 // FALL THROUGH
4178
4179 case AUDIO_SOURCE_DEFAULT:
4180 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004181 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4182 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4183 break;
4184 }
4185 // FALL THROUGH
4186
Eric Laurente552edb2014-03-10 17:42:56 -07004187 case AUDIO_SOURCE_VOICE_RECOGNITION:
4188 case AUDIO_SOURCE_HOTWORD:
4189 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004190 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004191 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004192 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004193 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004194 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004195 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4196 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004197 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004198 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4199 }
4200 break;
4201 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004202 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004203 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004204 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004205 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4206 }
4207 break;
4208 case AUDIO_SOURCE_VOICE_DOWNLINK:
4209 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004210 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004211 device = AUDIO_DEVICE_IN_VOICE_CALL;
4212 }
4213 break;
4214 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004215 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004216 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4217 }
4218 break;
4219 default:
4220 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4221 break;
4222 }
4223 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4224 return device;
4225}
4226
Eric Laurente0720872014-03-11 09:30:41 -07004227bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004228{
4229 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4230 device &= ~AUDIO_DEVICE_BIT_IN;
4231 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4232 return true;
4233 }
4234 return false;
4235}
4236
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004237bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4238 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4239}
4240
Eric Laurente0720872014-03-11 09:30:41 -07004241audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004242{
4243 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004244 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004245 if ((input_descriptor->mRefCount > 0)
4246 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4247 return mInputs.keyAt(i);
4248 }
4249 }
4250 return 0;
4251}
4252
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004253uint32_t AudioPolicyManager::activeInputsCount() const
4254{
4255 uint32_t count = 0;
4256 for (size_t i = 0; i < mInputs.size(); i++) {
4257 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4258 if (desc->mRefCount > 0) {
4259 return count++;
4260 }
4261 }
4262 return count;
4263}
4264
Eric Laurente552edb2014-03-10 17:42:56 -07004265
Eric Laurente0720872014-03-11 09:30:41 -07004266audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004267{
4268 if (device == AUDIO_DEVICE_NONE) {
4269 // this happens when forcing a route update and no track is active on an output.
4270 // In this case the returned category is not important.
4271 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004272 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004273 // Multiple device selection is either:
4274 // - speaker + one other device: give priority to speaker in this case.
4275 // - one A2DP device + another device: happens with duplicated output. In this case
4276 // retain the device on the A2DP output as the other must not correspond to an active
4277 // selection if not the speaker.
4278 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4279 device = AUDIO_DEVICE_OUT_SPEAKER;
4280 } else {
4281 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4282 }
4283 }
4284
Eric Laurent3b73df72014-03-11 09:06:29 -07004285 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004286 "getDeviceForVolume() invalid device combination: %08x",
4287 device);
4288
4289 return device;
4290}
4291
Eric Laurente0720872014-03-11 09:30:41 -07004292AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004293{
4294 switch(getDeviceForVolume(device)) {
4295 case AUDIO_DEVICE_OUT_EARPIECE:
4296 return DEVICE_CATEGORY_EARPIECE;
4297 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4298 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4299 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4300 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4301 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4302 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4303 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004304 case AUDIO_DEVICE_OUT_LINE:
4305 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4306 /*USB? Remote submix?*/
4307 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004308 case AUDIO_DEVICE_OUT_SPEAKER:
4309 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4310 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004311 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4312 case AUDIO_DEVICE_OUT_USB_DEVICE:
4313 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4314 default:
4315 return DEVICE_CATEGORY_SPEAKER;
4316 }
4317}
4318
Eric Laurente0720872014-03-11 09:30:41 -07004319float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004320 int indexInUi)
4321{
4322 device_category deviceCategory = getDeviceCategory(device);
4323 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4324
4325 // the volume index in the UI is relative to the min and max volume indices for this stream type
4326 int nbSteps = 1 + curve[VOLMAX].mIndex -
4327 curve[VOLMIN].mIndex;
4328 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4329 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4330
4331 // find what part of the curve this index volume belongs to, or if it's out of bounds
4332 int segment = 0;
4333 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4334 return 0.0f;
4335 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4336 segment = 0;
4337 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4338 segment = 1;
4339 } else if (volIdx <= curve[VOLMAX].mIndex) {
4340 segment = 2;
4341 } else { // out of bounds
4342 return 1.0f;
4343 }
4344
4345 // linear interpolation in the attenuation table in dB
4346 float decibels = curve[segment].mDBAttenuation +
4347 ((float)(volIdx - curve[segment].mIndex)) *
4348 ( (curve[segment+1].mDBAttenuation -
4349 curve[segment].mDBAttenuation) /
4350 ((float)(curve[segment+1].mIndex -
4351 curve[segment].mIndex)) );
4352
4353 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4354
4355 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4356 curve[segment].mIndex, volIdx,
4357 curve[segment+1].mIndex,
4358 curve[segment].mDBAttenuation,
4359 decibels,
4360 curve[segment+1].mDBAttenuation,
4361 amplification);
4362
4363 return amplification;
4364}
4365
Eric Laurente0720872014-03-11 09:30:41 -07004366const AudioPolicyManager::VolumeCurvePoint
4367 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004368 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4369};
4370
Eric Laurente0720872014-03-11 09:30:41 -07004371const AudioPolicyManager::VolumeCurvePoint
4372 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004373 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4374};
4375
Eric Laurente0720872014-03-11 09:30:41 -07004376const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004377 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4378 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4379};
4380
4381const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004382 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004383 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4384};
4385
Eric Laurente0720872014-03-11 09:30:41 -07004386const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004387 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004388 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004389};
4390
4391const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004392 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004393 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4394};
4395
Eric Laurente0720872014-03-11 09:30:41 -07004396const AudioPolicyManager::VolumeCurvePoint
4397 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004398 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4399};
4400
4401// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4402// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4403// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4404// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4405
Eric Laurente0720872014-03-11 09:30:41 -07004406const AudioPolicyManager::VolumeCurvePoint
4407 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004408 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4409};
4410
Eric Laurente0720872014-03-11 09:30:41 -07004411const AudioPolicyManager::VolumeCurvePoint
4412 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004413 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4414};
4415
Eric Laurente0720872014-03-11 09:30:41 -07004416const AudioPolicyManager::VolumeCurvePoint
4417 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004418 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4419};
4420
Eric Laurente0720872014-03-11 09:30:41 -07004421const AudioPolicyManager::VolumeCurvePoint
4422 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004423 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4424};
4425
Eric Laurente0720872014-03-11 09:30:41 -07004426const AudioPolicyManager::VolumeCurvePoint
4427 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004428 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4429};
4430
Eric Laurente0720872014-03-11 09:30:41 -07004431const AudioPolicyManager::VolumeCurvePoint
4432 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4433 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004434 { // AUDIO_STREAM_VOICE_CALL
4435 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4436 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004437 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4438 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004439 },
4440 { // AUDIO_STREAM_SYSTEM
4441 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4442 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004443 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4444 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004445 },
4446 { // AUDIO_STREAM_RING
4447 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4448 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004449 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4450 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004451 },
4452 { // AUDIO_STREAM_MUSIC
4453 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4454 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004455 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4456 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004457 },
4458 { // AUDIO_STREAM_ALARM
4459 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4460 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004461 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4462 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004463 },
4464 { // AUDIO_STREAM_NOTIFICATION
4465 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4466 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004467 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4468 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004469 },
4470 { // AUDIO_STREAM_BLUETOOTH_SCO
4471 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4472 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004473 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4474 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004475 },
4476 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4477 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4478 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004479 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4480 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004481 },
4482 { // AUDIO_STREAM_DTMF
4483 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4484 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004485 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4486 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004487 },
4488 { // AUDIO_STREAM_TTS
4489 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4490 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004491 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4492 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004493 },
4494};
4495
Eric Laurente0720872014-03-11 09:30:41 -07004496void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004497{
4498 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4499 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4500 mStreams[i].mVolumeCurve[j] =
4501 sVolumeProfiles[i][j];
4502 }
4503 }
4504
4505 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4506 if (mSpeakerDrcEnabled) {
4507 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4508 sDefaultSystemVolumeCurveDrc;
4509 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4510 sSpeakerSonificationVolumeCurveDrc;
4511 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4512 sSpeakerSonificationVolumeCurveDrc;
4513 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4514 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004515 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4516 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004517 }
4518}
4519
Eric Laurente0720872014-03-11 09:30:41 -07004520float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004521 int index,
4522 audio_io_handle_t output,
4523 audio_devices_t device)
4524{
4525 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004526 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004527 StreamDescriptor &streamDesc = mStreams[stream];
4528
4529 if (device == AUDIO_DEVICE_NONE) {
4530 device = outputDesc->device();
4531 }
4532
Eric Laurente552edb2014-03-10 17:42:56 -07004533 volume = volIndexToAmpl(device, streamDesc, index);
4534
4535 // if a headset is connected, apply the following rules to ring tones and notifications
4536 // to avoid sound level bursts in user's ears:
4537 // - always attenuate ring tones and notifications volume by 6dB
4538 // - if music is playing, always limit the volume to current music volume,
4539 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004540 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004541 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4542 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4543 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4544 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4545 ((stream_strategy == STRATEGY_SONIFICATION)
4546 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004547 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004548 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004549 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004550 streamDesc.mCanBeMuted) {
4551 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4552 // when the phone is ringing we must consider that music could have been paused just before
4553 // by the music application and behave as if music was active if the last music track was
4554 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004555 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004556 mLimitRingtoneVolume) {
4557 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004558 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4559 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004560 output,
4561 musicDevice);
4562 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4563 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4564 if (volume > minVol) {
4565 volume = minVol;
4566 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4567 }
4568 }
4569 }
4570
4571 return volume;
4572}
4573
Eric Laurente0720872014-03-11 09:30:41 -07004574status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004575 int index,
4576 audio_io_handle_t output,
4577 audio_devices_t device,
4578 int delayMs,
4579 bool force)
4580{
4581
4582 // do not change actual stream volume if the stream is muted
4583 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4584 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4585 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4586 return NO_ERROR;
4587 }
4588
4589 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004590 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4591 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4592 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4593 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004594 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004595 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004596 return INVALID_OPERATION;
4597 }
4598
4599 float volume = computeVolume(stream, index, output, device);
4600 // We actually change the volume if:
4601 // - the float value returned by computeVolume() changed
4602 // - the force flag is set
4603 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4604 force) {
4605 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4606 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4607 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4608 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004609 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4610 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004611 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004612 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004613 }
4614
Eric Laurent3b73df72014-03-11 09:06:29 -07004615 if (stream == AUDIO_STREAM_VOICE_CALL ||
4616 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004617 float voiceVolume;
4618 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004619 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004620 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4621 } else {
4622 voiceVolume = 1.0;
4623 }
4624
4625 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4626 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4627 mLastVoiceVolume = voiceVolume;
4628 }
4629 }
4630
4631 return NO_ERROR;
4632}
4633
Eric Laurente0720872014-03-11 09:30:41 -07004634void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004635 audio_devices_t device,
4636 int delayMs,
4637 bool force)
4638{
4639 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4640
Eric Laurent3b73df72014-03-11 09:06:29 -07004641 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4642 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004643 mStreams[stream].getVolumeIndex(device),
4644 output,
4645 device,
4646 delayMs,
4647 force);
4648 }
4649}
4650
Eric Laurente0720872014-03-11 09:30:41 -07004651void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004652 bool on,
4653 audio_io_handle_t output,
4654 int delayMs,
4655 audio_devices_t device)
4656{
4657 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004658 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4659 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4660 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 }
4662 }
4663}
4664
Eric Laurente0720872014-03-11 09:30:41 -07004665void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004666 bool on,
4667 audio_io_handle_t output,
4668 int delayMs,
4669 audio_devices_t device)
4670{
4671 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004672 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004673 if (device == AUDIO_DEVICE_NONE) {
4674 device = outputDesc->device();
4675 }
4676
4677 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4678 stream, on, output, outputDesc->mMuteCount[stream], device);
4679
4680 if (on) {
4681 if (outputDesc->mMuteCount[stream] == 0) {
4682 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004683 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4684 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004685 checkAndSetVolume(stream, 0, output, device, delayMs);
4686 }
4687 }
4688 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4689 outputDesc->mMuteCount[stream]++;
4690 } else {
4691 if (outputDesc->mMuteCount[stream] == 0) {
4692 ALOGV("setStreamMute() unmuting non muted stream!");
4693 return;
4694 }
4695 if (--outputDesc->mMuteCount[stream] == 0) {
4696 checkAndSetVolume(stream,
4697 streamDesc.getVolumeIndex(device),
4698 output,
4699 device,
4700 delayMs);
4701 }
4702 }
4703}
4704
Eric Laurente0720872014-03-11 09:30:41 -07004705void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004706 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004707{
4708 // if the stream pertains to sonification strategy and we are in call we must
4709 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4710 // in the device used for phone strategy and play the tone if the selected device does not
4711 // interfere with the device used for phone strategy
4712 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4713 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004714 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004715 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4716 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004717 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004718 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4719 stream, starting, outputDesc->mDevice, stateChange);
4720 if (outputDesc->mRefCount[stream]) {
4721 int muteCount = 1;
4722 if (stateChange) {
4723 muteCount = outputDesc->mRefCount[stream];
4724 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004725 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004726 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4727 for (int i = 0; i < muteCount; i++) {
4728 setStreamMute(stream, starting, mPrimaryOutput);
4729 }
4730 } else {
4731 ALOGV("handleIncallSonification() high visibility");
4732 if (outputDesc->device() &
4733 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4734 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4735 for (int i = 0; i < muteCount; i++) {
4736 setStreamMute(stream, starting, mPrimaryOutput);
4737 }
4738 }
4739 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004740 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4741 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004742 } else {
4743 mpClientInterface->stopTone();
4744 }
4745 }
4746 }
4747 }
4748}
4749
Eric Laurente0720872014-03-11 09:30:41 -07004750bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004751{
4752 return isStateInCall(mPhoneState);
4753}
4754
Eric Laurente0720872014-03-11 09:30:41 -07004755bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004756 return ((state == AUDIO_MODE_IN_CALL) ||
4757 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004758}
4759
Eric Laurente0720872014-03-11 09:30:41 -07004760uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004761{
4762 return MAX_EFFECTS_CPU_LOAD;
4763}
4764
Eric Laurente0720872014-03-11 09:30:41 -07004765uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004766{
4767 return MAX_EFFECTS_MEMORY;
4768}
4769
Eric Laurent6a94d692014-05-20 11:18:06 -07004770
Eric Laurente552edb2014-03-10 17:42:56 -07004771// --- AudioOutputDescriptor class implementation
4772
Eric Laurente0720872014-03-11 09:30:41 -07004773AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004774 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004775 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004776 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004777 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4778{
4779 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004780 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004781 mRefCount[i] = 0;
4782 mCurVolume[i] = -1.0;
4783 mMuteCount[i] = 0;
4784 mStopTime[i] = 0;
4785 }
4786 for (int i = 0; i < NUM_STRATEGIES; i++) {
4787 mStrategyMutedByDevice[i] = false;
4788 }
4789 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004790 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004791 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004792 mSamplingRate = profile->pickSamplingRate();
4793 mFormat = profile->pickFormat();
4794 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004795 if (profile->mGains.size() > 0) {
4796 profile->mGains[0]->getDefaultConfig(&mGain);
4797 }
Eric Laurente552edb2014-03-10 17:42:56 -07004798 }
4799}
4800
Eric Laurente0720872014-03-11 09:30:41 -07004801audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004802{
4803 if (isDuplicated()) {
4804 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4805 } else {
4806 return mDevice;
4807 }
4808}
4809
Eric Laurente0720872014-03-11 09:30:41 -07004810uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004811{
4812 if (isDuplicated()) {
4813 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4814 } else {
4815 return mLatency;
4816 }
4817}
4818
Eric Laurente0720872014-03-11 09:30:41 -07004819bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004820 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004821{
4822 if (isDuplicated()) {
4823 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4824 } else if (outputDesc->isDuplicated()){
4825 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4826 } else {
4827 return (mProfile->mModule == outputDesc->mProfile->mModule);
4828 }
4829}
4830
Eric Laurente0720872014-03-11 09:30:41 -07004831void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004832 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004833{
4834 // forward usage count change to attached outputs
4835 if (isDuplicated()) {
4836 mOutput1->changeRefCount(stream, delta);
4837 mOutput2->changeRefCount(stream, delta);
4838 }
4839 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004840 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4841 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004842 mRefCount[stream] = 0;
4843 return;
4844 }
4845 mRefCount[stream] += delta;
4846 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4847}
4848
Eric Laurente0720872014-03-11 09:30:41 -07004849audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004850{
4851 if (isDuplicated()) {
4852 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4853 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004854 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004855 }
4856}
4857
Eric Laurente0720872014-03-11 09:30:41 -07004858bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004859{
4860 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4861}
4862
Eric Laurente0720872014-03-11 09:30:41 -07004863bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004864 uint32_t inPastMs,
4865 nsecs_t sysTime) const
4866{
4867 if ((sysTime == 0) && (inPastMs != 0)) {
4868 sysTime = systemTime();
4869 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004870 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4871 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004872 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004873 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004874 return true;
4875 }
4876 }
4877 return false;
4878}
4879
Eric Laurente0720872014-03-11 09:30:41 -07004880bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004881 uint32_t inPastMs,
4882 nsecs_t sysTime) const
4883{
4884 if (mRefCount[stream] != 0) {
4885 return true;
4886 }
4887 if (inPastMs == 0) {
4888 return false;
4889 }
4890 if (sysTime == 0) {
4891 sysTime = systemTime();
4892 }
4893 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4894 return true;
4895 }
4896 return false;
4897}
4898
Eric Laurent1c333e22014-05-20 10:48:17 -07004899void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 struct audio_port_config *dstConfig,
4901 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004902{
Eric Laurent84c70242014-06-23 08:46:27 -07004903 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4904
Eric Laurent1f2f2232014-06-02 12:01:23 -07004905 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4906 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4907 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004908 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004909 }
4910 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4911
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 dstConfig->id = mId;
4913 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4914 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004915 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4916 dstConfig->ext.mix.handle = mIoHandle;
4917 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004918}
4919
4920void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4921 struct audio_port *port) const
4922{
Eric Laurent84c70242014-06-23 08:46:27 -07004923 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004924 mProfile->toAudioPort(port);
4925 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 toAudioPortConfig(&port->active_config);
4927 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004928 port->ext.mix.handle = mIoHandle;
4929 port->ext.mix.latency_class =
4930 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4931}
Eric Laurente552edb2014-03-10 17:42:56 -07004932
Eric Laurente0720872014-03-11 09:30:41 -07004933status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004934{
4935 const size_t SIZE = 256;
4936 char buffer[SIZE];
4937 String8 result;
4938
4939 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4940 result.append(buffer);
4941 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4942 result.append(buffer);
4943 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4944 result.append(buffer);
4945 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4946 result.append(buffer);
4947 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4948 result.append(buffer);
4949 snprintf(buffer, SIZE, " Devices %08x\n", device());
4950 result.append(buffer);
4951 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4952 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004953 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4954 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4955 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004956 result.append(buffer);
4957 }
4958 write(fd, result.string(), result.size());
4959
4960 return NO_ERROR;
4961}
4962
4963// --- AudioInputDescriptor class implementation
4964
Eric Laurent1c333e22014-05-20 10:48:17 -07004965AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004966 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004967 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004968 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004969{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004970 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004971 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004972 mSamplingRate = profile->pickSamplingRate();
4973 mFormat = profile->pickFormat();
4974 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004975 if (profile->mGains.size() > 0) {
4976 profile->mGains[0]->getDefaultConfig(&mGain);
4977 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004978 }
Eric Laurente552edb2014-03-10 17:42:56 -07004979}
4980
Eric Laurent1c333e22014-05-20 10:48:17 -07004981void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 struct audio_port_config *dstConfig,
4983 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004984{
Eric Laurent84c70242014-06-23 08:46:27 -07004985 ALOG_ASSERT(mProfile != 0,
4986 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004987 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4988 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4989 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004990 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004991 }
4992
4993 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4994
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 dstConfig->id = mId;
4996 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4997 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004998 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4999 dstConfig->ext.mix.handle = mIoHandle;
5000 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005001}
5002
5003void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5004 struct audio_port *port) const
5005{
Eric Laurent84c70242014-06-23 08:46:27 -07005006 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5007
Eric Laurent1c333e22014-05-20 10:48:17 -07005008 mProfile->toAudioPort(port);
5009 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 toAudioPortConfig(&port->active_config);
5011 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005012 port->ext.mix.handle = mIoHandle;
5013 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5014}
5015
Eric Laurente0720872014-03-11 09:30:41 -07005016status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005017{
5018 const size_t SIZE = 256;
5019 char buffer[SIZE];
5020 String8 result;
5021
5022 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5023 result.append(buffer);
5024 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5025 result.append(buffer);
5026 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5027 result.append(buffer);
5028 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5029 result.append(buffer);
5030 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5031 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005032 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5033 result.append(buffer);
5034
Eric Laurente552edb2014-03-10 17:42:56 -07005035 write(fd, result.string(), result.size());
5036
5037 return NO_ERROR;
5038}
5039
5040// --- StreamDescriptor class implementation
5041
Eric Laurente0720872014-03-11 09:30:41 -07005042AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005043 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5044{
5045 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5046}
5047
Eric Laurente0720872014-03-11 09:30:41 -07005048int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005049{
Eric Laurente0720872014-03-11 09:30:41 -07005050 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005051 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5052 if (mIndexCur.indexOfKey(device) < 0) {
5053 device = AUDIO_DEVICE_OUT_DEFAULT;
5054 }
5055 return mIndexCur.valueFor(device);
5056}
5057
Eric Laurente0720872014-03-11 09:30:41 -07005058void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005059{
5060 const size_t SIZE = 256;
5061 char buffer[SIZE];
5062 String8 result;
5063
5064 snprintf(buffer, SIZE, "%s %02d %02d ",
5065 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5066 result.append(buffer);
5067 for (size_t i = 0; i < mIndexCur.size(); i++) {
5068 snprintf(buffer, SIZE, "%04x : %02d, ",
5069 mIndexCur.keyAt(i),
5070 mIndexCur.valueAt(i));
5071 result.append(buffer);
5072 }
5073 result.append("\n");
5074
5075 write(fd, result.string(), result.size());
5076}
5077
5078// --- EffectDescriptor class implementation
5079
Eric Laurente0720872014-03-11 09:30:41 -07005080status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005081{
5082 const size_t SIZE = 256;
5083 char buffer[SIZE];
5084 String8 result;
5085
5086 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5087 result.append(buffer);
5088 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5089 result.append(buffer);
5090 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5091 result.append(buffer);
5092 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5093 result.append(buffer);
5094 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5095 result.append(buffer);
5096 write(fd, result.string(), result.size());
5097
5098 return NO_ERROR;
5099}
5100
Eric Laurent1c333e22014-05-20 10:48:17 -07005101// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005102
Eric Laurente0720872014-03-11 09:30:41 -07005103AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005104 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5105 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005106{
5107}
5108
Eric Laurente0720872014-03-11 09:30:41 -07005109AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005110{
5111 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005112 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005113 }
5114 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005115 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005116 }
5117 free((void *)mName);
5118}
5119
Eric Laurent1afeecb2014-05-14 08:52:28 -07005120status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5121{
5122 cnode *node = root->first_child;
5123
5124 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5125
5126 while (node) {
5127 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5128 profile->loadSamplingRates((char *)node->value);
5129 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5130 profile->loadFormats((char *)node->value);
5131 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5132 profile->loadInChannels((char *)node->value);
5133 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5134 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5135 mDeclaredDevices);
5136 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5137 profile->loadGains(node);
5138 }
5139 node = node->next;
5140 }
5141 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5142 "loadInput() invalid supported devices");
5143 ALOGW_IF(profile->mChannelMasks.size() == 0,
5144 "loadInput() invalid supported channel masks");
5145 ALOGW_IF(profile->mSamplingRates.size() == 0,
5146 "loadInput() invalid supported sampling rates");
5147 ALOGW_IF(profile->mFormats.size() == 0,
5148 "loadInput() invalid supported formats");
5149 if (!profile->mSupportedDevices.isEmpty() &&
5150 (profile->mChannelMasks.size() != 0) &&
5151 (profile->mSamplingRates.size() != 0) &&
5152 (profile->mFormats.size() != 0)) {
5153
5154 ALOGV("loadInput() adding input Supported Devices %04x",
5155 profile->mSupportedDevices.types());
5156
5157 mInputProfiles.add(profile);
5158 return NO_ERROR;
5159 } else {
5160 return BAD_VALUE;
5161 }
5162}
5163
5164status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5165{
5166 cnode *node = root->first_child;
5167
5168 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5169
5170 while (node) {
5171 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5172 profile->loadSamplingRates((char *)node->value);
5173 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5174 profile->loadFormats((char *)node->value);
5175 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5176 profile->loadOutChannels((char *)node->value);
5177 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5178 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5179 mDeclaredDevices);
5180 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5181 profile->mFlags = parseFlagNames((char *)node->value);
5182 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5183 profile->loadGains(node);
5184 }
5185 node = node->next;
5186 }
5187 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5188 "loadOutput() invalid supported devices");
5189 ALOGW_IF(profile->mChannelMasks.size() == 0,
5190 "loadOutput() invalid supported channel masks");
5191 ALOGW_IF(profile->mSamplingRates.size() == 0,
5192 "loadOutput() invalid supported sampling rates");
5193 ALOGW_IF(profile->mFormats.size() == 0,
5194 "loadOutput() invalid supported formats");
5195 if (!profile->mSupportedDevices.isEmpty() &&
5196 (profile->mChannelMasks.size() != 0) &&
5197 (profile->mSamplingRates.size() != 0) &&
5198 (profile->mFormats.size() != 0)) {
5199
5200 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5201 profile->mSupportedDevices.types(), profile->mFlags);
5202
5203 mOutputProfiles.add(profile);
5204 return NO_ERROR;
5205 } else {
5206 return BAD_VALUE;
5207 }
5208}
5209
5210status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5211{
5212 cnode *node = root->first_child;
5213
5214 audio_devices_t type = AUDIO_DEVICE_NONE;
5215 while (node) {
5216 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5217 type = parseDeviceNames((char *)node->value);
5218 break;
5219 }
5220 node = node->next;
5221 }
5222 if (type == AUDIO_DEVICE_NONE ||
5223 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5224 ALOGW("loadDevice() bad type %08x", type);
5225 return BAD_VALUE;
5226 }
5227 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5228 deviceDesc->mModule = this;
5229
5230 node = root->first_child;
5231 while (node) {
5232 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5233 deviceDesc->mAddress = String8((char *)node->value);
5234 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5235 if (audio_is_input_device(type)) {
5236 deviceDesc->loadInChannels((char *)node->value);
5237 } else {
5238 deviceDesc->loadOutChannels((char *)node->value);
5239 }
5240 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5241 deviceDesc->loadGains(node);
5242 }
5243 node = node->next;
5244 }
5245
5246 ALOGV("loadDevice() adding device name %s type %08x address %s",
5247 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5248
5249 mDeclaredDevices.add(deviceDesc);
5250
5251 return NO_ERROR;
5252}
5253
Eric Laurente0720872014-03-11 09:30:41 -07005254void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005255{
5256 const size_t SIZE = 256;
5257 char buffer[SIZE];
5258 String8 result;
5259
5260 snprintf(buffer, SIZE, " - name: %s\n", mName);
5261 result.append(buffer);
5262 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5263 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005264 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5265 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005266 write(fd, result.string(), result.size());
5267 if (mOutputProfiles.size()) {
5268 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5269 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005270 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005271 write(fd, buffer, strlen(buffer));
5272 mOutputProfiles[i]->dump(fd);
5273 }
5274 }
5275 if (mInputProfiles.size()) {
5276 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5277 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005278 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005279 write(fd, buffer, strlen(buffer));
5280 mInputProfiles[i]->dump(fd);
5281 }
5282 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005283 if (mDeclaredDevices.size()) {
5284 write(fd, " - devices:\n", strlen(" - devices:\n"));
5285 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5286 mDeclaredDevices[i]->dump(fd, 4, i);
5287 }
5288 }
Eric Laurente552edb2014-03-10 17:42:56 -07005289}
5290
Eric Laurent1c333e22014-05-20 10:48:17 -07005291// --- AudioPort class implementation
5292
Eric Laurenta121f902014-06-03 13:32:54 -07005293
5294AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5295 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005296 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005297{
5298 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5299 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5300}
5301
Eric Laurent1c333e22014-05-20 10:48:17 -07005302void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5303{
5304 port->role = mRole;
5305 port->type = mType;
5306 unsigned int i;
5307 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5308 port->sample_rates[i] = mSamplingRates[i];
5309 }
5310 port->num_sample_rates = i;
5311 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5312 port->channel_masks[i] = mChannelMasks[i];
5313 }
5314 port->num_channel_masks = i;
5315 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5316 port->formats[i] = mFormats[i];
5317 }
5318 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005319
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005320 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005321
5322 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5323 port->gains[i] = mGains[i]->mGain;
5324 }
5325 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005326}
5327
5328
5329void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5330{
5331 char *str = strtok(name, "|");
5332
5333 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5334 // rates should be read from the output stream after it is opened for the first time
5335 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5336 mSamplingRates.add(0);
5337 return;
5338 }
5339
5340 while (str != NULL) {
5341 uint32_t rate = atoi(str);
5342 if (rate != 0) {
5343 ALOGV("loadSamplingRates() adding rate %d", rate);
5344 mSamplingRates.add(rate);
5345 }
5346 str = strtok(NULL, "|");
5347 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005348}
5349
5350void AudioPolicyManager::AudioPort::loadFormats(char *name)
5351{
5352 char *str = strtok(name, "|");
5353
5354 // by convention, "0' in the first entry in mFormats indicates the supported formats
5355 // should be read from the output stream after it is opened for the first time
5356 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5357 mFormats.add(AUDIO_FORMAT_DEFAULT);
5358 return;
5359 }
5360
5361 while (str != NULL) {
5362 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5363 ARRAY_SIZE(sFormatNameToEnumTable),
5364 str);
5365 if (format != AUDIO_FORMAT_DEFAULT) {
5366 mFormats.add(format);
5367 }
5368 str = strtok(NULL, "|");
5369 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005370}
5371
5372void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5373{
5374 const char *str = strtok(name, "|");
5375
5376 ALOGV("loadInChannels() %s", name);
5377
5378 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5379 mChannelMasks.add(0);
5380 return;
5381 }
5382
5383 while (str != NULL) {
5384 audio_channel_mask_t channelMask =
5385 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5386 ARRAY_SIZE(sInChannelsNameToEnumTable),
5387 str);
5388 if (channelMask != 0) {
5389 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5390 mChannelMasks.add(channelMask);
5391 }
5392 str = strtok(NULL, "|");
5393 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005394}
5395
5396void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5397{
5398 const char *str = strtok(name, "|");
5399
5400 ALOGV("loadOutChannels() %s", name);
5401
5402 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5403 // masks should be read from the output stream after it is opened for the first time
5404 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5405 mChannelMasks.add(0);
5406 return;
5407 }
5408
5409 while (str != NULL) {
5410 audio_channel_mask_t channelMask =
5411 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5412 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5413 str);
5414 if (channelMask != 0) {
5415 mChannelMasks.add(channelMask);
5416 }
5417 str = strtok(NULL, "|");
5418 }
5419 return;
5420}
5421
Eric Laurent1afeecb2014-05-14 08:52:28 -07005422audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5423{
5424 const char *str = strtok(name, "|");
5425
5426 ALOGV("loadGainMode() %s", name);
5427 audio_gain_mode_t mode = 0;
5428 while (str != NULL) {
5429 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5430 ARRAY_SIZE(sGainModeNameToEnumTable),
5431 str);
5432 str = strtok(NULL, "|");
5433 }
5434 return mode;
5435}
5436
Eric Laurenta121f902014-06-03 13:32:54 -07005437void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005438{
5439 cnode *node = root->first_child;
5440
Eric Laurenta121f902014-06-03 13:32:54 -07005441 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005442
5443 while (node) {
5444 if (strcmp(node->name, GAIN_MODE) == 0) {
5445 gain->mGain.mode = loadGainMode((char *)node->value);
5446 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005447 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005448 gain->mGain.channel_mask =
5449 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5450 ARRAY_SIZE(sInChannelsNameToEnumTable),
5451 (char *)node->value);
5452 } else {
5453 gain->mGain.channel_mask =
5454 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5455 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5456 (char *)node->value);
5457 }
5458 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5459 gain->mGain.min_value = atoi((char *)node->value);
5460 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5461 gain->mGain.max_value = atoi((char *)node->value);
5462 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5463 gain->mGain.default_value = atoi((char *)node->value);
5464 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5465 gain->mGain.step_value = atoi((char *)node->value);
5466 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5467 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5468 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5469 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5470 }
5471 node = node->next;
5472 }
5473
5474 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5475 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5476
5477 if (gain->mGain.mode == 0) {
5478 return;
5479 }
5480 mGains.add(gain);
5481}
5482
5483void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5484{
5485 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005486 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005487 while (node) {
5488 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005489 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005490 node = node->next;
5491 }
5492}
5493
Glenn Kastencbd48022014-07-24 13:46:44 -07005494status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005495{
5496 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5497 if (mSamplingRates[i] == samplingRate) {
5498 return NO_ERROR;
5499 }
5500 }
5501 return BAD_VALUE;
5502}
5503
Glenn Kastencbd48022014-07-24 13:46:44 -07005504status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5505 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005506{
Glenn Kastencbd48022014-07-24 13:46:44 -07005507 // Search for the closest supported sampling rate that is above (preferred)
5508 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5509 // The sampling rates do not need to be sorted in ascending order.
5510 ssize_t maxBelow = -1;
5511 ssize_t minAbove = -1;
5512 uint32_t candidate;
5513 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5514 candidate = mSamplingRates[i];
5515 if (candidate == samplingRate) {
5516 if (updatedSamplingRate != NULL) {
5517 *updatedSamplingRate = candidate;
5518 }
5519 return NO_ERROR;
5520 }
5521 // candidate < desired
5522 if (candidate < samplingRate) {
5523 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5524 maxBelow = i;
5525 }
5526 // candidate > desired
5527 } else {
5528 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5529 minAbove = i;
5530 }
5531 }
5532 }
5533 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5534 // TODO Move these assumptions out.
5535 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5536 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5537 // due to approximation by an int32_t of the
5538 // phase increments
5539 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5540 if (minAbove >= 0) {
5541 candidate = mSamplingRates[minAbove];
5542 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5543 if (updatedSamplingRate != NULL) {
5544 *updatedSamplingRate = candidate;
5545 }
5546 return NO_ERROR;
5547 }
5548 }
5549 // But if we have to up-sample from a lower sampling rate, that's OK.
5550 if (maxBelow >= 0) {
5551 candidate = mSamplingRates[maxBelow];
5552 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5553 if (updatedSamplingRate != NULL) {
5554 *updatedSamplingRate = candidate;
5555 }
5556 return NO_ERROR;
5557 }
5558 }
5559 // leave updatedSamplingRate unmodified
5560 return BAD_VALUE;
5561}
5562
5563status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5564{
5565 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005566 if (mChannelMasks[i] == channelMask) {
5567 return NO_ERROR;
5568 }
5569 }
5570 return BAD_VALUE;
5571}
5572
Glenn Kastencbd48022014-07-24 13:46:44 -07005573status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5574 const
5575{
5576 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5577 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5578 // FIXME Does not handle multi-channel automatic conversions yet
5579 audio_channel_mask_t supported = mChannelMasks[i];
5580 if (supported == channelMask) {
5581 return NO_ERROR;
5582 }
5583 if (isRecordThread) {
5584 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5585 // FIXME Abstract this out to a table.
5586 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5587 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5588 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5589 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5590 return NO_ERROR;
5591 }
5592 }
5593 }
5594 return BAD_VALUE;
5595}
5596
Eric Laurenta121f902014-06-03 13:32:54 -07005597status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5598{
5599 for (size_t i = 0; i < mFormats.size(); i ++) {
5600 if (mFormats[i] == format) {
5601 return NO_ERROR;
5602 }
5603 }
5604 return BAD_VALUE;
5605}
5606
Eric Laurent1e693b52014-07-09 15:03:28 -07005607
5608uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5609{
5610 // special case for uninitialized dynamic profile
5611 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5612 return 0;
5613 }
5614
5615 uint32_t samplingRate = 0;
5616 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5617
5618 // For mixed output and inputs, use max mixer sampling rates. Do not
5619 // limit sampling rate otherwise
5620 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5621 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5622 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5623 maxRate = UINT_MAX;
5624 }
5625 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5626 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5627 samplingRate = mSamplingRates[i];
5628 }
5629 }
5630 return samplingRate;
5631}
5632
5633audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5634{
5635 // special case for uninitialized dynamic profile
5636 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5637 return AUDIO_CHANNEL_NONE;
5638 }
5639
5640 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5641 uint32_t channelCount = 0;
5642 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5643
5644 // For mixed output and inputs, use max mixer channel count. Do not
5645 // limit channel count otherwise
5646 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5647 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5648 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5649 maxCount = UINT_MAX;
5650 }
5651 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5652 uint32_t cnlCount;
5653 if (mUseInChannelMask) {
5654 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5655 } else {
5656 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5657 }
5658 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5659 channelMask = mChannelMasks[i];
5660 }
5661 }
5662 return channelMask;
5663}
5664
Andy Hung9a605382014-07-28 16:16:31 -07005665/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005666const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5667 AUDIO_FORMAT_DEFAULT,
5668 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005669 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005670 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005671 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005672 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005673};
5674
5675int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5676 audio_format_t format2)
5677{
5678 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5679 // compressed format and better than any PCM format. This is by design of pickFormat()
5680 if (!audio_is_linear_pcm(format1)) {
5681 if (!audio_is_linear_pcm(format2)) {
5682 return 0;
5683 }
5684 return 1;
5685 }
5686 if (!audio_is_linear_pcm(format2)) {
5687 return -1;
5688 }
5689
5690 int index1 = -1, index2 = -1;
5691 for (size_t i = 0;
5692 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5693 i ++) {
5694 if (sPcmFormatCompareTable[i] == format1) {
5695 index1 = i;
5696 }
5697 if (sPcmFormatCompareTable[i] == format2) {
5698 index2 = i;
5699 }
5700 }
5701 // format1 not found => index1 < 0 => format2 > format1
5702 // format2 not found => index2 < 0 => format2 < format1
5703 return index1 - index2;
5704}
5705
5706audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5707{
5708 // special case for uninitialized dynamic profile
5709 if (mFormats.size() == 1 && mFormats[0] == 0) {
5710 return AUDIO_FORMAT_DEFAULT;
5711 }
5712
5713 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005714 audio_format_t bestFormat =
5715 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5716 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005717 // For mixed output and inputs, use best mixer output format. Do not
5718 // limit format otherwise
5719 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5720 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005721 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005722 bestFormat = AUDIO_FORMAT_INVALID;
5723 }
5724
5725 for (size_t i = 0; i < mFormats.size(); i ++) {
5726 if ((compareFormats(mFormats[i], format) > 0) &&
5727 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5728 format = mFormats[i];
5729 }
5730 }
5731 return format;
5732}
5733
Eric Laurenta121f902014-06-03 13:32:54 -07005734status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5735 int index) const
5736{
5737 if (index < 0 || (size_t)index >= mGains.size()) {
5738 return BAD_VALUE;
5739 }
5740 return mGains[index]->checkConfig(gainConfig);
5741}
5742
Eric Laurent1afeecb2014-05-14 08:52:28 -07005743void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5744{
5745 const size_t SIZE = 256;
5746 char buffer[SIZE];
5747 String8 result;
5748
5749 if (mName.size() != 0) {
5750 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5751 result.append(buffer);
5752 }
5753
5754 if (mSamplingRates.size() != 0) {
5755 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5756 result.append(buffer);
5757 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005758 if (i == 0 && mSamplingRates[i] == 0) {
5759 snprintf(buffer, SIZE, "Dynamic");
5760 } else {
5761 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5762 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005763 result.append(buffer);
5764 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5765 }
5766 result.append("\n");
5767 }
5768
5769 if (mChannelMasks.size() != 0) {
5770 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5771 result.append(buffer);
5772 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005773 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5774
5775 if (i == 0 && mChannelMasks[i] == 0) {
5776 snprintf(buffer, SIZE, "Dynamic");
5777 } else {
5778 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5779 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005780 result.append(buffer);
5781 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5782 }
5783 result.append("\n");
5784 }
5785
5786 if (mFormats.size() != 0) {
5787 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5788 result.append(buffer);
5789 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005790 const char *formatStr = enumToString(sFormatNameToEnumTable,
5791 ARRAY_SIZE(sFormatNameToEnumTable),
5792 mFormats[i]);
5793 if (i == 0 && strcmp(formatStr, "") == 0) {
5794 snprintf(buffer, SIZE, "Dynamic");
5795 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005796 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07005797 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005798 result.append(buffer);
5799 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5800 }
5801 result.append("\n");
5802 }
5803 write(fd, result.string(), result.size());
5804 if (mGains.size() != 0) {
5805 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5806 write(fd, buffer, strlen(buffer) + 1);
5807 result.append(buffer);
5808 for (size_t i = 0; i < mGains.size(); i++) {
5809 mGains[i]->dump(fd, spaces + 2, i);
5810 }
5811 }
5812}
5813
5814// --- AudioGain class implementation
5815
Eric Laurenta121f902014-06-03 13:32:54 -07005816AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005817{
Eric Laurenta121f902014-06-03 13:32:54 -07005818 mIndex = index;
5819 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005820 memset(&mGain, 0, sizeof(struct audio_gain));
5821}
5822
Eric Laurenta121f902014-06-03 13:32:54 -07005823void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5824{
5825 config->index = mIndex;
5826 config->mode = mGain.mode;
5827 config->channel_mask = mGain.channel_mask;
5828 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5829 config->values[0] = mGain.default_value;
5830 } else {
5831 uint32_t numValues;
5832 if (mUseInChannelMask) {
5833 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5834 } else {
5835 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5836 }
5837 for (size_t i = 0; i < numValues; i++) {
5838 config->values[i] = mGain.default_value;
5839 }
5840 }
5841 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5842 config->ramp_duration_ms = mGain.min_ramp_ms;
5843 }
5844}
5845
5846status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5847{
5848 if ((config->mode & ~mGain.mode) != 0) {
5849 return BAD_VALUE;
5850 }
5851 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5852 if ((config->values[0] < mGain.min_value) ||
5853 (config->values[0] > mGain.max_value)) {
5854 return BAD_VALUE;
5855 }
5856 } else {
5857 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5858 return BAD_VALUE;
5859 }
5860 uint32_t numValues;
5861 if (mUseInChannelMask) {
5862 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5863 } else {
5864 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5865 }
5866 for (size_t i = 0; i < numValues; i++) {
5867 if ((config->values[i] < mGain.min_value) ||
5868 (config->values[i] > mGain.max_value)) {
5869 return BAD_VALUE;
5870 }
5871 }
5872 }
5873 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5874 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5875 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5876 return BAD_VALUE;
5877 }
5878 }
5879 return NO_ERROR;
5880}
5881
Eric Laurent1afeecb2014-05-14 08:52:28 -07005882void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5883{
5884 const size_t SIZE = 256;
5885 char buffer[SIZE];
5886 String8 result;
5887
5888 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5889 result.append(buffer);
5890 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5891 result.append(buffer);
5892 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5893 result.append(buffer);
5894 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5895 result.append(buffer);
5896 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5897 result.append(buffer);
5898 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5899 result.append(buffer);
5900 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5901 result.append(buffer);
5902 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5903 result.append(buffer);
5904 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5905 result.append(buffer);
5906
5907 write(fd, result.string(), result.size());
5908}
5909
Eric Laurent1f2f2232014-06-02 12:01:23 -07005910// --- AudioPortConfig class implementation
5911
5912AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5913{
5914 mSamplingRate = 0;
5915 mChannelMask = AUDIO_CHANNEL_NONE;
5916 mFormat = AUDIO_FORMAT_INVALID;
5917 mGain.index = -1;
5918}
5919
Eric Laurenta121f902014-06-03 13:32:54 -07005920status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5921 const struct audio_port_config *config,
5922 struct audio_port_config *backupConfig)
5923{
5924 struct audio_port_config localBackupConfig;
5925 status_t status = NO_ERROR;
5926
5927 localBackupConfig.config_mask = config->config_mask;
5928 toAudioPortConfig(&localBackupConfig);
5929
5930 if (mAudioPort == 0) {
5931 status = NO_INIT;
5932 goto exit;
5933 }
5934 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005935 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005936 if (status != NO_ERROR) {
5937 goto exit;
5938 }
5939 mSamplingRate = config->sample_rate;
5940 }
5941 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005942 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005943 if (status != NO_ERROR) {
5944 goto exit;
5945 }
5946 mChannelMask = config->channel_mask;
5947 }
5948 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5949 status = mAudioPort->checkFormat(config->format);
5950 if (status != NO_ERROR) {
5951 goto exit;
5952 }
5953 mFormat = config->format;
5954 }
5955 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5956 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5957 if (status != NO_ERROR) {
5958 goto exit;
5959 }
5960 mGain = config->gain;
5961 }
5962
5963exit:
5964 if (status != NO_ERROR) {
5965 applyAudioPortConfig(&localBackupConfig);
5966 }
5967 if (backupConfig != NULL) {
5968 *backupConfig = localBackupConfig;
5969 }
5970 return status;
5971}
5972
Eric Laurent1f2f2232014-06-02 12:01:23 -07005973void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5974 struct audio_port_config *dstConfig,
5975 const struct audio_port_config *srcConfig) const
5976{
5977 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5978 dstConfig->sample_rate = mSamplingRate;
5979 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5980 dstConfig->sample_rate = srcConfig->sample_rate;
5981 }
5982 } else {
5983 dstConfig->sample_rate = 0;
5984 }
5985 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5986 dstConfig->channel_mask = mChannelMask;
5987 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5988 dstConfig->channel_mask = srcConfig->channel_mask;
5989 }
5990 } else {
5991 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5992 }
5993 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5994 dstConfig->format = mFormat;
5995 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5996 dstConfig->format = srcConfig->format;
5997 }
5998 } else {
5999 dstConfig->format = AUDIO_FORMAT_INVALID;
6000 }
6001 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6002 dstConfig->gain = mGain;
6003 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6004 dstConfig->gain = srcConfig->gain;
6005 }
6006 } else {
6007 dstConfig->gain.index = -1;
6008 }
6009 if (dstConfig->gain.index != -1) {
6010 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6011 } else {
6012 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6013 }
6014}
6015
Eric Laurent1c333e22014-05-20 10:48:17 -07006016// --- IOProfile class implementation
6017
Eric Laurent1afeecb2014-05-14 08:52:28 -07006018AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006019 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006020 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006021{
6022}
6023
Eric Laurente0720872014-03-11 09:30:41 -07006024AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006025{
6026}
6027
6028// checks if the IO profile is compatible with specified parameters.
6029// Sampling rate, format and channel mask must be specified in order to
6030// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006031bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006032 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006033 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006034 audio_format_t format,
6035 audio_channel_mask_t channelMask,
6036 audio_output_flags_t flags) const
6037{
Glenn Kastencbd48022014-07-24 13:46:44 -07006038 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6039 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6040 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006041
Glenn Kastencbd48022014-07-24 13:46:44 -07006042 if ((mSupportedDevices.types() & device) != device) {
6043 return false;
6044 }
6045
6046 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006047 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006048 }
6049 uint32_t myUpdatedSamplingRate = samplingRate;
6050 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006051 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006052 }
6053 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6054 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006055 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006056 }
6057
6058 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6059 return false;
6060 }
6061
6062 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6063 checkExactChannelMask(channelMask) != NO_ERROR)) {
6064 return false;
6065 }
6066 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6067 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6068 return false;
6069 }
6070
6071 if (isPlaybackThread && (mFlags & flags) != flags) {
6072 return false;
6073 }
6074 // The only input flag that is allowed to be different is the fast flag.
6075 // An existing fast stream is compatible with a normal track request.
6076 // An existing normal stream is compatible with a fast track request,
6077 // but the fast request will be denied by AudioFlinger and converted to normal track.
6078 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6079 ~AUDIO_INPUT_FLAG_FAST)) {
6080 return false;
6081 }
6082
6083 if (updatedSamplingRate != NULL) {
6084 *updatedSamplingRate = myUpdatedSamplingRate;
6085 }
6086 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006087}
6088
Eric Laurente0720872014-03-11 09:30:41 -07006089void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006090{
6091 const size_t SIZE = 256;
6092 char buffer[SIZE];
6093 String8 result;
6094
Eric Laurent1afeecb2014-05-14 08:52:28 -07006095 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006096
Eric Laurente552edb2014-03-10 17:42:56 -07006097 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6098 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006099 snprintf(buffer, SIZE, " - devices:\n");
6100 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006101 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006102 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6103 mSupportedDevices[i]->dump(fd, 6, i);
6104 }
Eric Laurente552edb2014-03-10 17:42:56 -07006105}
6106
Eric Laurentd4692962014-05-05 18:13:44 -07006107void AudioPolicyManager::IOProfile::log()
6108{
6109 const size_t SIZE = 256;
6110 char buffer[SIZE];
6111 String8 result;
6112
6113 ALOGV(" - sampling rates: ");
6114 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6115 ALOGV(" %d", mSamplingRates[i]);
6116 }
6117
6118 ALOGV(" - channel masks: ");
6119 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6120 ALOGV(" 0x%04x", mChannelMasks[i]);
6121 }
6122
6123 ALOGV(" - formats: ");
6124 for (size_t i = 0; i < mFormats.size(); i++) {
6125 ALOGV(" 0x%08x", mFormats[i]);
6126 }
6127
6128 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6129 ALOGV(" - flags: 0x%04x\n", mFlags);
6130}
6131
6132
Eric Laurent3a4311c2014-03-17 12:00:47 -07006133// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006134
Eric Laurent1f2f2232014-06-02 12:01:23 -07006135
6136AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6137 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6138 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6139 AUDIO_PORT_ROLE_SOURCE,
6140 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006141 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006142{
6143 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006144 if (mGains.size() > 0) {
6145 mGains[0]->getDefaultConfig(&mGain);
6146 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006147}
6148
Eric Laurent3a4311c2014-03-17 12:00:47 -07006149bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006150{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006151 // Devices are considered equal if they:
6152 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6153 // - have the same address or one device does not specify the address
6154 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006155 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006156 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006157 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006158 mChannelMask == other->mChannelMask);
6159}
6160
6161void AudioPolicyManager::DeviceVector::refreshTypes()
6162{
Eric Laurent1c333e22014-05-20 10:48:17 -07006163 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006164 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006165 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006166 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006167 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006168}
6169
6170ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6171{
6172 for(size_t i = 0; i < size(); i++) {
6173 if (item->equals(itemAt(i))) {
6174 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006175 }
6176 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006177 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006178}
6179
Eric Laurent3a4311c2014-03-17 12:00:47 -07006180ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006181{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006182 ssize_t ret = indexOf(item);
6183
6184 if (ret < 0) {
6185 ret = SortedVector::add(item);
6186 if (ret >= 0) {
6187 refreshTypes();
6188 }
6189 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006190 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006191 ret = -1;
6192 }
6193 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006194}
6195
Eric Laurent3a4311c2014-03-17 12:00:47 -07006196ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6197{
6198 size_t i;
6199 ssize_t ret = indexOf(item);
6200
6201 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006202 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006203 } else {
6204 ret = SortedVector::removeAt(ret);
6205 if (ret >= 0) {
6206 refreshTypes();
6207 }
6208 }
6209 return ret;
6210}
6211
6212void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6213{
6214 DeviceVector deviceList;
6215
6216 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6217 types &= ~role_bit;
6218
6219 while (types) {
6220 uint32_t i = 31 - __builtin_clz(types);
6221 uint32_t type = 1 << i;
6222 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006223 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006224 }
6225}
6226
Eric Laurent1afeecb2014-05-14 08:52:28 -07006227void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6228 const DeviceVector& declaredDevices)
6229{
6230 char *devName = strtok(name, "|");
6231 while (devName != NULL) {
6232 if (strlen(devName) != 0) {
6233 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6234 ARRAY_SIZE(sDeviceNameToEnumTable),
6235 devName);
6236 if (type != AUDIO_DEVICE_NONE) {
6237 add(new DeviceDescriptor(String8(""), type));
6238 } else {
6239 sp<DeviceDescriptor> deviceDesc =
6240 declaredDevices.getDeviceFromName(String8(devName));
6241 if (deviceDesc != 0) {
6242 add(deviceDesc);
6243 }
6244 }
6245 }
6246 devName = strtok(NULL, "|");
6247 }
6248}
6249
Eric Laurent1c333e22014-05-20 10:48:17 -07006250sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6251 audio_devices_t type, String8 address) const
6252{
6253 sp<DeviceDescriptor> device;
6254 for (size_t i = 0; i < size(); i++) {
6255 if (itemAt(i)->mDeviceType == type) {
6256 device = itemAt(i);
6257 if (itemAt(i)->mAddress = address) {
6258 break;
6259 }
6260 }
6261 }
6262 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6263 type, address.string(), device.get());
6264 return device;
6265}
6266
Eric Laurent6a94d692014-05-20 11:18:06 -07006267sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6268 audio_port_handle_t id) const
6269{
6270 sp<DeviceDescriptor> device;
6271 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006272 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006273 if (itemAt(i)->mId == id) {
6274 device = itemAt(i);
6275 break;
6276 }
6277 }
6278 return device;
6279}
6280
Eric Laurent1c333e22014-05-20 10:48:17 -07006281AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6282 audio_devices_t type) const
6283{
6284 DeviceVector devices;
6285 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6286 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6287 devices.add(itemAt(i));
6288 type &= ~itemAt(i)->mDeviceType;
6289 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6290 itemAt(i)->mDeviceType, itemAt(i).get());
6291 }
6292 }
6293 return devices;
6294}
6295
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006296AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6297 audio_devices_t type, String8 address) const
6298{
6299 DeviceVector devices;
6300 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6301 for (size_t i = 0; i < size(); i++) {
6302 //ALOGV(" at i=%d: device=%x, addr=%s",
6303 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6304 if (itemAt(i)->mDeviceType == type) {
6305 if (itemAt(i)->mAddress == address) {
6306 //ALOGV(" found matching address %s", address.string());
6307 devices.add(itemAt(i));
6308 }
6309 }
6310 }
6311 return devices;
6312}
6313
Eric Laurent1afeecb2014-05-14 08:52:28 -07006314sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6315 const String8& name) const
6316{
6317 sp<DeviceDescriptor> device;
6318 for (size_t i = 0; i < size(); i++) {
6319 if (itemAt(i)->mName == name) {
6320 device = itemAt(i);
6321 break;
6322 }
6323 }
6324 return device;
6325}
6326
Eric Laurent6a94d692014-05-20 11:18:06 -07006327void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6328 struct audio_port_config *dstConfig,
6329 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006330{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006331 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6332 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006333 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006334 }
6335
6336 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6337
Eric Laurent6a94d692014-05-20 11:18:06 -07006338 dstConfig->id = mId;
6339 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006340 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006341 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006342 dstConfig->ext.device.type = mDeviceType;
6343 dstConfig->ext.device.hw_module = mModule->mHandle;
6344 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006345}
6346
6347void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6348{
Eric Laurent83b88082014-06-20 18:31:16 -07006349 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006350 AudioPort::toAudioPort(port);
6351 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006352 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006353 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006354 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006355 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6356}
6357
Eric Laurent1afeecb2014-05-14 08:52:28 -07006358status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006359{
6360 const size_t SIZE = 256;
6361 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006362 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006363
Eric Laurent1afeecb2014-05-14 08:52:28 -07006364 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6365 result.append(buffer);
6366 if (mId != 0) {
6367 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6368 result.append(buffer);
6369 }
6370 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6371 enumToString(sDeviceNameToEnumTable,
6372 ARRAY_SIZE(sDeviceNameToEnumTable),
6373 mDeviceType));
6374 result.append(buffer);
6375 if (mAddress.size() != 0) {
6376 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6377 result.append(buffer);
6378 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006379 write(fd, result.string(), result.size());
6380 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006381
6382 return NO_ERROR;
6383}
6384
6385
6386// --- audio_policy.conf file parsing
6387
Eric Laurente0720872014-03-11 09:30:41 -07006388audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006389{
6390 uint32_t flag = 0;
6391
6392 // it is OK to cast name to non const here as we are not going to use it after
6393 // strtok() modifies it
6394 char *flagName = strtok(name, "|");
6395 while (flagName != NULL) {
6396 if (strlen(flagName) != 0) {
6397 flag |= stringToEnum(sFlagNameToEnumTable,
6398 ARRAY_SIZE(sFlagNameToEnumTable),
6399 flagName);
6400 }
6401 flagName = strtok(NULL, "|");
6402 }
6403 //force direct flag if offload flag is set: offloading implies a direct output stream
6404 // and all common behaviors are driven by checking only the direct flag
6405 // this should normally be set appropriately in the policy configuration file
6406 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6407 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6408 }
6409
6410 return (audio_output_flags_t)flag;
6411}
6412
Eric Laurente0720872014-03-11 09:30:41 -07006413audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006414{
6415 uint32_t device = 0;
6416
6417 char *devName = strtok(name, "|");
6418 while (devName != NULL) {
6419 if (strlen(devName) != 0) {
6420 device |= stringToEnum(sDeviceNameToEnumTable,
6421 ARRAY_SIZE(sDeviceNameToEnumTable),
6422 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006423 }
Eric Laurente552edb2014-03-10 17:42:56 -07006424 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006425 }
Eric Laurente552edb2014-03-10 17:42:56 -07006426 return device;
6427}
6428
Eric Laurente0720872014-03-11 09:30:41 -07006429void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006430{
Eric Laurente552edb2014-03-10 17:42:56 -07006431 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006432 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006433 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006434
Eric Laurent1afeecb2014-05-14 08:52:28 -07006435 node = config_find(root, DEVICES_TAG);
6436 if (node != NULL) {
6437 node = node->first_child;
6438 while (node) {
6439 ALOGV("loadHwModule() loading device %s", node->name);
6440 status_t tmpStatus = module->loadDevice(node);
6441 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6442 status = tmpStatus;
6443 }
6444 node = node->next;
6445 }
6446 }
6447 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006448 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006449 node = node->first_child;
6450 while (node) {
6451 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006452 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006453 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6454 status = tmpStatus;
6455 }
6456 node = node->next;
6457 }
6458 }
6459 node = config_find(root, INPUTS_TAG);
6460 if (node != NULL) {
6461 node = node->first_child;
6462 while (node) {
6463 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006464 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006465 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6466 status = tmpStatus;
6467 }
6468 node = node->next;
6469 }
6470 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006471 loadGlobalConfig(root, module);
6472
Eric Laurente552edb2014-03-10 17:42:56 -07006473 if (status == NO_ERROR) {
6474 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006475 }
6476}
6477
Eric Laurente0720872014-03-11 09:30:41 -07006478void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006479{
6480 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6481 if (node == NULL) {
6482 return;
6483 }
6484
6485 node = node->first_child;
6486 while (node) {
6487 ALOGV("loadHwModules() loading module %s", node->name);
6488 loadHwModule(node);
6489 node = node->next;
6490 }
6491}
6492
Eric Laurent1f2f2232014-06-02 12:01:23 -07006493void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006494{
6495 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006496
Eric Laurente552edb2014-03-10 17:42:56 -07006497 if (node == NULL) {
6498 return;
6499 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006500 DeviceVector declaredDevices;
6501 if (module != NULL) {
6502 declaredDevices = module->mDeclaredDevices;
6503 }
6504
Eric Laurente552edb2014-03-10 17:42:56 -07006505 node = node->first_child;
6506 while (node) {
6507 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006508 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6509 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006510 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6511 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006512 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006513 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006514 ARRAY_SIZE(sDeviceNameToEnumTable),
6515 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006516 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006517 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006518 } else {
6519 ALOGW("loadGlobalConfig() default device not specified");
6520 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006521 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006522 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006523 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6524 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006525 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006526 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6527 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6528 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006529 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6530 uint32_t major, minor;
6531 sscanf((char *)node->value, "%u.%u", &major, &minor);
6532 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6533 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6534 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006535 }
6536 node = node->next;
6537 }
6538}
6539
Eric Laurente0720872014-03-11 09:30:41 -07006540status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006541{
6542 cnode *root;
6543 char *data;
6544
6545 data = (char *)load_file(path, NULL);
6546 if (data == NULL) {
6547 return -ENODEV;
6548 }
6549 root = config_node("", "");
6550 config_load(root, data);
6551
Eric Laurente552edb2014-03-10 17:42:56 -07006552 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006553 // legacy audio_policy.conf files have one global_configuration section
6554 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006555 config_free(root);
6556 free(root);
6557 free(data);
6558
6559 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6560
6561 return NO_ERROR;
6562}
6563
Eric Laurente0720872014-03-11 09:30:41 -07006564void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006565{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006566 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006567 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006568 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6569 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006570 mAvailableOutputDevices.add(mDefaultOutputDevice);
6571 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006572
6573 module = new HwModule("primary");
6574
Eric Laurent1afeecb2014-05-14 08:52:28 -07006575 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006576 profile->mSamplingRates.add(44100);
6577 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6578 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006579 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006580 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6581 module->mOutputProfiles.add(profile);
6582
Eric Laurent1afeecb2014-05-14 08:52:28 -07006583 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006584 profile->mSamplingRates.add(8000);
6585 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6586 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006587 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006588 module->mInputProfiles.add(profile);
6589
6590 mHwModules.add(module);
6591}
6592
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006593audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6594{
6595 // flags to stream type mapping
6596 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6597 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6598 }
6599 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6600 return AUDIO_STREAM_BLUETOOTH_SCO;
6601 }
6602
6603 // usage to stream type mapping
6604 switch (attr->usage) {
6605 case AUDIO_USAGE_MEDIA:
6606 case AUDIO_USAGE_GAME:
6607 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6608 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6609 return AUDIO_STREAM_MUSIC;
6610 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6611 return AUDIO_STREAM_SYSTEM;
6612 case AUDIO_USAGE_VOICE_COMMUNICATION:
6613 return AUDIO_STREAM_VOICE_CALL;
6614
6615 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6616 return AUDIO_STREAM_DTMF;
6617
6618 case AUDIO_USAGE_ALARM:
6619 return AUDIO_STREAM_ALARM;
6620 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6621 return AUDIO_STREAM_RING;
6622
6623 case AUDIO_USAGE_NOTIFICATION:
6624 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6625 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6626 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6627 case AUDIO_USAGE_NOTIFICATION_EVENT:
6628 return AUDIO_STREAM_NOTIFICATION;
6629
6630 case AUDIO_USAGE_UNKNOWN:
6631 default:
6632 return AUDIO_STREAM_MUSIC;
6633 }
6634}
Eric Laurente552edb2014-03-10 17:42:56 -07006635}; // namespace android