blob: e4ff3b111e2139cb70e321f29c7e0e1daeef0b5b [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
33
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
39#include <hardware/audio.h>
40#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070041#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070043#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070044
Eric Laurent3b73df72014-03-11 09:06:29 -070045namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070046
47// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070048// Definitions for audio_policy.conf file parsing
49// ----------------------------------------------------------------------------
50
51struct StringToEnum {
52 const char *name;
53 uint32_t value;
54};
55
56#define STRING_TO_ENUM(string) { #string, string }
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
59const StringToEnum sDeviceNameToEnumTable[] = {
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070073 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070074 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700103};
104
105const StringToEnum sFlagNameToEnumTable[] = {
106 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
107 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
112};
113
114const StringToEnum sFormatNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
116 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
121 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
122 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
123 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
124};
125
126const StringToEnum sOutChannelsNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
128 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
129 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
130 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
131};
132
133const StringToEnum sInChannelsNameToEnumTable[] = {
134 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
135 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
136 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
137};
138
Eric Laurent1afeecb2014-05-14 08:52:28 -0700139const StringToEnum sGainModeNameToEnumTable[] = {
140 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
141 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
142 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
143};
144
Eric Laurent3a4311c2014-03-17 12:00:47 -0700145
146uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
147 size_t size,
148 const char *name)
149{
150 for (size_t i = 0; i < size; i++) {
151 if (strcmp(table[i].name, name) == 0) {
152 ALOGV("stringToEnum() found %s", table[i].name);
153 return table[i].value;
154 }
155 }
156 return 0;
157}
158
159const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
160 size_t size,
161 uint32_t value)
162{
163 for (size_t i = 0; i < size; i++) {
164 if (table[i].value == value) {
165 return table[i].name;
166 }
167 }
168 return "";
169}
170
171bool AudioPolicyManager::stringToBool(const char *value)
172{
173 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
174}
175
176
177// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700178// AudioPolicyInterface implementation
179// ----------------------------------------------------------------------------
180
181
Eric Laurente0720872014-03-11 09:30:41 -0700182status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700183 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700184 const char *device_address)
185{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700186 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700187
188 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
189
190 // connect/disconnect only 1 device at a time
191 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
192
Eric Laurente552edb2014-03-10 17:42:56 -0700193 // handle output devices
194 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700195 SortedVector <audio_io_handle_t> outputs;
196
Eric Laurent1afeecb2014-05-14 08:52:28 -0700197 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
198 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700199 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // save a copy of the opened output descriptors before any output is opened or closed
202 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
203 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700204 switch (state)
205 {
206 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700207 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700208 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700209 ALOGW("setDeviceConnectionState() device already connected: %x", device);
210 return INVALID_OPERATION;
211 }
212 ALOGV("setDeviceConnectionState() connecting device %x", device);
213
Eric Laurent3a4311c2014-03-17 12:00:47 -0700214 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700215 return INVALID_OPERATION;
216 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700217 // outputs should never be empty here
218 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
219 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700220 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700221 outputs.size());
222 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700223 index = mAvailableOutputDevices.add(devDesc);
224 if (index >= 0) {
225 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700226 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700227 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
228 "could not find HW module for device %08x", device);
229 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 } else {
231 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700232 }
233
234 break;
235 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700236 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700238 ALOGW("setDeviceConnectionState() device not connected: %x", device);
239 return INVALID_OPERATION;
240 }
241
242 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
243 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700244 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700245
Eric Laurent3a4311c2014-03-17 12:00:47 -0700246 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700247 // not currently handling multiple simultaneous submixes: ignoring remote submix
248 // case and address
249 } break;
250
251 default:
252 ALOGE("setDeviceConnectionState() invalid state: %x", state);
253 return BAD_VALUE;
254 }
255
Eric Laurent3a4311c2014-03-17 12:00:47 -0700256 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
257 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700258 checkA2dpSuspend();
259 checkOutputForAllStrategies();
260 // outputs must be closed after checkOutputForAllStrategies() is executed
261 if (!outputs.isEmpty()) {
262 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700263 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700264 // close unused outputs after device disconnection or direct outputs that have been
265 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700266 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700267 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
268 (desc->mDirectOpenCount == 0))) {
269 closeOutput(outputs[i]);
270 }
271 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700272 // check again after closing A2DP output to reset mA2dpSuspended if needed
273 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700274 }
275
276 updateDevicesAndOutputs();
277 for (size_t i = 0; i < mOutputs.size(); i++) {
278 // do not force device change on duplicated output because if device is 0, it will
279 // also force a device 0 for the two outputs it is duplicated to which may override
280 // a valid device selection on those outputs.
281 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent951f4552014-05-20 10:48:17 -0700282 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700283 !mOutputs.valueAt(i)->isDuplicated(),
284 0);
285 }
286
287 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
288 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
289 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
290 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
291 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
292 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
293 } else {
Eric Laurentb52c1522014-05-20 11:27:36 -0700294 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700295 return NO_ERROR;
296 }
Eric Laurentd4692962014-05-05 18:13:44 -0700297 } // end if is output device
298
Eric Laurente552edb2014-03-10 17:42:56 -0700299 // handle input devices
300 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700301 SortedVector <audio_io_handle_t> inputs;
302
Eric Laurent1afeecb2014-05-14 08:52:28 -0700303 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
304 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700305 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700306 switch (state)
307 {
308 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700309 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700310 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700311 ALOGW("setDeviceConnectionState() device already connected: %d", device);
312 return INVALID_OPERATION;
313 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700314 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700315 if (module == NULL) {
316 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
317 device);
318 return INVALID_OPERATION;
319 }
Eric Laurentd4692962014-05-05 18:13:44 -0700320 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
321 return INVALID_OPERATION;
322 }
323
Eric Laurent3a4311c2014-03-17 12:00:47 -0700324 index = mAvailableInputDevices.add(devDesc);
325 if (index >= 0) {
326 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700327 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 } else {
329 return NO_MEMORY;
330 }
Eric Laurentd4692962014-05-05 18:13:44 -0700331 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700332
333 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700334 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700335 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700336 ALOGW("setDeviceConnectionState() device not connected: %d", device);
337 return INVALID_OPERATION;
338 }
Eric Laurentd4692962014-05-05 18:13:44 -0700339 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700340 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700341 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700342
343 default:
344 ALOGE("setDeviceConnectionState() invalid state: %x", state);
345 return BAD_VALUE;
346 }
347
Eric Laurentd4692962014-05-05 18:13:44 -0700348 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700349
Eric Laurentb52c1522014-05-20 11:27:36 -0700350 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700351 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700352 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700353
354 ALOGW("setDeviceConnectionState() invalid device: %x", device);
355 return BAD_VALUE;
356}
357
Eric Laurente0720872014-03-11 09:30:41 -0700358audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700359 const char *device_address)
360{
Eric Laurent3b73df72014-03-11 09:06:29 -0700361 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700362 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700363 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
364 devDesc->mAddress = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700365 ssize_t index;
366 DeviceVector *deviceVector;
367
Eric Laurente552edb2014-03-10 17:42:56 -0700368 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700369 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700370 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700371 deviceVector = &mAvailableInputDevices;
372 } else {
373 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
374 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700375 }
376
Eric Laurent3a4311c2014-03-17 12:00:47 -0700377 index = deviceVector->indexOf(devDesc);
378 if (index >= 0) {
379 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
380 } else {
381 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
382 }
Eric Laurente552edb2014-03-10 17:42:56 -0700383}
384
Eric Laurente0720872014-03-11 09:30:41 -0700385void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700386{
387 ALOGV("setPhoneState() state %d", state);
388 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700389 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700390 ALOGW("setPhoneState() invalid state %d", state);
391 return;
392 }
393
394 if (state == mPhoneState ) {
395 ALOGW("setPhoneState() setting same state %d", state);
396 return;
397 }
398
399 // if leaving call state, handle special case of active streams
400 // pertaining to sonification strategy see handleIncallSonification()
401 if (isInCall()) {
402 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700403 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
404 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700405 }
406 }
407
408 // store previous phone state for management of sonification strategy below
409 int oldState = mPhoneState;
410 mPhoneState = state;
411 bool force = false;
412
413 // are we entering or starting a call
414 if (!isStateInCall(oldState) && isStateInCall(state)) {
415 ALOGV(" Entering call in setPhoneState()");
416 // force routing command to audio hardware when starting a call
417 // even if no device change is needed
418 force = true;
419 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
420 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
421 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
422 }
423 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
424 ALOGV(" Exiting call in setPhoneState()");
425 // force routing command to audio hardware when exiting a call
426 // even if no device change is needed
427 force = true;
428 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
429 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
430 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
431 }
432 } else if (isStateInCall(state) && (state != oldState)) {
433 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
434 // force routing command to audio hardware when switching between telephony and VoIP
435 // even if no device change is needed
436 force = true;
437 }
438
439 // check for device and output changes triggered by new phone state
Eric Laurent951f4552014-05-20 10:48:17 -0700440 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700441 checkA2dpSuspend();
442 checkOutputForAllStrategies();
443 updateDevicesAndOutputs();
444
Eric Laurent1f2f2232014-06-02 12:01:23 -0700445 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700446
447 // force routing command to audio hardware when ending call
448 // even if no device change is needed
449 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
450 newDevice = hwOutputDesc->device();
451 }
452
453 int delayMs = 0;
454 if (isStateInCall(state)) {
455 nsecs_t sysTime = systemTime();
456 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700457 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700458 // mute media and sonification strategies and delay device switch by the largest
459 // latency of any output where either strategy is active.
460 // This avoid sending the ring tone or music tail into the earpiece or headset.
461 if ((desc->isStrategyActive(STRATEGY_MEDIA,
462 SONIFICATION_HEADSET_MUSIC_DELAY,
463 sysTime) ||
464 desc->isStrategyActive(STRATEGY_SONIFICATION,
465 SONIFICATION_HEADSET_MUSIC_DELAY,
466 sysTime)) &&
467 (delayMs < (int)desc->mLatency*2)) {
468 delayMs = desc->mLatency*2;
469 }
470 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
471 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
472 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
473 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
474 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
475 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
476 }
477 }
478
479 // change routing is necessary
480 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
481
482 // if entering in call state, handle special case of active streams
483 // pertaining to sonification strategy see handleIncallSonification()
484 if (isStateInCall(state)) {
485 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700486 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
487 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700488 }
489 }
490
491 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700492 if (state == AUDIO_MODE_RINGTONE &&
493 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700494 mLimitRingtoneVolume = true;
495 } else {
496 mLimitRingtoneVolume = false;
497 }
498}
499
Eric Laurente0720872014-03-11 09:30:41 -0700500void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700501 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700502{
503 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
504
505 bool forceVolumeReeval = false;
506 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700507 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
508 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
509 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700510 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
511 return;
512 }
513 forceVolumeReeval = true;
514 mForceUse[usage] = config;
515 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700516 case AUDIO_POLICY_FORCE_FOR_MEDIA:
517 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
518 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
519 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
520 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
521 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700522 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
523 return;
524 }
525 mForceUse[usage] = config;
526 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700527 case AUDIO_POLICY_FORCE_FOR_RECORD:
528 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
529 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700530 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
531 return;
532 }
533 mForceUse[usage] = config;
534 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700535 case AUDIO_POLICY_FORCE_FOR_DOCK:
536 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
537 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
538 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
539 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
540 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700541 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
542 }
543 forceVolumeReeval = true;
544 mForceUse[usage] = config;
545 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700546 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
547 if (config != AUDIO_POLICY_FORCE_NONE &&
548 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700549 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
550 }
551 forceVolumeReeval = true;
552 mForceUse[usage] = config;
553 break;
554 default:
555 ALOGW("setForceUse() invalid usage %d", usage);
556 break;
557 }
558
559 // check for device and output changes triggered by new force usage
560 checkA2dpSuspend();
561 checkOutputForAllStrategies();
562 updateDevicesAndOutputs();
563 for (size_t i = 0; i < mOutputs.size(); i++) {
564 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent951f4552014-05-20 10:48:17 -0700565 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700566 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
567 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
568 applyStreamVolumes(output, newDevice, 0, true);
569 }
570 }
571
572 audio_io_handle_t activeInput = getActiveInput();
573 if (activeInput != 0) {
Eric Laurent951f4552014-05-20 10:48:17 -0700574 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700575 }
576
577}
578
Eric Laurente0720872014-03-11 09:30:41 -0700579audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700580{
581 return mForceUse[usage];
582}
583
Eric Laurente0720872014-03-11 09:30:41 -0700584void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700585{
586 ALOGV("setSystemProperty() property %s, value %s", property, value);
587}
588
589// Find a direct output profile compatible with the parameters passed, even if the input flags do
590// not explicitly request a direct output
Eric Laurent951f4552014-05-20 10:48:17 -0700591sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700592 audio_devices_t device,
593 uint32_t samplingRate,
594 audio_format_t format,
595 audio_channel_mask_t channelMask,
596 audio_output_flags_t flags)
597{
598 for (size_t i = 0; i < mHwModules.size(); i++) {
599 if (mHwModules[i]->mHandle == 0) {
600 continue;
601 }
602 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent951f4552014-05-20 10:48:17 -0700603 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700604 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700605 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
606 if (profile->isCompatibleProfile(device, samplingRate, format,
607 channelMask,
608 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700609 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700610 }
611 } else {
612 if (profile->isCompatibleProfile(device, samplingRate, format,
613 channelMask,
614 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700615 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700616 }
617 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700618 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
619 return profile;
620 }
Eric Laurente552edb2014-03-10 17:42:56 -0700621 }
622 }
623 return 0;
624}
625
Eric Laurente0720872014-03-11 09:30:41 -0700626audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700627 uint32_t samplingRate,
628 audio_format_t format,
629 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700630 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700631 const audio_offload_info_t *offloadInfo)
632{
633 audio_io_handle_t output = 0;
634 uint32_t latency = 0;
Eric Laurent3b73df72014-03-11 09:06:29 -0700635 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700636 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
637 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
638 device, stream, samplingRate, format, channelMask, flags);
639
640#ifdef AUDIO_POLICY_TEST
641 if (mCurOutput != 0) {
642 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
643 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
644
645 if (mTestOutputs[mCurOutput] == 0) {
646 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700647 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700648 outputDesc->mDevice = mTestDevice;
649 outputDesc->mSamplingRate = mTestSamplingRate;
650 outputDesc->mFormat = mTestFormat;
651 outputDesc->mChannelMask = mTestChannels;
652 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700653 outputDesc->mFlags =
654 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700655 outputDesc->mRefCount[stream] = 0;
656 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
657 &outputDesc->mSamplingRate,
658 &outputDesc->mFormat,
659 &outputDesc->mChannelMask,
660 &outputDesc->mLatency,
661 outputDesc->mFlags,
662 offloadInfo);
663 if (mTestOutputs[mCurOutput]) {
664 AudioParameter outputCmd = AudioParameter();
665 outputCmd.addInt(String8("set_id"),mCurOutput);
666 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
667 addOutput(mTestOutputs[mCurOutput], outputDesc);
668 }
669 }
670 return mTestOutputs[mCurOutput];
671 }
672#endif //AUDIO_POLICY_TEST
673
674 // open a direct output if required by specified parameters
675 //force direct flag if offload flag is set: offloading implies a direct output stream
676 // and all common behaviors are driven by checking only the direct flag
677 // this should normally be set appropriately in the policy configuration file
678 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700679 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700680 }
681
682 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
683 // creating an offloaded track and tearing it down immediately after start when audioflinger
684 // detects there is an active non offloadable effect.
685 // FIXME: We should check the audio session here but we do not have it in this context.
686 // This may prevent offloading in rare situations where effects are left active by apps
687 // in the background.
Eric Laurent951f4552014-05-20 10:48:17 -0700688 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700689 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
690 !isNonOffloadableEffectEnabled()) {
691 profile = getProfileForDirectOutput(device,
692 samplingRate,
693 format,
694 channelMask,
695 (audio_output_flags_t)flags);
696 }
697
Eric Laurent951f4552014-05-20 10:48:17 -0700698 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700699 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700700
701 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700702 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700703 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
704 outputDesc = desc;
705 // reuse direct output if currently open and configured with same parameters
706 if ((samplingRate == outputDesc->mSamplingRate) &&
707 (format == outputDesc->mFormat) &&
708 (channelMask == outputDesc->mChannelMask)) {
709 outputDesc->mDirectOpenCount++;
710 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
711 return mOutputs.keyAt(i);
712 }
713 }
714 }
715 // close direct output if currently open and configured with different parameters
716 if (outputDesc != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -0700717 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700718 }
719 outputDesc = new AudioOutputDescriptor(profile);
720 outputDesc->mDevice = device;
721 outputDesc->mSamplingRate = samplingRate;
722 outputDesc->mFormat = format;
723 outputDesc->mChannelMask = channelMask;
724 outputDesc->mLatency = 0;
725 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
726 outputDesc->mRefCount[stream] = 0;
727 outputDesc->mStopTime[stream] = 0;
728 outputDesc->mDirectOpenCount = 1;
729 output = mpClientInterface->openOutput(profile->mModule->mHandle,
730 &outputDesc->mDevice,
731 &outputDesc->mSamplingRate,
732 &outputDesc->mFormat,
733 &outputDesc->mChannelMask,
734 &outputDesc->mLatency,
735 outputDesc->mFlags,
736 offloadInfo);
737
738 // only accept an output with the requested parameters
739 if (output == 0 ||
740 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
741 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
742 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
743 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
744 "format %d %d, channelMask %04x %04x", output, samplingRate,
745 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
746 outputDesc->mChannelMask);
747 if (output != 0) {
748 mpClientInterface->closeOutput(output);
749 }
Eric Laurente552edb2014-03-10 17:42:56 -0700750 return 0;
751 }
752 audio_io_handle_t srcOutput = getOutputForEffect();
753 addOutput(output, outputDesc);
754 audio_io_handle_t dstOutput = getOutputForEffect();
755 if (dstOutput == output) {
756 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
757 }
758 mPreviousOutputs = mOutputs;
759 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700760 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700761 return output;
762 }
763
764 // ignoring channel mask due to downmix capability in mixer
765
766 // open a non direct output
767
768 // for non direct outputs, only PCM is supported
769 if (audio_is_linear_pcm(format)) {
770 // get which output is suitable for the specified stream. The actual
771 // routing change will happen when startOutput() will be called
772 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
773
774 output = selectOutput(outputs, flags);
775 }
776 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
777 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
778
779 ALOGV("getOutput() returns output %d", output);
780
781 return output;
782}
783
Eric Laurente0720872014-03-11 09:30:41 -0700784audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700785 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700786{
787 // select one output among several that provide a path to a particular device or set of
788 // devices (the list was previously build by getOutputsForDevice()).
789 // The priority is as follows:
790 // 1: the output with the highest number of requested policy flags
791 // 2: the primary output
792 // 3: the first output in the list
793
794 if (outputs.size() == 0) {
795 return 0;
796 }
797 if (outputs.size() == 1) {
798 return outputs[0];
799 }
800
801 int maxCommonFlags = 0;
802 audio_io_handle_t outputFlags = 0;
803 audio_io_handle_t outputPrimary = 0;
804
805 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700806 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700807 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700808 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700809 if (commonFlags > maxCommonFlags) {
810 outputFlags = outputs[i];
811 maxCommonFlags = commonFlags;
812 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
813 }
814 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
815 outputPrimary = outputs[i];
816 }
817 }
818 }
819
820 if (outputFlags != 0) {
821 return outputFlags;
822 }
823 if (outputPrimary != 0) {
824 return outputPrimary;
825 }
826
827 return outputs[0];
828}
829
Eric Laurente0720872014-03-11 09:30:41 -0700830status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700831 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700832 int session)
833{
834 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
835 ssize_t index = mOutputs.indexOfKey(output);
836 if (index < 0) {
837 ALOGW("startOutput() unknown output %d", output);
838 return BAD_VALUE;
839 }
840
Eric Laurent1f2f2232014-06-02 12:01:23 -0700841 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700842
843 // increment usage count for this stream on the requested output:
844 // NOTE that the usage count is the same for duplicated output and hardware output which is
845 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
846 outputDesc->changeRefCount(stream, 1);
847
848 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent951f4552014-05-20 10:48:17 -0700849 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700850 routing_strategy strategy = getStrategy(stream);
851 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
852 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
853 uint32_t waitMs = 0;
854 bool force = false;
855 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700856 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700857 if (desc != outputDesc) {
858 // force a device change if any other output is managed by the same hw
859 // module and has a current device selection that differs from selected device.
860 // In this case, the audio HAL must receive the new device selection so that it can
861 // change the device currently selected by the other active output.
862 if (outputDesc->sharesHwModuleWith(desc) &&
863 desc->device() != newDevice) {
864 force = true;
865 }
866 // wait for audio on other active outputs to be presented when starting
867 // a notification so that audio focus effect can propagate.
868 uint32_t latency = desc->latency();
869 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
870 waitMs = latency;
871 }
872 }
873 }
874 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
875
876 // handle special case for sonification while in call
877 if (isInCall()) {
878 handleIncallSonification(stream, true, false);
879 }
880
881 // apply volume rules for current stream and device if necessary
882 checkAndSetVolume(stream,
883 mStreams[stream].getVolumeIndex(newDevice),
884 output,
885 newDevice);
886
887 // update the outputs if starting an output with a stream that can affect notification
888 // routing
889 handleNotificationRoutingForStream(stream);
890 if (waitMs > muteWaitMs) {
891 usleep((waitMs - muteWaitMs) * 2 * 1000);
892 }
893 }
894 return NO_ERROR;
895}
896
897
Eric Laurente0720872014-03-11 09:30:41 -0700898status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700899 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700900 int session)
901{
902 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
903 ssize_t index = mOutputs.indexOfKey(output);
904 if (index < 0) {
905 ALOGW("stopOutput() unknown output %d", output);
906 return BAD_VALUE;
907 }
908
Eric Laurent1f2f2232014-06-02 12:01:23 -0700909 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700910
911 // handle special case for sonification while in call
912 if (isInCall()) {
913 handleIncallSonification(stream, false, false);
914 }
915
916 if (outputDesc->mRefCount[stream] > 0) {
917 // decrement usage count of this stream on the output
918 outputDesc->changeRefCount(stream, -1);
919 // store time at which the stream was stopped - see isStreamActive()
920 if (outputDesc->mRefCount[stream] == 0) {
921 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent951f4552014-05-20 10:48:17 -0700922 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700923 // delay the device switch by twice the latency because stopOutput() is executed when
924 // the track stop() command is received and at that time the audio track buffer can
925 // still contain data that needs to be drained. The latency only covers the audio HAL
926 // and kernel buffers. Also the latency does not always include additional delay in the
927 // audio path (audio DSP, CODEC ...)
928 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
929
930 // force restoring the device selection on other active outputs if it differs from the
931 // one being selected for this output
932 for (size_t i = 0; i < mOutputs.size(); i++) {
933 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700934 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700935 if (curOutput != output &&
936 desc->isActive() &&
937 outputDesc->sharesHwModuleWith(desc) &&
938 (newDevice != desc->device())) {
939 setOutputDevice(curOutput,
Eric Laurent951f4552014-05-20 10:48:17 -0700940 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700941 true,
942 outputDesc->mLatency*2);
943 }
944 }
945 // update the outputs if stopping one with a stream that can affect notification routing
946 handleNotificationRoutingForStream(stream);
947 }
948 return NO_ERROR;
949 } else {
950 ALOGW("stopOutput() refcount is already 0 for output %d", output);
951 return INVALID_OPERATION;
952 }
953}
954
Eric Laurente0720872014-03-11 09:30:41 -0700955void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700956{
957 ALOGV("releaseOutput() %d", output);
958 ssize_t index = mOutputs.indexOfKey(output);
959 if (index < 0) {
960 ALOGW("releaseOutput() releasing unknown output %d", output);
961 return;
962 }
963
964#ifdef AUDIO_POLICY_TEST
965 int testIndex = testOutputIndex(output);
966 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700967 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700968 if (outputDesc->isActive()) {
969 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700970 mOutputs.removeItem(output);
971 mTestOutputs[testIndex] = 0;
972 }
973 return;
974 }
975#endif //AUDIO_POLICY_TEST
976
Eric Laurent1f2f2232014-06-02 12:01:23 -0700977 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -0700978 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700979 if (desc->mDirectOpenCount <= 0) {
980 ALOGW("releaseOutput() invalid open count %d for output %d",
981 desc->mDirectOpenCount, output);
982 return;
983 }
984 if (--desc->mDirectOpenCount == 0) {
985 closeOutput(output);
986 // If effects where present on the output, audioflinger moved them to the primary
987 // output by default: move them back to the appropriate output.
988 audio_io_handle_t dstOutput = getOutputForEffect();
989 if (dstOutput != mPrimaryOutput) {
990 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
991 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700992 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700993 }
994 }
995}
996
997
Eric Laurente0720872014-03-11 09:30:41 -0700998audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -0700999 uint32_t samplingRate,
1000 audio_format_t format,
1001 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001002 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001003{
1004 audio_io_handle_t input = 0;
1005 audio_devices_t device = getDeviceForInputSource(inputSource);
1006
1007 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1008 inputSource, samplingRate, format, channelMask, acoustics);
1009
1010 if (device == AUDIO_DEVICE_NONE) {
1011 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1012 return 0;
1013 }
1014
1015 // adapt channel selection to input source
1016 switch(inputSource) {
1017 case AUDIO_SOURCE_VOICE_UPLINK:
1018 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1019 break;
1020 case AUDIO_SOURCE_VOICE_DOWNLINK:
1021 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1022 break;
1023 case AUDIO_SOURCE_VOICE_CALL:
1024 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1025 break;
1026 default:
1027 break;
1028 }
1029
Eric Laurent951f4552014-05-20 10:48:17 -07001030 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001031 samplingRate,
1032 format,
1033 channelMask);
Eric Laurent951f4552014-05-20 10:48:17 -07001034 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001035 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1036 "channelMask %04x",
1037 device, samplingRate, format, channelMask);
1038 return 0;
1039 }
1040
1041 if (profile->mModule->mHandle == 0) {
1042 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1043 return 0;
1044 }
1045
Eric Laurent1f2f2232014-06-02 12:01:23 -07001046 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001047
1048 inputDesc->mInputSource = inputSource;
1049 inputDesc->mDevice = device;
1050 inputDesc->mSamplingRate = samplingRate;
1051 inputDesc->mFormat = format;
1052 inputDesc->mChannelMask = channelMask;
1053 inputDesc->mRefCount = 0;
1054 input = mpClientInterface->openInput(profile->mModule->mHandle,
1055 &inputDesc->mDevice,
1056 &inputDesc->mSamplingRate,
1057 &inputDesc->mFormat,
1058 &inputDesc->mChannelMask);
1059
1060 // only accept input with the exact requested set of parameters
1061 if (input == 0 ||
1062 (samplingRate != inputDesc->mSamplingRate) ||
1063 (format != inputDesc->mFormat) ||
1064 (channelMask != inputDesc->mChannelMask)) {
1065 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1066 samplingRate, format, channelMask);
1067 if (input != 0) {
1068 mpClientInterface->closeInput(input);
1069 }
Eric Laurente552edb2014-03-10 17:42:56 -07001070 return 0;
1071 }
Eric Laurentd4692962014-05-05 18:13:44 -07001072 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001073 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001074 return input;
1075}
1076
Eric Laurente0720872014-03-11 09:30:41 -07001077status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001078{
1079 ALOGV("startInput() input %d", input);
1080 ssize_t index = mInputs.indexOfKey(input);
1081 if (index < 0) {
1082 ALOGW("startInput() unknown input %d", input);
1083 return BAD_VALUE;
1084 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001085 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001086
1087#ifdef AUDIO_POLICY_TEST
1088 if (mTestInput == 0)
1089#endif //AUDIO_POLICY_TEST
1090 {
1091 // refuse 2 active AudioRecord clients at the same time except if the active input
1092 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1093 audio_io_handle_t activeInput = getActiveInput();
1094 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001095 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001096 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1097 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1098 stopInput(activeInput);
1099 releaseInput(activeInput);
1100 } else {
1101 ALOGW("startInput() input %d failed: other input already started", input);
1102 return INVALID_OPERATION;
1103 }
1104 }
1105 }
1106
Eric Laurent951f4552014-05-20 10:48:17 -07001107 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001108
1109 // automatically enable the remote submix output when input is started
1110 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1111 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001112 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001113 }
1114
Eric Laurente552edb2014-03-10 17:42:56 -07001115 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1116
Eric Laurente552edb2014-03-10 17:42:56 -07001117 inputDesc->mRefCount = 1;
1118 return NO_ERROR;
1119}
1120
Eric Laurente0720872014-03-11 09:30:41 -07001121status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001122{
1123 ALOGV("stopInput() input %d", input);
1124 ssize_t index = mInputs.indexOfKey(input);
1125 if (index < 0) {
1126 ALOGW("stopInput() unknown input %d", input);
1127 return BAD_VALUE;
1128 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001129 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001130
1131 if (inputDesc->mRefCount == 0) {
1132 ALOGW("stopInput() input %d already stopped", input);
1133 return INVALID_OPERATION;
1134 } else {
1135 // automatically disable the remote submix output when input is stopped
1136 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1137 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001138 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001139 }
1140
Eric Laurent951f4552014-05-20 10:48:17 -07001141 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001142 inputDesc->mRefCount = 0;
1143 return NO_ERROR;
1144 }
1145}
1146
Eric Laurente0720872014-03-11 09:30:41 -07001147void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001148{
1149 ALOGV("releaseInput() %d", input);
1150 ssize_t index = mInputs.indexOfKey(input);
1151 if (index < 0) {
1152 ALOGW("releaseInput() releasing unknown input %d", input);
1153 return;
1154 }
1155 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001156 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001157 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001158 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001159 ALOGV("releaseInput() exit");
1160}
1161
Eric Laurentd4692962014-05-05 18:13:44 -07001162void AudioPolicyManager::closeAllInputs() {
1163 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1164 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1165 }
1166 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001167 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001168}
1169
Eric Laurente0720872014-03-11 09:30:41 -07001170void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001171 int indexMin,
1172 int indexMax)
1173{
1174 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1175 if (indexMin < 0 || indexMin >= indexMax) {
1176 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1177 return;
1178 }
1179 mStreams[stream].mIndexMin = indexMin;
1180 mStreams[stream].mIndexMax = indexMax;
1181}
1182
Eric Laurente0720872014-03-11 09:30:41 -07001183status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001184 int index,
1185 audio_devices_t device)
1186{
1187
1188 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1189 return BAD_VALUE;
1190 }
1191 if (!audio_is_output_device(device)) {
1192 return BAD_VALUE;
1193 }
1194
1195 // Force max volume if stream cannot be muted
1196 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1197
1198 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1199 stream, device, index);
1200
1201 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1202 // clear all device specific values
1203 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1204 mStreams[stream].mIndexCur.clear();
1205 }
1206 mStreams[stream].mIndexCur.add(device, index);
1207
1208 // compute and apply stream volume on all outputs according to connected device
1209 status_t status = NO_ERROR;
1210 for (size_t i = 0; i < mOutputs.size(); i++) {
1211 audio_devices_t curDevice =
1212 getDeviceForVolume(mOutputs.valueAt(i)->device());
1213 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1214 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1215 if (volStatus != NO_ERROR) {
1216 status = volStatus;
1217 }
1218 }
1219 }
1220 return status;
1221}
1222
Eric Laurente0720872014-03-11 09:30:41 -07001223status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001224 int *index,
1225 audio_devices_t device)
1226{
1227 if (index == NULL) {
1228 return BAD_VALUE;
1229 }
1230 if (!audio_is_output_device(device)) {
1231 return BAD_VALUE;
1232 }
1233 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1234 // the strategy the stream belongs to.
1235 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1236 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1237 }
1238 device = getDeviceForVolume(device);
1239
1240 *index = mStreams[stream].getVolumeIndex(device);
1241 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1242 return NO_ERROR;
1243}
1244
Eric Laurente0720872014-03-11 09:30:41 -07001245audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001246 const SortedVector<audio_io_handle_t>& outputs)
1247{
1248 // select one output among several suitable for global effects.
1249 // The priority is as follows:
1250 // 1: An offloaded output. If the effect ends up not being offloadable,
1251 // AudioFlinger will invalidate the track and the offloaded output
1252 // will be closed causing the effect to be moved to a PCM output.
1253 // 2: A deep buffer output
1254 // 3: the first output in the list
1255
1256 if (outputs.size() == 0) {
1257 return 0;
1258 }
1259
1260 audio_io_handle_t outputOffloaded = 0;
1261 audio_io_handle_t outputDeepBuffer = 0;
1262
1263 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001264 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001265 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001266 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1267 outputOffloaded = outputs[i];
1268 }
1269 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1270 outputDeepBuffer = outputs[i];
1271 }
1272 }
1273
1274 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1275 outputOffloaded, outputDeepBuffer);
1276 if (outputOffloaded != 0) {
1277 return outputOffloaded;
1278 }
1279 if (outputDeepBuffer != 0) {
1280 return outputDeepBuffer;
1281 }
1282
1283 return outputs[0];
1284}
1285
Eric Laurente0720872014-03-11 09:30:41 -07001286audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001287{
1288 // apply simple rule where global effects are attached to the same output as MUSIC streams
1289
Eric Laurent3b73df72014-03-11 09:06:29 -07001290 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001291 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1292 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1293
1294 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1295 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1296 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1297
1298 return output;
1299}
1300
Eric Laurente0720872014-03-11 09:30:41 -07001301status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001302 audio_io_handle_t io,
1303 uint32_t strategy,
1304 int session,
1305 int id)
1306{
1307 ssize_t index = mOutputs.indexOfKey(io);
1308 if (index < 0) {
1309 index = mInputs.indexOfKey(io);
1310 if (index < 0) {
1311 ALOGW("registerEffect() unknown io %d", io);
1312 return INVALID_OPERATION;
1313 }
1314 }
1315
1316 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1317 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1318 desc->name, desc->memoryUsage);
1319 return INVALID_OPERATION;
1320 }
1321 mTotalEffectsMemory += desc->memoryUsage;
1322 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1323 desc->name, io, strategy, session, id);
1324 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1325
Eric Laurent1f2f2232014-06-02 12:01:23 -07001326 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1327 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1328 effectDesc->mIo = io;
1329 effectDesc->mStrategy = (routing_strategy)strategy;
1330 effectDesc->mSession = session;
1331 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001332
Eric Laurent1f2f2232014-06-02 12:01:23 -07001333 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001334
1335 return NO_ERROR;
1336}
1337
Eric Laurente0720872014-03-11 09:30:41 -07001338status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001339{
1340 ssize_t index = mEffects.indexOfKey(id);
1341 if (index < 0) {
1342 ALOGW("unregisterEffect() unknown effect ID %d", id);
1343 return INVALID_OPERATION;
1344 }
1345
Eric Laurent1f2f2232014-06-02 12:01:23 -07001346 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001347
Eric Laurent1f2f2232014-06-02 12:01:23 -07001348 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001349
Eric Laurent1f2f2232014-06-02 12:01:23 -07001350 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001351 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001352 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1353 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001354 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001355 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001356 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001357 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001358
1359 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001360
1361 return NO_ERROR;
1362}
1363
Eric Laurente0720872014-03-11 09:30:41 -07001364status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001365{
1366 ssize_t index = mEffects.indexOfKey(id);
1367 if (index < 0) {
1368 ALOGW("unregisterEffect() unknown effect ID %d", id);
1369 return INVALID_OPERATION;
1370 }
1371
1372 return setEffectEnabled(mEffects.valueAt(index), enabled);
1373}
1374
Eric Laurent1f2f2232014-06-02 12:01:23 -07001375status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001376{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001377 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001378 ALOGV("setEffectEnabled(%s) effect already %s",
1379 enabled?"true":"false", enabled?"enabled":"disabled");
1380 return INVALID_OPERATION;
1381 }
1382
1383 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001384 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001385 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001386 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001387 return INVALID_OPERATION;
1388 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001389 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001390 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1391 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001392 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001393 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001394 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1395 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001396 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001397 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001398 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1399 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001400 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001401 return NO_ERROR;
1402}
1403
Eric Laurente0720872014-03-11 09:30:41 -07001404bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001405{
1406 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001407 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1408 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1409 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001410 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001411 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001412 return true;
1413 }
1414 }
1415 return false;
1416}
1417
Eric Laurente0720872014-03-11 09:30:41 -07001418bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001419{
1420 nsecs_t sysTime = systemTime();
1421 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001423 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001424 return true;
1425 }
1426 }
1427 return false;
1428}
1429
Eric Laurente0720872014-03-11 09:30:41 -07001430bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001431 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001432{
1433 nsecs_t sysTime = systemTime();
1434 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001435 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001436 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001437 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001438 return true;
1439 }
1440 }
1441 return false;
1442}
1443
Eric Laurente0720872014-03-11 09:30:41 -07001444bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001445{
1446 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001447 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001448 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001449 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001450 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1451 && (inputDescriptor->mRefCount > 0)) {
1452 return true;
1453 }
1454 }
1455 return false;
1456}
1457
1458
Eric Laurente0720872014-03-11 09:30:41 -07001459status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001460{
1461 const size_t SIZE = 256;
1462 char buffer[SIZE];
1463 String8 result;
1464
1465 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1466 result.append(buffer);
1467
1468 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1469 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001470 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1471 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001472 snprintf(buffer, SIZE, " Force use for communications %d\n",
1473 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001474 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001475 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001476 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001477 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001478 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001479 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001480 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001481 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001482 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001483
Eric Laurent3a4311c2014-03-17 12:00:47 -07001484 snprintf(buffer, SIZE, " Available output devices:\n");
1485 result.append(buffer);
1486 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001487 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001488 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001489 }
1490 snprintf(buffer, SIZE, "\n Available input devices:\n");
1491 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001492 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001493 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001494 }
Eric Laurente552edb2014-03-10 17:42:56 -07001495
1496 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1497 write(fd, buffer, strlen(buffer));
1498 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001499 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001500 write(fd, buffer, strlen(buffer));
1501 mHwModules[i]->dump(fd);
1502 }
1503
1504 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1505 write(fd, buffer, strlen(buffer));
1506 for (size_t i = 0; i < mOutputs.size(); i++) {
1507 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1508 write(fd, buffer, strlen(buffer));
1509 mOutputs.valueAt(i)->dump(fd);
1510 }
1511
1512 snprintf(buffer, SIZE, "\nInputs dump:\n");
1513 write(fd, buffer, strlen(buffer));
1514 for (size_t i = 0; i < mInputs.size(); i++) {
1515 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1516 write(fd, buffer, strlen(buffer));
1517 mInputs.valueAt(i)->dump(fd);
1518 }
1519
1520 snprintf(buffer, SIZE, "\nStreams dump:\n");
1521 write(fd, buffer, strlen(buffer));
1522 snprintf(buffer, SIZE,
1523 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1524 write(fd, buffer, strlen(buffer));
Eric Laurent3b73df72014-03-11 09:06:29 -07001525 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001526 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001527 write(fd, buffer, strlen(buffer));
1528 mStreams[i].dump(fd);
1529 }
1530
1531 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1532 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1533 write(fd, buffer, strlen(buffer));
1534
1535 snprintf(buffer, SIZE, "Registered effects:\n");
1536 write(fd, buffer, strlen(buffer));
1537 for (size_t i = 0; i < mEffects.size(); i++) {
1538 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1539 write(fd, buffer, strlen(buffer));
1540 mEffects.valueAt(i)->dump(fd);
1541 }
1542
1543
1544 return NO_ERROR;
1545}
1546
1547// This function checks for the parameters which can be offloaded.
1548// This can be enhanced depending on the capability of the DSP and policy
1549// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001550bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001551{
1552 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001553 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001554 offloadInfo.sample_rate, offloadInfo.channel_mask,
1555 offloadInfo.format,
1556 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1557 offloadInfo.has_video);
1558
1559 // Check if offload has been disabled
1560 char propValue[PROPERTY_VALUE_MAX];
1561 if (property_get("audio.offload.disable", propValue, "0")) {
1562 if (atoi(propValue) != 0) {
1563 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1564 return false;
1565 }
1566 }
1567
1568 // Check if stream type is music, then only allow offload as of now.
1569 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1570 {
1571 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1572 return false;
1573 }
1574
1575 //TODO: enable audio offloading with video when ready
1576 if (offloadInfo.has_video)
1577 {
1578 ALOGV("isOffloadSupported: has_video == true, returning false");
1579 return false;
1580 }
1581
1582 //If duration is less than minimum value defined in property, return false
1583 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1584 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1585 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1586 return false;
1587 }
1588 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1589 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1590 return false;
1591 }
1592
1593 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1594 // creating an offloaded track and tearing it down immediately after start when audioflinger
1595 // detects there is an active non offloadable effect.
1596 // FIXME: We should check the audio session here but we do not have it in this context.
1597 // This may prevent offloading in rare situations where effects are left active by apps
1598 // in the background.
1599 if (isNonOffloadableEffectEnabled()) {
1600 return false;
1601 }
1602
1603 // See if there is a profile to support this.
1604 // AUDIO_DEVICE_NONE
Eric Laurent951f4552014-05-20 10:48:17 -07001605 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001606 offloadInfo.sample_rate,
1607 offloadInfo.format,
1608 offloadInfo.channel_mask,
1609 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent951f4552014-05-20 10:48:17 -07001610 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1611 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001612}
1613
Eric Laurent6a94d692014-05-20 11:18:06 -07001614status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1615 audio_port_type_t type,
1616 unsigned int *num_ports,
1617 struct audio_port *ports,
1618 unsigned int *generation)
1619{
1620 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1621 generation == NULL) {
1622 return BAD_VALUE;
1623 }
1624 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1625 if (ports == NULL) {
1626 *num_ports = 0;
1627 }
1628
1629 size_t portsWritten = 0;
1630 size_t portsMax = *num_ports;
1631 *num_ports = 0;
1632 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1633 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1634 for (size_t i = 0;
1635 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1636 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1637 }
1638 *num_ports += mAvailableOutputDevices.size();
1639 }
1640 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1641 for (size_t i = 0;
1642 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1643 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1644 }
1645 *num_ports += mAvailableInputDevices.size();
1646 }
1647 }
1648 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1649 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1650 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1651 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1652 }
1653 *num_ports += mInputs.size();
1654 }
1655 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1656 for (size_t i = 0; i < mOutputs.size() && portsWritten < portsMax; i++) {
1657 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1658 }
1659 *num_ports += mOutputs.size();
1660 }
1661 }
1662 *generation = curAudioPortGeneration();
1663 ALOGV("listAudioPorts() got %d ports needed %d", portsWritten, *num_ports);
1664 return NO_ERROR;
1665}
1666
1667status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1668{
1669 return NO_ERROR;
1670}
1671
Eric Laurent1f2f2232014-06-02 12:01:23 -07001672sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001673 audio_port_handle_t id) const
1674{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001675 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001676 for (size_t i = 0; i < mOutputs.size(); i++) {
1677 outputDesc = mOutputs.valueAt(i);
1678 if (outputDesc->mId == id) {
1679 break;
1680 }
1681 }
1682 return outputDesc;
1683}
1684
Eric Laurent1f2f2232014-06-02 12:01:23 -07001685sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001686 audio_port_handle_t id) const
1687{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001688 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001689 for (size_t i = 0; i < mInputs.size(); i++) {
1690 inputDesc = mInputs.valueAt(i);
1691 if (inputDesc->mId == id) {
1692 break;
1693 }
1694 }
1695 return inputDesc;
1696}
1697
Eric Laurent1f2f2232014-06-02 12:01:23 -07001698sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1699 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001700{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001701 sp <HwModule> module;
1702
Eric Laurent6a94d692014-05-20 11:18:06 -07001703 for (size_t i = 0; i < mHwModules.size(); i++) {
1704 if (mHwModules[i]->mHandle == 0) {
1705 continue;
1706 }
1707 if (audio_is_output_device(device)) {
1708 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1709 {
1710 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1711 return mHwModules[i];
1712 }
1713 }
1714 } else {
1715 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1716 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1717 device & ~AUDIO_DEVICE_BIT_IN) {
1718 return mHwModules[i];
1719 }
1720 }
1721 }
1722 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001723 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001724}
1725
Eric Laurent1f2f2232014-06-02 12:01:23 -07001726sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001727{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001728 sp <HwModule> module;
1729
Eric Laurent1afeecb2014-05-14 08:52:28 -07001730 for (size_t i = 0; i < mHwModules.size(); i++)
1731 {
1732 if (strcmp(mHwModules[i]->mName, name) == 0) {
1733 return mHwModules[i];
1734 }
1735 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001736 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001737}
1738
1739
Eric Laurent6a94d692014-05-20 11:18:06 -07001740status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1741 audio_patch_handle_t *handle,
1742 uid_t uid)
1743{
1744 ALOGV("createAudioPatch()");
1745
1746 if (handle == NULL || patch == NULL) {
1747 return BAD_VALUE;
1748 }
1749 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1750
1751 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1752 return INVALID_OPERATION;
1753 }
1754 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1755 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1756 return INVALID_OPERATION;
1757 }
1758
1759 sp<AudioPatch> patchDesc;
1760 ssize_t index = mAudioPatches.indexOfKey(*handle);
1761
1762 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1763 patch->sinks[0].type);
1764 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1765 patch->sources[0].role,
1766 patch->sources[0].type);
1767
1768 if (index >= 0) {
1769 patchDesc = mAudioPatches.valueAt(index);
1770 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1771 mUidCached, patchDesc->mUid, uid);
1772 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1773 return INVALID_OPERATION;
1774 }
1775 } else {
1776 *handle = 0;
1777 }
1778
1779 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1780 // TODO add support for mix to mix connection
1781 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1782 ALOGV("createAudioPatch() source mix sink not device");
1783 return BAD_VALUE;
1784 }
1785 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001786 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001787 if (outputDesc == NULL) {
1788 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1789 return BAD_VALUE;
1790 }
1791 if (patchDesc != 0) {
1792 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1793 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1794 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1795 return BAD_VALUE;
1796 }
1797 }
1798 sp<DeviceDescriptor> devDesc =
1799 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1800 if (devDesc == 0) {
1801 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1802 return BAD_VALUE;
1803 }
1804
1805 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1806 patch->sources[0].sample_rate,
1807 patch->sources[0].format,
1808 patch->sources[0].channel_mask,
1809 AUDIO_OUTPUT_FLAG_NONE)) {
1810 return INVALID_OPERATION;
1811 }
1812 // TODO: reconfigure output format and channels here
1813 ALOGV("createAudioPatch() setting device %08x on output %d",
1814 devDesc->mType, outputDesc->mIoHandle);
1815 setOutputDevice(outputDesc->mIoHandle,
1816 devDesc->mType,
1817 true,
1818 0,
1819 handle);
1820 index = mAudioPatches.indexOfKey(*handle);
1821 if (index >= 0) {
1822 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1823 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1824 }
1825 patchDesc = mAudioPatches.valueAt(index);
1826 patchDesc->mUid = uid;
1827 ALOGV("createAudioPatch() success");
1828 } else {
1829 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1830 return INVALID_OPERATION;
1831 }
1832 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1833 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1834 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001835 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001836 if (inputDesc == NULL) {
1837 return BAD_VALUE;
1838 }
1839 if (patchDesc != 0) {
1840 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1841 return BAD_VALUE;
1842 }
1843 }
1844 sp<DeviceDescriptor> devDesc =
1845 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1846 if (devDesc == 0) {
1847 return BAD_VALUE;
1848 }
1849
1850 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1851 patch->sinks[0].sample_rate,
1852 patch->sinks[0].format,
1853 patch->sinks[0].channel_mask,
1854 AUDIO_OUTPUT_FLAG_NONE)) {
1855 return INVALID_OPERATION;
1856 }
1857 // TODO: reconfigure output format and channels here
1858 ALOGV("createAudioPatch() setting device %08x on output %d",
1859 devDesc->mType, inputDesc->mIoHandle);
1860 setInputDevice(inputDesc->mIoHandle,
1861 devDesc->mType,
1862 true,
1863 handle);
1864 index = mAudioPatches.indexOfKey(*handle);
1865 if (index >= 0) {
1866 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1867 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1868 }
1869 patchDesc = mAudioPatches.valueAt(index);
1870 patchDesc->mUid = uid;
1871 ALOGV("createAudioPatch() success");
1872 } else {
1873 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1874 return INVALID_OPERATION;
1875 }
1876 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1877 // device to device connection
1878 if (patchDesc != 0) {
1879 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1880 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1881 return BAD_VALUE;
1882 }
1883 }
1884
1885 sp<DeviceDescriptor> srcDeviceDesc =
1886 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1887 sp<DeviceDescriptor> sinkDeviceDesc =
1888 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1889 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1890 return BAD_VALUE;
1891 }
1892 //update source and sink with our own data as the data passed in the patch may
1893 // be incomplete.
1894 struct audio_patch newPatch = *patch;
1895 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1896 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1897
1898 // TODO: add support for devices on different HW modules
1899 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1900 return INVALID_OPERATION;
1901 }
1902 // TODO: check from routing capabilities in config file and other conflicting patches
1903
1904 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1905 if (index >= 0) {
1906 afPatchHandle = patchDesc->mAfPatchHandle;
1907 }
1908
1909 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1910 &afPatchHandle,
1911 0);
1912 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1913 status, afPatchHandle);
1914 if (status == NO_ERROR) {
1915 if (index < 0) {
1916 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1917 &newPatch, uid);
1918 addAudioPatch(patchDesc->mHandle, patchDesc);
1919 } else {
1920 patchDesc->mPatch = newPatch;
1921 }
1922 patchDesc->mAfPatchHandle = afPatchHandle;
1923 *handle = patchDesc->mHandle;
1924 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001925 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001926 } else {
1927 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1928 status);
1929 return INVALID_OPERATION;
1930 }
1931 } else {
1932 return BAD_VALUE;
1933 }
1934 } else {
1935 return BAD_VALUE;
1936 }
1937 return NO_ERROR;
1938}
1939
1940status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1941 uid_t uid)
1942{
1943 ALOGV("releaseAudioPatch() patch %d", handle);
1944
1945 ssize_t index = mAudioPatches.indexOfKey(handle);
1946
1947 if (index < 0) {
1948 return BAD_VALUE;
1949 }
1950 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1951 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1952 mUidCached, patchDesc->mUid, uid);
1953 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1954 return INVALID_OPERATION;
1955 }
1956
1957 struct audio_patch *patch = &patchDesc->mPatch;
1958 patchDesc->mUid = mUidCached;
1959 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001960 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001961 if (outputDesc == NULL) {
1962 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
1963 return BAD_VALUE;
1964 }
1965
1966 setOutputDevice(outputDesc->mIoHandle,
1967 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
1968 true,
1969 0,
1970 NULL);
1971 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1972 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001973 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001974 if (inputDesc == NULL) {
1975 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
1976 return BAD_VALUE;
1977 }
1978 setInputDevice(inputDesc->mIoHandle,
1979 getNewInputDevice(inputDesc->mIoHandle),
1980 true,
1981 NULL);
1982 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1983 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
1984 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1985 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
1986 status, patchDesc->mAfPatchHandle);
1987 removeAudioPatch(patchDesc->mHandle);
1988 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001989 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001990 } else {
1991 return BAD_VALUE;
1992 }
1993 } else {
1994 return BAD_VALUE;
1995 }
1996 return NO_ERROR;
1997}
1998
1999status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2000 struct audio_patch *patches,
2001 unsigned int *generation)
2002{
2003 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2004 generation == NULL) {
2005 return BAD_VALUE;
2006 }
2007 ALOGV("listAudioPatches() num_patches %d patches %p available patches %d",
2008 *num_patches, patches, mAudioPatches.size());
2009 if (patches == NULL) {
2010 *num_patches = 0;
2011 }
2012
2013 size_t patchesWritten = 0;
2014 size_t patchesMax = *num_patches;
2015 for (size_t i = 0;
2016 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2017 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2018 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
2019 ALOGV("listAudioPatches() patch %d num_sources %d num_sinks %d",
2020 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2021 }
2022 *num_patches = mAudioPatches.size();
2023
2024 *generation = curAudioPortGeneration();
2025 ALOGV("listAudioPatches() got %d patches needed %d", patchesWritten, *num_patches);
2026 return NO_ERROR;
2027}
2028
Eric Laurente1715a42014-05-20 11:30:42 -07002029status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002030{
Eric Laurente1715a42014-05-20 11:30:42 -07002031 ALOGV("setAudioPortConfig()");
2032
2033 if (config == NULL) {
2034 return BAD_VALUE;
2035 }
2036 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2037 // Only support gain configuration for now
2038 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN || config->gain.index < 0) {
2039 return BAD_VALUE;
2040 }
2041
2042 sp<AudioPort> portDesc;
2043 struct audio_port_config portConfig;
2044 if (config->type == AUDIO_PORT_TYPE_MIX) {
2045 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002046 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002047 if (outputDesc == NULL) {
2048 return BAD_VALUE;
2049 }
2050 portDesc = outputDesc->mProfile;
2051 outputDesc->toAudioPortConfig(&portConfig);
2052 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002053 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002054 if (inputDesc == NULL) {
2055 return BAD_VALUE;
2056 }
2057 portDesc = inputDesc->mProfile;
2058 inputDesc->toAudioPortConfig(&portConfig);
2059 } else {
2060 return BAD_VALUE;
2061 }
2062 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2063 sp<DeviceDescriptor> deviceDesc;
2064 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2065 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2066 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2067 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2068 } else {
2069 return BAD_VALUE;
2070 }
2071 if (deviceDesc == NULL) {
2072 return BAD_VALUE;
2073 }
2074 portDesc = deviceDesc;
2075 deviceDesc->toAudioPortConfig(&portConfig);
2076 } else {
2077 return BAD_VALUE;
2078 }
2079
2080 if ((size_t)config->gain.index >= portDesc->mGains.size()) {
2081 return INVALID_OPERATION;
2082 }
2083 const struct audio_gain *gain = &portDesc->mGains[config->gain.index]->mGain;
2084 if ((config->gain.mode & ~gain->mode) != 0) {
2085 return BAD_VALUE;
2086 }
2087 if ((config->gain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
2088 if ((config->gain.values[0] < gain->min_value) ||
2089 (config->gain.values[0] > gain->max_value)) {
2090 return BAD_VALUE;
2091 }
2092 } else {
2093 if ((config->gain.channel_mask & ~gain->channel_mask) != 0) {
2094 return BAD_VALUE;
2095 }
2096 size_t numValues = popcount(config->gain.channel_mask);
2097 for (size_t i = 0; i < numValues; i++) {
2098 if ((config->gain.values[i] < gain->min_value) ||
2099 (config->gain.values[i] > gain->max_value)) {
2100 return BAD_VALUE;
2101 }
2102 }
2103 }
2104 if ((config->gain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
2105 if ((config->gain.ramp_duration_ms < gain->min_ramp_ms) ||
2106 (config->gain.ramp_duration_ms > gain->max_ramp_ms)) {
2107 return BAD_VALUE;
2108 }
2109 }
2110
2111 portConfig.gain = config->gain;
2112
2113 status_t status = mpClientInterface->setAudioPortConfig(&portConfig, 0);
2114
2115 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002116}
2117
2118void AudioPolicyManager::clearAudioPatches(uid_t uid)
2119{
2120 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2121 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2122 if (patchDesc->mUid == uid) {
2123 // releaseAudioPatch() removes the patch from mAudioPatches
2124 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2125 i--;
2126 }
2127 }
2128 }
2129}
2130
2131status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2132 const sp<AudioPatch>& patch)
2133{
2134 ssize_t index = mAudioPatches.indexOfKey(handle);
2135
2136 if (index >= 0) {
2137 ALOGW("addAudioPatch() patch %d already in", handle);
2138 return ALREADY_EXISTS;
2139 }
2140 mAudioPatches.add(handle, patch);
2141 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2142 "sink handle %d",
2143 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2144 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2145 return NO_ERROR;
2146}
2147
2148status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2149{
2150 ssize_t index = mAudioPatches.indexOfKey(handle);
2151
2152 if (index < 0) {
2153 ALOGW("removeAudioPatch() patch %d not in", handle);
2154 return ALREADY_EXISTS;
2155 }
2156 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2157 mAudioPatches.valueAt(index)->mAfPatchHandle);
2158 mAudioPatches.removeItemsAt(index);
2159 return NO_ERROR;
2160}
2161
Eric Laurente552edb2014-03-10 17:42:56 -07002162// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002163// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002164// ----------------------------------------------------------------------------
2165
Eric Laurent3a4311c2014-03-17 12:00:47 -07002166uint32_t AudioPolicyManager::nextUniqueId()
2167{
2168 return android_atomic_inc(&mNextUniqueId);
2169}
2170
Eric Laurent6a94d692014-05-20 11:18:06 -07002171uint32_t AudioPolicyManager::nextAudioPortGeneration()
2172{
2173 return android_atomic_inc(&mAudioPortGeneration);
2174}
2175
Eric Laurente0720872014-03-11 09:30:41 -07002176AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002177 :
2178#ifdef AUDIO_POLICY_TEST
2179 Thread(false),
2180#endif //AUDIO_POLICY_TEST
2181 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002182 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002183 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2184 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002185 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002186 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2187 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002188{
Eric Laurent6a94d692014-05-20 11:18:06 -07002189 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002190 mpClientInterface = clientInterface;
2191
Eric Laurent3b73df72014-03-11 09:06:29 -07002192 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2193 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002194 }
2195
Eric Laurent1afeecb2014-05-14 08:52:28 -07002196 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002197 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2198 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2199 ALOGE("could not load audio policy configuration file, setting defaults");
2200 defaultAudioPolicyConfig();
2201 }
2202 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002203 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002204
2205 // must be done after reading the policy
2206 initializeVolumeCurves();
2207
2208 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002209 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2210 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002211 for (size_t i = 0; i < mHwModules.size(); i++) {
2212 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2213 if (mHwModules[i]->mHandle == 0) {
2214 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2215 continue;
2216 }
2217 // open all output streams needed to access attached devices
2218 // except for direct output streams that are only opened when they are actually
2219 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002220 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002221 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2222 {
Eric Laurent951f4552014-05-20 10:48:17 -07002223 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002224
Eric Laurent3a4311c2014-03-17 12:00:47 -07002225 if (outProfile->mSupportedDevices.isEmpty()) {
2226 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2227 continue;
2228 }
2229
2230 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2231 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002232 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002233 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002234
Eric Laurent951f4552014-05-20 10:48:17 -07002235 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002236 audio_io_handle_t output = mpClientInterface->openOutput(
2237 outProfile->mModule->mHandle,
2238 &outputDesc->mDevice,
2239 &outputDesc->mSamplingRate,
2240 &outputDesc->mFormat,
2241 &outputDesc->mChannelMask,
2242 &outputDesc->mLatency,
2243 outputDesc->mFlags);
2244 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002245 ALOGW("Cannot open output stream for device %08x on hw module %s",
2246 outputDesc->mDevice,
2247 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002248 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002249 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent951f4552014-05-20 10:48:17 -07002250 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002251 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002252 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002253 // give a valid ID to an attached device once confirmed it is reachable
2254 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2255 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002256 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002257 }
2258 }
Eric Laurente552edb2014-03-10 17:42:56 -07002259 if (mPrimaryOutput == 0 &&
2260 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2261 mPrimaryOutput = output;
2262 }
2263 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002264 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002265 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002266 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002267 true);
2268 }
2269 }
2270 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002271 // open input streams needed to access attached devices to validate
2272 // mAvailableInputDevices list
2273 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2274 {
Eric Laurent951f4552014-05-20 10:48:17 -07002275 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002276
Eric Laurent3a4311c2014-03-17 12:00:47 -07002277 if (inProfile->mSupportedDevices.isEmpty()) {
2278 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2279 continue;
2280 }
2281
2282 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2283 if (profileTypes & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002284 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002285
2286 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent951f4552014-05-20 10:48:17 -07002287 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002288 audio_io_handle_t input = mpClientInterface->openInput(
2289 inProfile->mModule->mHandle,
2290 &inputDesc->mDevice,
2291 &inputDesc->mSamplingRate,
2292 &inputDesc->mFormat,
2293 &inputDesc->mChannelMask);
2294
2295 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002296 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent951f4552014-05-20 10:48:17 -07002297 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002298 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002299 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002300 // give a valid ID to an attached device once confirmed it is reachable
2301 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2302 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002303 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002304 }
2305 }
2306 mpClientInterface->closeInput(input);
2307 } else {
2308 ALOGW("Cannot open input stream for device %08x on hw module %s",
2309 inputDesc->mDevice,
2310 mHwModules[i]->mName);
2311 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002312 }
2313 }
2314 }
2315 // make sure all attached devices have been allocated a unique ID
2316 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2317 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07002318 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002319 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2320 continue;
2321 }
2322 i++;
2323 }
2324 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2325 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07002326 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002327 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2328 continue;
2329 }
2330 i++;
2331 }
2332 // make sure default device is reachable
2333 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07002334 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002335 }
Eric Laurente552edb2014-03-10 17:42:56 -07002336
2337 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2338
2339 updateDevicesAndOutputs();
2340
2341#ifdef AUDIO_POLICY_TEST
2342 if (mPrimaryOutput != 0) {
2343 AudioParameter outputCmd = AudioParameter();
2344 outputCmd.addInt(String8("set_id"), 0);
2345 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2346
2347 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2348 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002349 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2350 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002351 mTestLatencyMs = 0;
2352 mCurOutput = 0;
2353 mDirectOutput = false;
2354 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2355 mTestOutputs[i] = 0;
2356 }
2357
2358 const size_t SIZE = 256;
2359 char buffer[SIZE];
2360 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2361 run(buffer, ANDROID_PRIORITY_AUDIO);
2362 }
2363#endif //AUDIO_POLICY_TEST
2364}
2365
Eric Laurente0720872014-03-11 09:30:41 -07002366AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002367{
2368#ifdef AUDIO_POLICY_TEST
2369 exit();
2370#endif //AUDIO_POLICY_TEST
2371 for (size_t i = 0; i < mOutputs.size(); i++) {
2372 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002373 }
2374 for (size_t i = 0; i < mInputs.size(); i++) {
2375 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002376 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002377 mAvailableOutputDevices.clear();
2378 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002379 mOutputs.clear();
2380 mInputs.clear();
2381 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002382}
2383
Eric Laurente0720872014-03-11 09:30:41 -07002384status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002385{
2386 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2387}
2388
2389#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002390bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002391{
2392 ALOGV("entering threadLoop()");
2393 while (!exitPending())
2394 {
2395 String8 command;
2396 int valueInt;
2397 String8 value;
2398
2399 Mutex::Autolock _l(mLock);
2400 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2401
2402 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2403 AudioParameter param = AudioParameter(command);
2404
2405 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2406 valueInt != 0) {
2407 ALOGV("Test command %s received", command.string());
2408 String8 target;
2409 if (param.get(String8("target"), target) != NO_ERROR) {
2410 target = "Manager";
2411 }
2412 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2413 param.remove(String8("test_cmd_policy_output"));
2414 mCurOutput = valueInt;
2415 }
2416 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2417 param.remove(String8("test_cmd_policy_direct"));
2418 if (value == "false") {
2419 mDirectOutput = false;
2420 } else if (value == "true") {
2421 mDirectOutput = true;
2422 }
2423 }
2424 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2425 param.remove(String8("test_cmd_policy_input"));
2426 mTestInput = valueInt;
2427 }
2428
2429 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2430 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002431 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002432 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002433 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002434 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002435 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002436 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002437 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002438 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002439 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002440 if (target == "Manager") {
2441 mTestFormat = format;
2442 } else if (mTestOutputs[mCurOutput] != 0) {
2443 AudioParameter outputParam = AudioParameter();
2444 outputParam.addInt(String8("format"), format);
2445 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2446 }
2447 }
2448 }
2449 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2450 param.remove(String8("test_cmd_policy_channels"));
2451 int channels = 0;
2452
2453 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002454 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002455 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002456 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002457 }
2458 if (channels != 0) {
2459 if (target == "Manager") {
2460 mTestChannels = channels;
2461 } else if (mTestOutputs[mCurOutput] != 0) {
2462 AudioParameter outputParam = AudioParameter();
2463 outputParam.addInt(String8("channels"), channels);
2464 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2465 }
2466 }
2467 }
2468 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2469 param.remove(String8("test_cmd_policy_sampleRate"));
2470 if (valueInt >= 0 && valueInt <= 96000) {
2471 int samplingRate = valueInt;
2472 if (target == "Manager") {
2473 mTestSamplingRate = samplingRate;
2474 } else if (mTestOutputs[mCurOutput] != 0) {
2475 AudioParameter outputParam = AudioParameter();
2476 outputParam.addInt(String8("sampling_rate"), samplingRate);
2477 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2478 }
2479 }
2480 }
2481
2482 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2483 param.remove(String8("test_cmd_policy_reopen"));
2484
Eric Laurent1f2f2232014-06-02 12:01:23 -07002485 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002486 mpClientInterface->closeOutput(mPrimaryOutput);
2487
2488 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2489
Eric Laurente552edb2014-03-10 17:42:56 -07002490 mOutputs.removeItem(mPrimaryOutput);
2491
Eric Laurent1f2f2232014-06-02 12:01:23 -07002492 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002493 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2494 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2495 &outputDesc->mDevice,
2496 &outputDesc->mSamplingRate,
2497 &outputDesc->mFormat,
2498 &outputDesc->mChannelMask,
2499 &outputDesc->mLatency,
2500 outputDesc->mFlags);
2501 if (mPrimaryOutput == 0) {
2502 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2503 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2504 } else {
2505 AudioParameter outputCmd = AudioParameter();
2506 outputCmd.addInt(String8("set_id"), 0);
2507 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2508 addOutput(mPrimaryOutput, outputDesc);
2509 }
2510 }
2511
2512
2513 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2514 }
2515 }
2516 return false;
2517}
2518
Eric Laurente0720872014-03-11 09:30:41 -07002519void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002520{
2521 {
2522 AutoMutex _l(mLock);
2523 requestExit();
2524 mWaitWorkCV.signal();
2525 }
2526 requestExitAndWait();
2527}
2528
Eric Laurente0720872014-03-11 09:30:41 -07002529int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002530{
2531 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2532 if (output == mTestOutputs[i]) return i;
2533 }
2534 return 0;
2535}
2536#endif //AUDIO_POLICY_TEST
2537
2538// ---
2539
Eric Laurent1f2f2232014-06-02 12:01:23 -07002540void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002541{
Eric Laurent951f4552014-05-20 10:48:17 -07002542 outputDesc->mIoHandle = output;
2543 outputDesc->mId = nextUniqueId();
2544 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002545 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002546}
2547
Eric Laurent1f2f2232014-06-02 12:01:23 -07002548void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002549{
Eric Laurent951f4552014-05-20 10:48:17 -07002550 inputDesc->mIoHandle = input;
2551 inputDesc->mId = nextUniqueId();
2552 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002553 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002554}
Eric Laurente552edb2014-03-10 17:42:56 -07002555
Eric Laurent3a4311c2014-03-17 12:00:47 -07002556String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2557{
2558 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2559 return String8("a2dp_sink_address=")+address;
2560 }
2561 return address;
2562}
2563
Eric Laurente0720872014-03-11 09:30:41 -07002564status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002565 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002566 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002567 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002568{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002569 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002570
Eric Laurent3b73df72014-03-11 09:06:29 -07002571 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002572 // first list already open outputs that can be routed to this device
2573 for (size_t i = 0; i < mOutputs.size(); i++) {
2574 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002575 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002576 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2577 outputs.add(mOutputs.keyAt(i));
2578 }
2579 }
2580 // then look for output profiles that can be routed to this device
Eric Laurent951f4552014-05-20 10:48:17 -07002581 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002582 for (size_t i = 0; i < mHwModules.size(); i++)
2583 {
2584 if (mHwModules[i]->mHandle == 0) {
2585 continue;
2586 }
2587 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2588 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002589 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002590 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002591 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2592 }
2593 }
2594 }
2595
2596 if (profiles.isEmpty() && outputs.isEmpty()) {
2597 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2598 return BAD_VALUE;
2599 }
2600
2601 // open outputs for matching profiles if needed. Direct outputs are also opened to
2602 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2603 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent951f4552014-05-20 10:48:17 -07002604 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002605
2606 // nothing to do if one output is already opened for this profile
2607 size_t j;
2608 for (j = 0; j < mOutputs.size(); j++) {
2609 desc = mOutputs.valueAt(j);
2610 if (!desc->isDuplicated() && desc->mProfile == profile) {
2611 break;
2612 }
2613 }
2614 if (j != mOutputs.size()) {
2615 continue;
2616 }
2617
Eric Laurent3a4311c2014-03-17 12:00:47 -07002618 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002619 desc = new AudioOutputDescriptor(profile);
2620 desc->mDevice = device;
2621 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2622 offloadInfo.sample_rate = desc->mSamplingRate;
2623 offloadInfo.format = desc->mFormat;
2624 offloadInfo.channel_mask = desc->mChannelMask;
2625
2626 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2627 &desc->mDevice,
2628 &desc->mSamplingRate,
2629 &desc->mFormat,
2630 &desc->mChannelMask,
2631 &desc->mLatency,
2632 desc->mFlags,
2633 &offloadInfo);
2634 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002635 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002636 if (!address.isEmpty()) {
2637 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002638 }
2639
Eric Laurentd4692962014-05-05 18:13:44 -07002640 // Here is where we step through and resolve any "dynamic" fields
2641 String8 reply;
2642 char *value;
2643 if (profile->mSamplingRates[0] == 0) {
2644 reply = mpClientInterface->getParameters(output,
2645 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2646 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2647 reply.string());
2648 value = strpbrk((char *)reply.string(), "=");
2649 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002650 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002651 }
Eric Laurentd4692962014-05-05 18:13:44 -07002652 }
2653 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2654 reply = mpClientInterface->getParameters(output,
2655 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2656 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2657 reply.string());
2658 value = strpbrk((char *)reply.string(), "=");
2659 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002660 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002661 }
Eric Laurentd4692962014-05-05 18:13:44 -07002662 }
2663 if (profile->mChannelMasks[0] == 0) {
2664 reply = mpClientInterface->getParameters(output,
2665 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2666 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2667 reply.string());
2668 value = strpbrk((char *)reply.string(), "=");
2669 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002670 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002671 }
Eric Laurentd4692962014-05-05 18:13:44 -07002672 }
2673 if (((profile->mSamplingRates[0] == 0) &&
2674 (profile->mSamplingRates.size() < 2)) ||
2675 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2676 (profile->mFormats.size() < 2)) ||
2677 ((profile->mChannelMasks[0] == 0) &&
2678 (profile->mChannelMasks.size() < 2))) {
2679 ALOGW("checkOutputsForDevice() direct output missing param");
2680 mpClientInterface->closeOutput(output);
2681 output = 0;
2682 } else if (profile->mSamplingRates[0] == 0) {
2683 mpClientInterface->closeOutput(output);
2684 desc->mSamplingRate = profile->mSamplingRates[1];
2685 offloadInfo.sample_rate = desc->mSamplingRate;
2686 output = mpClientInterface->openOutput(
2687 profile->mModule->mHandle,
2688 &desc->mDevice,
2689 &desc->mSamplingRate,
2690 &desc->mFormat,
2691 &desc->mChannelMask,
2692 &desc->mLatency,
2693 desc->mFlags,
2694 &offloadInfo);
2695 }
2696
2697 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002698 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002699 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2700 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002701
Eric Laurentd4692962014-05-05 18:13:44 -07002702 // set initial stream volume for device
2703 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002704
Eric Laurentd4692962014-05-05 18:13:44 -07002705 //TODO: configure audio effect output stage here
2706
2707 // open a duplicating output thread for the new output and the primary output
2708 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2709 mPrimaryOutput);
2710 if (duplicatedOutput != 0) {
2711 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002712 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002713 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2714 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2715 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2716 dupOutputDesc->mFormat = desc->mFormat;
2717 dupOutputDesc->mChannelMask = desc->mChannelMask;
2718 dupOutputDesc->mLatency = desc->mLatency;
2719 addOutput(duplicatedOutput, dupOutputDesc);
2720 applyStreamVolumes(duplicatedOutput, device, 0, true);
2721 } else {
2722 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2723 mPrimaryOutput, output);
2724 mpClientInterface->closeOutput(output);
2725 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002726 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002727 output = 0;
2728 }
Eric Laurente552edb2014-03-10 17:42:56 -07002729 }
2730 }
2731 }
2732 if (output == 0) {
2733 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002734 profiles.removeAt(profile_index);
2735 profile_index--;
2736 } else {
2737 outputs.add(output);
2738 ALOGV("checkOutputsForDevice(): adding output %d", output);
2739 }
2740 }
2741
2742 if (profiles.isEmpty()) {
2743 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2744 return BAD_VALUE;
2745 }
Eric Laurentd4692962014-05-05 18:13:44 -07002746 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002747 // check if one opened output is not needed any more after disconnecting one device
2748 for (size_t i = 0; i < mOutputs.size(); i++) {
2749 desc = mOutputs.valueAt(i);
2750 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002751 !(desc->mProfile->mSupportedDevices.types() &
2752 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002753 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2754 outputs.add(mOutputs.keyAt(i));
2755 }
2756 }
Eric Laurentd4692962014-05-05 18:13:44 -07002757 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002758 for (size_t i = 0; i < mHwModules.size(); i++)
2759 {
2760 if (mHwModules[i]->mHandle == 0) {
2761 continue;
2762 }
2763 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2764 {
Eric Laurent951f4552014-05-20 10:48:17 -07002765 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002766 if (profile->mSupportedDevices.types() & device) {
2767 ALOGV("checkOutputsForDevice(): "
2768 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002769 if (profile->mSamplingRates[0] == 0) {
2770 profile->mSamplingRates.clear();
2771 profile->mSamplingRates.add(0);
2772 }
2773 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2774 profile->mFormats.clear();
2775 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2776 }
2777 if (profile->mChannelMasks[0] == 0) {
2778 profile->mChannelMasks.clear();
2779 profile->mChannelMasks.add(0);
2780 }
2781 }
2782 }
2783 }
2784 }
2785 return NO_ERROR;
2786}
2787
Eric Laurentd4692962014-05-05 18:13:44 -07002788status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2789 audio_policy_dev_state_t state,
2790 SortedVector<audio_io_handle_t>& inputs,
2791 const String8 address)
2792{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002793 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002794 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2795 // first list already open inputs that can be routed to this device
2796 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2797 desc = mInputs.valueAt(input_index);
2798 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2799 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2800 inputs.add(mInputs.keyAt(input_index));
2801 }
2802 }
2803
2804 // then look for input profiles that can be routed to this device
Eric Laurent951f4552014-05-20 10:48:17 -07002805 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002806 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2807 {
2808 if (mHwModules[module_idx]->mHandle == 0) {
2809 continue;
2810 }
2811 for (size_t profile_index = 0;
2812 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2813 profile_index++)
2814 {
2815 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2816 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2817 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2818 profile_index, module_idx);
2819 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2820 }
2821 }
2822 }
2823
2824 if (profiles.isEmpty() && inputs.isEmpty()) {
2825 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2826 return BAD_VALUE;
2827 }
2828
2829 // open inputs for matching profiles if needed. Direct inputs are also opened to
2830 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2831 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2832
Eric Laurent951f4552014-05-20 10:48:17 -07002833 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002834 // nothing to do if one input is already opened for this profile
2835 size_t input_index;
2836 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2837 desc = mInputs.valueAt(input_index);
2838 if (desc->mProfile == profile) {
2839 break;
2840 }
2841 }
2842 if (input_index != mInputs.size()) {
2843 continue;
2844 }
2845
2846 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2847 desc = new AudioInputDescriptor(profile);
2848 desc->mDevice = device;
2849
2850 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2851 &desc->mDevice,
2852 &desc->mSamplingRate,
2853 &desc->mFormat,
2854 &desc->mChannelMask);
2855
2856 if (input != 0) {
2857 if (!address.isEmpty()) {
2858 mpClientInterface->setParameters(input, addressToParameter(device, address));
2859 }
2860
2861 // Here is where we step through and resolve any "dynamic" fields
2862 String8 reply;
2863 char *value;
2864 if (profile->mSamplingRates[0] == 0) {
2865 reply = mpClientInterface->getParameters(input,
2866 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2867 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2868 reply.string());
2869 value = strpbrk((char *)reply.string(), "=");
2870 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002871 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002872 }
2873 }
2874 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2875 reply = mpClientInterface->getParameters(input,
2876 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2877 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2878 value = strpbrk((char *)reply.string(), "=");
2879 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002880 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002881 }
2882 }
2883 if (profile->mChannelMasks[0] == 0) {
2884 reply = mpClientInterface->getParameters(input,
2885 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2886 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2887 reply.string());
2888 value = strpbrk((char *)reply.string(), "=");
2889 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002890 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002891 }
2892 }
2893 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2894 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2895 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2896 ALOGW("checkInputsForDevice() direct input missing param");
2897 mpClientInterface->closeInput(input);
2898 input = 0;
2899 }
2900
2901 if (input != 0) {
2902 addInput(input, desc);
2903 }
2904 } // endif input != 0
2905
2906 if (input == 0) {
2907 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07002908 profiles.removeAt(profile_index);
2909 profile_index--;
2910 } else {
2911 inputs.add(input);
2912 ALOGV("checkInputsForDevice(): adding input %d", input);
2913 }
2914 } // end scan profiles
2915
2916 if (profiles.isEmpty()) {
2917 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2918 return BAD_VALUE;
2919 }
2920 } else {
2921 // Disconnect
2922 // check if one opened input is not needed any more after disconnecting one device
2923 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2924 desc = mInputs.valueAt(input_index);
2925 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2926 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2927 mInputs.keyAt(input_index));
2928 inputs.add(mInputs.keyAt(input_index));
2929 }
2930 }
2931 // Clear any profiles associated with the disconnected device.
2932 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2933 if (mHwModules[module_index]->mHandle == 0) {
2934 continue;
2935 }
2936 for (size_t profile_index = 0;
2937 profile_index < mHwModules[module_index]->mInputProfiles.size();
2938 profile_index++) {
Eric Laurent951f4552014-05-20 10:48:17 -07002939 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002940 if (profile->mSupportedDevices.types() & device) {
2941 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2942 profile_index, module_index);
2943 if (profile->mSamplingRates[0] == 0) {
2944 profile->mSamplingRates.clear();
2945 profile->mSamplingRates.add(0);
2946 }
2947 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2948 profile->mFormats.clear();
2949 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2950 }
2951 if (profile->mChannelMasks[0] == 0) {
2952 profile->mChannelMasks.clear();
2953 profile->mChannelMasks.add(0);
2954 }
2955 }
2956 }
2957 }
2958 } // end disconnect
2959
2960 return NO_ERROR;
2961}
2962
2963
Eric Laurente0720872014-03-11 09:30:41 -07002964void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002965{
2966 ALOGV("closeOutput(%d)", output);
2967
Eric Laurent1f2f2232014-06-02 12:01:23 -07002968 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07002969 if (outputDesc == NULL) {
2970 ALOGW("closeOutput() unknown output %d", output);
2971 return;
2972 }
2973
2974 // look for duplicated outputs connected to the output being removed.
2975 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002976 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002977 if (dupOutputDesc->isDuplicated() &&
2978 (dupOutputDesc->mOutput1 == outputDesc ||
2979 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002980 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07002981 if (dupOutputDesc->mOutput1 == outputDesc) {
2982 outputDesc2 = dupOutputDesc->mOutput2;
2983 } else {
2984 outputDesc2 = dupOutputDesc->mOutput1;
2985 }
2986 // As all active tracks on duplicated output will be deleted,
2987 // and as they were also referenced on the other output, the reference
2988 // count for their stream type must be adjusted accordingly on
2989 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07002990 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07002991 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07002992 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07002993 }
2994 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2995 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2996
2997 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002998 mOutputs.removeItem(duplicatedOutput);
2999 }
3000 }
3001
3002 AudioParameter param;
3003 param.add(String8("closing"), String8("true"));
3004 mpClientInterface->setParameters(output, param.toString());
3005
3006 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003007 mOutputs.removeItem(output);
3008 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003009 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003010}
3011
Eric Laurente0720872014-03-11 09:30:41 -07003012SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003013 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003014{
3015 SortedVector<audio_io_handle_t> outputs;
3016
3017 ALOGVV("getOutputsForDevice() device %04x", device);
3018 for (size_t i = 0; i < openOutputs.size(); i++) {
3019 ALOGVV("output %d isDuplicated=%d device=%04x",
3020 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3021 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3022 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3023 outputs.add(openOutputs.keyAt(i));
3024 }
3025 }
3026 return outputs;
3027}
3028
Eric Laurente0720872014-03-11 09:30:41 -07003029bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003030 SortedVector<audio_io_handle_t>& outputs2)
3031{
3032 if (outputs1.size() != outputs2.size()) {
3033 return false;
3034 }
3035 for (size_t i = 0; i < outputs1.size(); i++) {
3036 if (outputs1[i] != outputs2[i]) {
3037 return false;
3038 }
3039 }
3040 return true;
3041}
3042
Eric Laurente0720872014-03-11 09:30:41 -07003043void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003044{
3045 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3046 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3047 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3048 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3049
3050 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3051 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3052 strategy, srcOutputs[0], dstOutputs[0]);
3053 // mute strategy while moving tracks from one output to another
3054 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003055 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003056 if (desc->isStrategyActive(strategy)) {
3057 setStrategyMute(strategy, true, srcOutputs[i]);
3058 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3059 }
3060 }
3061
3062 // Move effects associated to this strategy from previous output to new output
3063 if (strategy == STRATEGY_MEDIA) {
3064 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3065 SortedVector<audio_io_handle_t> moved;
3066 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003067 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3068 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3069 effectDesc->mIo != fxOutput) {
3070 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003071 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3072 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003073 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003074 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003075 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003076 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003077 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003078 }
3079 }
3080 }
3081 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003082 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3083 if (getStrategy((audio_stream_type_t)i) == strategy) {
3084 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003085 }
3086 }
3087 }
3088}
3089
Eric Laurente0720872014-03-11 09:30:41 -07003090void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003091{
3092 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3093 checkOutputForStrategy(STRATEGY_PHONE);
3094 checkOutputForStrategy(STRATEGY_SONIFICATION);
3095 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3096 checkOutputForStrategy(STRATEGY_MEDIA);
3097 checkOutputForStrategy(STRATEGY_DTMF);
3098}
3099
Eric Laurente0720872014-03-11 09:30:41 -07003100audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003101{
Eric Laurente552edb2014-03-10 17:42:56 -07003102 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003103 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003104 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3105 return mOutputs.keyAt(i);
3106 }
3107 }
3108
3109 return 0;
3110}
3111
Eric Laurente0720872014-03-11 09:30:41 -07003112void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003113{
Eric Laurente552edb2014-03-10 17:42:56 -07003114 audio_io_handle_t a2dpOutput = getA2dpOutput();
3115 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003116 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003117 return;
3118 }
3119
Eric Laurent3a4311c2014-03-17 12:00:47 -07003120 bool isScoConnected =
3121 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003122 // suspend A2DP output if:
3123 // (NOT already suspended) &&
3124 // ((SCO device is connected &&
3125 // (forced usage for communication || for record is SCO))) ||
3126 // (phone state is ringing || in call)
3127 //
3128 // restore A2DP output if:
3129 // (Already suspended) &&
3130 // ((SCO device is NOT connected ||
3131 // (forced usage NOT for communication && NOT for record is SCO))) &&
3132 // (phone state is NOT ringing && NOT in call)
3133 //
3134 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003135 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003136 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3137 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3138 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3139 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003140
3141 mpClientInterface->restoreOutput(a2dpOutput);
3142 mA2dpSuspended = false;
3143 }
3144 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003145 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003146 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3147 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3148 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3149 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003150
3151 mpClientInterface->suspendOutput(a2dpOutput);
3152 mA2dpSuspended = true;
3153 }
3154 }
3155}
3156
Eric Laurent951f4552014-05-20 10:48:17 -07003157audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003158{
3159 audio_devices_t device = AUDIO_DEVICE_NONE;
3160
Eric Laurent1f2f2232014-06-02 12:01:23 -07003161 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003162
3163 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3164 if (index >= 0) {
3165 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3166 if (patchDesc->mUid != mUidCached) {
3167 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3168 outputDesc->device(), outputDesc->mPatchHandle);
3169 return outputDesc->device();
3170 }
3171 }
3172
Eric Laurente552edb2014-03-10 17:42:56 -07003173 // check the following by order of priority to request a routing change if necessary:
3174 // 1: the strategy enforced audible is active on the output:
3175 // use device for strategy enforced audible
3176 // 2: we are in call or the strategy phone is active on the output:
3177 // use device for strategy phone
3178 // 3: the strategy sonification is active on the output:
3179 // use device for strategy sonification
3180 // 4: the strategy "respectful" sonification is active on the output:
3181 // use device for strategy "respectful" sonification
3182 // 5: the strategy media is active on the output:
3183 // use device for strategy media
3184 // 6: the strategy DTMF is active on the output:
3185 // use device for strategy DTMF
3186 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3187 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3188 } else if (isInCall() ||
3189 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3190 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3191 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3192 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3193 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3194 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3195 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3196 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3197 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3198 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3199 }
3200
Eric Laurent951f4552014-05-20 10:48:17 -07003201 ALOGV("getNewOutputDevice() selected device %x", device);
3202 return device;
3203}
3204
3205audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3206{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003207 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003208
3209 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3210 if (index >= 0) {
3211 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3212 if (patchDesc->mUid != mUidCached) {
3213 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3214 inputDesc->mDevice, inputDesc->mPatchHandle);
3215 return inputDesc->mDevice;
3216 }
3217 }
3218
Eric Laurent951f4552014-05-20 10:48:17 -07003219 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3220
3221 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003222 return device;
3223}
3224
Eric Laurente0720872014-03-11 09:30:41 -07003225uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003226 return (uint32_t)getStrategy(stream);
3227}
3228
Eric Laurente0720872014-03-11 09:30:41 -07003229audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003230 // By checking the range of stream before calling getStrategy, we avoid
3231 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3232 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003233 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003234 return AUDIO_DEVICE_NONE;
3235 }
3236 audio_devices_t devices;
3237 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3238 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3239 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3240 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003241 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003242 if (outputDesc->isStrategyActive(strategy)) {
3243 devices = outputDesc->device();
3244 break;
3245 }
Eric Laurente552edb2014-03-10 17:42:56 -07003246 }
3247 return devices;
3248}
3249
Eric Laurente0720872014-03-11 09:30:41 -07003250AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003251 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003252 // stream to strategy mapping
3253 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003254 case AUDIO_STREAM_VOICE_CALL:
3255 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003256 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003257 case AUDIO_STREAM_RING:
3258 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003259 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003260 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003261 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003262 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003263 return STRATEGY_DTMF;
3264 default:
3265 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003266 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003267 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3268 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003269 case AUDIO_STREAM_TTS:
3270 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003271 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003272 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003273 return STRATEGY_ENFORCED_AUDIBLE;
3274 }
3275}
3276
Eric Laurente0720872014-03-11 09:30:41 -07003277void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003278 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003279 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003280 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3281 updateDevicesAndOutputs();
3282 break;
3283 default:
3284 break;
3285 }
3286}
3287
Eric Laurente0720872014-03-11 09:30:41 -07003288audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003289 bool fromCache)
3290{
3291 uint32_t device = AUDIO_DEVICE_NONE;
3292
3293 if (fromCache) {
3294 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3295 strategy, mDeviceForStrategy[strategy]);
3296 return mDeviceForStrategy[strategy];
3297 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003298 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003299 switch (strategy) {
3300
3301 case STRATEGY_SONIFICATION_RESPECTFUL:
3302 if (isInCall()) {
3303 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003304 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003305 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3306 // while media is playing on a remote device, use the the sonification behavior.
3307 // Note that we test this usecase before testing if media is playing because
3308 // the isStreamActive() method only informs about the activity of a stream, not
3309 // if it's for local playback. Note also that we use the same delay between both tests
3310 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003311 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003312 // while media is playing (or has recently played), use the same device
3313 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3314 } else {
3315 // when media is not playing anymore, fall back on the sonification behavior
3316 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3317 }
3318
3319 break;
3320
3321 case STRATEGY_DTMF:
3322 if (!isInCall()) {
3323 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3324 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3325 break;
3326 }
3327 // when in call, DTMF and PHONE strategies follow the same rules
3328 // FALL THROUGH
3329
3330 case STRATEGY_PHONE:
3331 // for phone strategy, we first consider the forced use and then the available devices by order
3332 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003333 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3334 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003335 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003336 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003337 if (device) break;
3338 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003339 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003340 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003341 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003342 if (device) break;
3343 // if SCO device is requested but no SCO device is available, fall back to default case
3344 // FALL THROUGH
3345
3346 default: // FORCE_NONE
3347 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003348 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003349 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003350 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003351 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003352 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003353 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003354 if (device) break;
3355 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003356 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003357 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003358 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003359 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003360 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003361 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003362 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003363 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003364 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003365 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003366 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003367 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003368 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003369 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003370 if (device) break;
3371 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003372 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003373 if (device) break;
Eric Laurent951f4552014-05-20 10:48:17 -07003374 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003375 if (device == AUDIO_DEVICE_NONE) {
3376 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3377 }
3378 break;
3379
Eric Laurent3b73df72014-03-11 09:06:29 -07003380 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003381 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3382 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003383 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003384 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003385 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003386 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003387 if (device) break;
3388 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003389 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003390 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003391 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003392 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003393 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003394 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003395 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003396 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003397 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003398 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003399 if (device) break;
3400 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003401 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003402 if (device) break;
Eric Laurent951f4552014-05-20 10:48:17 -07003403 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003404 if (device == AUDIO_DEVICE_NONE) {
3405 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3406 }
3407 break;
3408 }
3409 break;
3410
3411 case STRATEGY_SONIFICATION:
3412
3413 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3414 // handleIncallSonification().
3415 if (isInCall()) {
3416 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3417 break;
3418 }
3419 // FALL THROUGH
3420
3421 case STRATEGY_ENFORCED_AUDIBLE:
3422 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3423 // except:
3424 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3425 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3426
3427 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003428 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003429 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003430 if (device == AUDIO_DEVICE_NONE) {
3431 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3432 }
3433 }
3434 // The second device used for sonification is the same as the device used by media strategy
3435 // FALL THROUGH
3436
3437 case STRATEGY_MEDIA: {
3438 uint32_t device2 = AUDIO_DEVICE_NONE;
3439 if (strategy != STRATEGY_SONIFICATION) {
3440 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003441 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003442 }
3443 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003444 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003445 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003446 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003447 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003448 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003449 }
3450 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003451 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003452 }
3453 }
3454 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003455 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003456 }
3457 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003458 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003459 }
3460 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003461 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003462 }
3463 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003464 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003465 }
3466 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003467 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003468 }
3469 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3470 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003471 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003472 }
3473 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003474 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003475 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003476 }
3477 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003478 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003479 }
3480
3481 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3482 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3483 device |= device2;
3484 if (device) break;
Eric Laurent951f4552014-05-20 10:48:17 -07003485 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003486 if (device == AUDIO_DEVICE_NONE) {
3487 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3488 }
3489 } break;
3490
3491 default:
3492 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3493 break;
3494 }
3495
3496 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3497 return device;
3498}
3499
Eric Laurente0720872014-03-11 09:30:41 -07003500void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003501{
3502 for (int i = 0; i < NUM_STRATEGIES; i++) {
3503 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3504 }
3505 mPreviousOutputs = mOutputs;
3506}
3507
Eric Laurent1f2f2232014-06-02 12:01:23 -07003508uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003509 audio_devices_t prevDevice,
3510 uint32_t delayMs)
3511{
3512 // mute/unmute strategies using an incompatible device combination
3513 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3514 // if unmuting, unmute only after the specified delay
3515 if (outputDesc->isDuplicated()) {
3516 return 0;
3517 }
3518
3519 uint32_t muteWaitMs = 0;
3520 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003521 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003522
3523 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3524 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3525 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3526 bool doMute = false;
3527
3528 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3529 doMute = true;
3530 outputDesc->mStrategyMutedByDevice[i] = true;
3531 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3532 doMute = true;
3533 outputDesc->mStrategyMutedByDevice[i] = false;
3534 }
Eric Laurent99401132014-05-07 19:48:15 -07003535 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003536 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003537 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003538 // skip output if it does not share any device with current output
3539 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3540 == AUDIO_DEVICE_NONE) {
3541 continue;
3542 }
3543 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3544 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3545 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3546 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3547 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003548 if (mute) {
3549 // FIXME: should not need to double latency if volume could be applied
3550 // immediately by the audioflinger mixer. We must account for the delay
3551 // between now and the next time the audioflinger thread for this output
3552 // will process a buffer (which corresponds to one buffer size,
3553 // usually 1/2 or 1/4 of the latency).
3554 if (muteWaitMs < desc->latency() * 2) {
3555 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003556 }
3557 }
3558 }
3559 }
3560 }
3561 }
3562
Eric Laurent99401132014-05-07 19:48:15 -07003563 // temporary mute output if device selection changes to avoid volume bursts due to
3564 // different per device volumes
3565 if (outputDesc->isActive() && (device != prevDevice)) {
3566 if (muteWaitMs < outputDesc->latency() * 2) {
3567 muteWaitMs = outputDesc->latency() * 2;
3568 }
3569 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3570 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent951f4552014-05-20 10:48:17 -07003571 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003572 // do tempMute unmute after twice the mute wait time
Eric Laurent951f4552014-05-20 10:48:17 -07003573 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003574 muteWaitMs *2, device);
3575 }
3576 }
3577 }
3578
Eric Laurente552edb2014-03-10 17:42:56 -07003579 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3580 if (muteWaitMs > delayMs) {
3581 muteWaitMs -= delayMs;
3582 usleep(muteWaitMs * 1000);
3583 return muteWaitMs;
3584 }
3585 return 0;
3586}
3587
Eric Laurente0720872014-03-11 09:30:41 -07003588uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003589 audio_devices_t device,
3590 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003591 int delayMs,
3592 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003593{
3594 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003595 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003596 AudioParameter param;
3597 uint32_t muteWaitMs;
3598
3599 if (outputDesc->isDuplicated()) {
Eric Laurent951f4552014-05-20 10:48:17 -07003600 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3601 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003602 return muteWaitMs;
3603 }
3604 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3605 // output profile
3606 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003607 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003608 return 0;
3609 }
3610
3611 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003612 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003613
3614 audio_devices_t prevDevice = outputDesc->mDevice;
3615
3616 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3617
3618 if (device != AUDIO_DEVICE_NONE) {
3619 outputDesc->mDevice = device;
3620 }
3621 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3622
3623 // Do not change the routing if:
3624 // - the requested device is AUDIO_DEVICE_NONE
3625 // - the requested device is the same as current device and force is not specified.
3626 // Doing this check here allows the caller to call setOutputDevice() without conditions
3627 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3628 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3629 return muteWaitMs;
3630 }
3631
3632 ALOGV("setOutputDevice() changing device");
Eric Laurent951f4552014-05-20 10:48:17 -07003633
Eric Laurente552edb2014-03-10 17:42:56 -07003634 // do the routing
Eric Laurent951f4552014-05-20 10:48:17 -07003635 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003636 resetOutputDevice(output, delayMs, NULL);
Eric Laurent951f4552014-05-20 10:48:17 -07003637 } else {
3638 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3639 if (!deviceList.isEmpty()) {
3640 struct audio_patch patch;
3641 outputDesc->toAudioPortConfig(&patch.sources[0]);
3642 patch.num_sources = 1;
3643 patch.num_sinks = 0;
3644 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3645 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent951f4552014-05-20 10:48:17 -07003646 patch.num_sinks++;
3647 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003648 ssize_t index;
3649 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3650 index = mAudioPatches.indexOfKey(*patchHandle);
3651 } else {
3652 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3653 }
3654 sp< AudioPatch> patchDesc;
3655 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3656 if (index >= 0) {
3657 patchDesc = mAudioPatches.valueAt(index);
3658 afPatchHandle = patchDesc->mAfPatchHandle;
3659 }
3660
Eric Laurent951f4552014-05-20 10:48:17 -07003661 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003662 &afPatchHandle,
3663 delayMs);
Eric Laurent951f4552014-05-20 10:48:17 -07003664 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3665 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003666 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent951f4552014-05-20 10:48:17 -07003667 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003668 if (index < 0) {
3669 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3670 &patch, mUidCached);
3671 addAudioPatch(patchDesc->mHandle, patchDesc);
3672 } else {
3673 patchDesc->mPatch = patch;
3674 }
3675 patchDesc->mAfPatchHandle = afPatchHandle;
3676 patchDesc->mUid = mUidCached;
3677 if (patchHandle) {
3678 *patchHandle = patchDesc->mHandle;
3679 }
3680 outputDesc->mPatchHandle = patchDesc->mHandle;
3681 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003682 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent951f4552014-05-20 10:48:17 -07003683 }
3684 }
3685 }
Eric Laurente552edb2014-03-10 17:42:56 -07003686
3687 // update stream volumes according to new device
3688 applyStreamVolumes(output, device, delayMs);
3689
3690 return muteWaitMs;
3691}
3692
Eric Laurent951f4552014-05-20 10:48:17 -07003693status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003694 int delayMs,
3695 audio_patch_handle_t *patchHandle)
Eric Laurent951f4552014-05-20 10:48:17 -07003696{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003697 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003698 ssize_t index;
3699 if (patchHandle) {
3700 index = mAudioPatches.indexOfKey(*patchHandle);
3701 } else {
3702 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3703 }
3704 if (index < 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07003705 return INVALID_OPERATION;
3706 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003707 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3708 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent951f4552014-05-20 10:48:17 -07003709 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3710 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003711 removeAudioPatch(patchDesc->mHandle);
3712 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003713 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent951f4552014-05-20 10:48:17 -07003714 return status;
3715}
3716
3717status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3718 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003719 bool force,
3720 audio_patch_handle_t *patchHandle)
Eric Laurent951f4552014-05-20 10:48:17 -07003721{
3722 status_t status = NO_ERROR;
3723
Eric Laurent1f2f2232014-06-02 12:01:23 -07003724 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent951f4552014-05-20 10:48:17 -07003725 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3726 inputDesc->mDevice = device;
3727
3728 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3729 if (!deviceList.isEmpty()) {
3730 struct audio_patch patch;
3731 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3732 patch.num_sinks = 1;
3733 //only one input device for now
3734 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent951f4552014-05-20 10:48:17 -07003735 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003736 ssize_t index;
3737 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3738 index = mAudioPatches.indexOfKey(*patchHandle);
3739 } else {
3740 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3741 }
3742 sp< AudioPatch> patchDesc;
3743 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3744 if (index >= 0) {
3745 patchDesc = mAudioPatches.valueAt(index);
3746 afPatchHandle = patchDesc->mAfPatchHandle;
3747 }
3748
Eric Laurent951f4552014-05-20 10:48:17 -07003749 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003750 &afPatchHandle,
Eric Laurent951f4552014-05-20 10:48:17 -07003751 0);
3752 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003753 status, afPatchHandle);
Eric Laurent951f4552014-05-20 10:48:17 -07003754 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003755 if (index < 0) {
3756 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3757 &patch, mUidCached);
3758 addAudioPatch(patchDesc->mHandle, patchDesc);
3759 } else {
3760 patchDesc->mPatch = patch;
3761 }
3762 patchDesc->mAfPatchHandle = afPatchHandle;
3763 patchDesc->mUid = mUidCached;
3764 if (patchHandle) {
3765 *patchHandle = patchDesc->mHandle;
3766 }
3767 inputDesc->mPatchHandle = patchDesc->mHandle;
3768 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003769 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent951f4552014-05-20 10:48:17 -07003770 }
3771 }
3772 }
3773 return status;
3774}
3775
Eric Laurent6a94d692014-05-20 11:18:06 -07003776status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3777 audio_patch_handle_t *patchHandle)
Eric Laurent951f4552014-05-20 10:48:17 -07003778{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003779 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003780 ssize_t index;
3781 if (patchHandle) {
3782 index = mAudioPatches.indexOfKey(*patchHandle);
3783 } else {
3784 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3785 }
3786 if (index < 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07003787 return INVALID_OPERATION;
3788 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003789 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3790 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent951f4552014-05-20 10:48:17 -07003791 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3792 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003793 removeAudioPatch(patchDesc->mHandle);
3794 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003795 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent951f4552014-05-20 10:48:17 -07003796 return status;
3797}
3798
3799sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003800 uint32_t samplingRate,
3801 audio_format_t format,
3802 audio_channel_mask_t channelMask)
3803{
3804 // Choose an input profile based on the requested capture parameters: select the first available
3805 // profile supporting all requested parameters.
3806
3807 for (size_t i = 0; i < mHwModules.size(); i++)
3808 {
3809 if (mHwModules[i]->mHandle == 0) {
3810 continue;
3811 }
3812 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3813 {
Eric Laurent951f4552014-05-20 10:48:17 -07003814 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003815 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003816 if (profile->isCompatibleProfile(device, samplingRate, format,
3817 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3818 return profile;
3819 }
3820 }
3821 }
3822 return NULL;
3823}
3824
Eric Laurente0720872014-03-11 09:30:41 -07003825audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003826{
3827 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003828 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3829 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003830 switch (inputSource) {
3831 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003832 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003833 device = AUDIO_DEVICE_IN_VOICE_CALL;
3834 break;
3835 }
3836 // FALL THROUGH
3837
3838 case AUDIO_SOURCE_DEFAULT:
3839 case AUDIO_SOURCE_MIC:
3840 case AUDIO_SOURCE_VOICE_RECOGNITION:
3841 case AUDIO_SOURCE_HOTWORD:
3842 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003843 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003844 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003845 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003846 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003847 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003848 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3849 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003850 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003851 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3852 }
3853 break;
3854 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003855 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003856 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003857 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003858 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3859 }
3860 break;
3861 case AUDIO_SOURCE_VOICE_DOWNLINK:
3862 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003863 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003864 device = AUDIO_DEVICE_IN_VOICE_CALL;
3865 }
3866 break;
3867 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003868 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003869 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3870 }
3871 break;
3872 default:
3873 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3874 break;
3875 }
3876 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3877 return device;
3878}
3879
Eric Laurente0720872014-03-11 09:30:41 -07003880bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003881{
3882 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3883 device &= ~AUDIO_DEVICE_BIT_IN;
3884 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3885 return true;
3886 }
3887 return false;
3888}
3889
Eric Laurente0720872014-03-11 09:30:41 -07003890audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003891{
3892 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003893 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003894 if ((input_descriptor->mRefCount > 0)
3895 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3896 return mInputs.keyAt(i);
3897 }
3898 }
3899 return 0;
3900}
3901
3902
Eric Laurente0720872014-03-11 09:30:41 -07003903audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003904{
3905 if (device == AUDIO_DEVICE_NONE) {
3906 // this happens when forcing a route update and no track is active on an output.
3907 // In this case the returned category is not important.
3908 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003909 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003910 // Multiple device selection is either:
3911 // - speaker + one other device: give priority to speaker in this case.
3912 // - one A2DP device + another device: happens with duplicated output. In this case
3913 // retain the device on the A2DP output as the other must not correspond to an active
3914 // selection if not the speaker.
3915 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3916 device = AUDIO_DEVICE_OUT_SPEAKER;
3917 } else {
3918 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3919 }
3920 }
3921
Eric Laurent3b73df72014-03-11 09:06:29 -07003922 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003923 "getDeviceForVolume() invalid device combination: %08x",
3924 device);
3925
3926 return device;
3927}
3928
Eric Laurente0720872014-03-11 09:30:41 -07003929AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003930{
3931 switch(getDeviceForVolume(device)) {
3932 case AUDIO_DEVICE_OUT_EARPIECE:
3933 return DEVICE_CATEGORY_EARPIECE;
3934 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3935 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3936 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3937 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3938 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3939 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3940 return DEVICE_CATEGORY_HEADSET;
3941 case AUDIO_DEVICE_OUT_SPEAKER:
3942 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3943 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3944 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3945 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3946 case AUDIO_DEVICE_OUT_USB_DEVICE:
3947 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3948 default:
3949 return DEVICE_CATEGORY_SPEAKER;
3950 }
3951}
3952
Eric Laurente0720872014-03-11 09:30:41 -07003953float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003954 int indexInUi)
3955{
3956 device_category deviceCategory = getDeviceCategory(device);
3957 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3958
3959 // the volume index in the UI is relative to the min and max volume indices for this stream type
3960 int nbSteps = 1 + curve[VOLMAX].mIndex -
3961 curve[VOLMIN].mIndex;
3962 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3963 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3964
3965 // find what part of the curve this index volume belongs to, or if it's out of bounds
3966 int segment = 0;
3967 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3968 return 0.0f;
3969 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3970 segment = 0;
3971 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3972 segment = 1;
3973 } else if (volIdx <= curve[VOLMAX].mIndex) {
3974 segment = 2;
3975 } else { // out of bounds
3976 return 1.0f;
3977 }
3978
3979 // linear interpolation in the attenuation table in dB
3980 float decibels = curve[segment].mDBAttenuation +
3981 ((float)(volIdx - curve[segment].mIndex)) *
3982 ( (curve[segment+1].mDBAttenuation -
3983 curve[segment].mDBAttenuation) /
3984 ((float)(curve[segment+1].mIndex -
3985 curve[segment].mIndex)) );
3986
3987 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3988
3989 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3990 curve[segment].mIndex, volIdx,
3991 curve[segment+1].mIndex,
3992 curve[segment].mDBAttenuation,
3993 decibels,
3994 curve[segment+1].mDBAttenuation,
3995 amplification);
3996
3997 return amplification;
3998}
3999
Eric Laurente0720872014-03-11 09:30:41 -07004000const AudioPolicyManager::VolumeCurvePoint
4001 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004002 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4003};
4004
Eric Laurente0720872014-03-11 09:30:41 -07004005const AudioPolicyManager::VolumeCurvePoint
4006 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004007 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4008};
4009
Eric Laurente0720872014-03-11 09:30:41 -07004010const AudioPolicyManager::VolumeCurvePoint
4011 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004012 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4013};
4014
Eric Laurente0720872014-03-11 09:30:41 -07004015const AudioPolicyManager::VolumeCurvePoint
4016 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004017 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4018};
4019
Eric Laurente0720872014-03-11 09:30:41 -07004020const AudioPolicyManager::VolumeCurvePoint
4021 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004022 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4023};
4024
4025// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4026// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4027// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4028// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4029
Eric Laurente0720872014-03-11 09:30:41 -07004030const AudioPolicyManager::VolumeCurvePoint
4031 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004032 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4033};
4034
Eric Laurente0720872014-03-11 09:30:41 -07004035const AudioPolicyManager::VolumeCurvePoint
4036 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004037 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4038};
4039
Eric Laurente0720872014-03-11 09:30:41 -07004040const AudioPolicyManager::VolumeCurvePoint
4041 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004042 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4043};
4044
Eric Laurente0720872014-03-11 09:30:41 -07004045const AudioPolicyManager::VolumeCurvePoint
4046 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004047 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4048};
4049
Eric Laurente0720872014-03-11 09:30:41 -07004050const AudioPolicyManager::VolumeCurvePoint
4051 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004052 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4053};
4054
Eric Laurente0720872014-03-11 09:30:41 -07004055const AudioPolicyManager::VolumeCurvePoint
4056 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4057 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004058 { // AUDIO_STREAM_VOICE_CALL
4059 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4060 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4061 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4062 },
4063 { // AUDIO_STREAM_SYSTEM
4064 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4065 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4066 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4067 },
4068 { // AUDIO_STREAM_RING
4069 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4070 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4071 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4072 },
4073 { // AUDIO_STREAM_MUSIC
4074 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4075 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4076 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4077 },
4078 { // AUDIO_STREAM_ALARM
4079 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4080 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4081 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4082 },
4083 { // AUDIO_STREAM_NOTIFICATION
4084 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4085 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4086 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4087 },
4088 { // AUDIO_STREAM_BLUETOOTH_SCO
4089 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4090 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4091 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4092 },
4093 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4094 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4095 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4096 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4097 },
4098 { // AUDIO_STREAM_DTMF
4099 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4100 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4101 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4102 },
4103 { // AUDIO_STREAM_TTS
4104 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4105 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4106 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4107 },
4108};
4109
Eric Laurente0720872014-03-11 09:30:41 -07004110void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004111{
4112 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4113 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4114 mStreams[i].mVolumeCurve[j] =
4115 sVolumeProfiles[i][j];
4116 }
4117 }
4118
4119 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4120 if (mSpeakerDrcEnabled) {
4121 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4122 sDefaultSystemVolumeCurveDrc;
4123 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4124 sSpeakerSonificationVolumeCurveDrc;
4125 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4126 sSpeakerSonificationVolumeCurveDrc;
4127 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4128 sSpeakerSonificationVolumeCurveDrc;
4129 }
4130}
4131
Eric Laurente0720872014-03-11 09:30:41 -07004132float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004133 int index,
4134 audio_io_handle_t output,
4135 audio_devices_t device)
4136{
4137 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004138 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004139 StreamDescriptor &streamDesc = mStreams[stream];
4140
4141 if (device == AUDIO_DEVICE_NONE) {
4142 device = outputDesc->device();
4143 }
4144
4145 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004146 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004147 index != mStreams[stream].mIndexMin &&
4148 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
4149 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
4150 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
4151 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
4152 return 1.0;
4153 }
4154
4155 volume = volIndexToAmpl(device, streamDesc, index);
4156
4157 // if a headset is connected, apply the following rules to ring tones and notifications
4158 // to avoid sound level bursts in user's ears:
4159 // - always attenuate ring tones and notifications volume by 6dB
4160 // - if music is playing, always limit the volume to current music volume,
4161 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004162 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004163 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4164 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4165 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4166 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4167 ((stream_strategy == STRATEGY_SONIFICATION)
4168 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004169 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004170 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004171 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004172 streamDesc.mCanBeMuted) {
4173 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4174 // when the phone is ringing we must consider that music could have been paused just before
4175 // by the music application and behave as if music was active if the last music track was
4176 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004177 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004178 mLimitRingtoneVolume) {
4179 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004180 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4181 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004182 output,
4183 musicDevice);
4184 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4185 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4186 if (volume > minVol) {
4187 volume = minVol;
4188 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4189 }
4190 }
4191 }
4192
4193 return volume;
4194}
4195
Eric Laurente0720872014-03-11 09:30:41 -07004196status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004197 int index,
4198 audio_io_handle_t output,
4199 audio_devices_t device,
4200 int delayMs,
4201 bool force)
4202{
4203
4204 // do not change actual stream volume if the stream is muted
4205 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4206 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4207 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4208 return NO_ERROR;
4209 }
4210
4211 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004212 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4213 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4214 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4215 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004216 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004217 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004218 return INVALID_OPERATION;
4219 }
4220
4221 float volume = computeVolume(stream, index, output, device);
4222 // We actually change the volume if:
4223 // - the float value returned by computeVolume() changed
4224 // - the force flag is set
4225 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4226 force) {
4227 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4228 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4229 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4230 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004231 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4232 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004233 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004234 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004235 }
4236
Eric Laurent3b73df72014-03-11 09:06:29 -07004237 if (stream == AUDIO_STREAM_VOICE_CALL ||
4238 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004239 float voiceVolume;
4240 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004241 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004242 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4243 } else {
4244 voiceVolume = 1.0;
4245 }
4246
4247 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4248 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4249 mLastVoiceVolume = voiceVolume;
4250 }
4251 }
4252
4253 return NO_ERROR;
4254}
4255
Eric Laurente0720872014-03-11 09:30:41 -07004256void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004257 audio_devices_t device,
4258 int delayMs,
4259 bool force)
4260{
4261 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4262
Eric Laurent3b73df72014-03-11 09:06:29 -07004263 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4264 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004265 mStreams[stream].getVolumeIndex(device),
4266 output,
4267 device,
4268 delayMs,
4269 force);
4270 }
4271}
4272
Eric Laurente0720872014-03-11 09:30:41 -07004273void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004274 bool on,
4275 audio_io_handle_t output,
4276 int delayMs,
4277 audio_devices_t device)
4278{
4279 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004280 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4281 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4282 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004283 }
4284 }
4285}
4286
Eric Laurente0720872014-03-11 09:30:41 -07004287void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004288 bool on,
4289 audio_io_handle_t output,
4290 int delayMs,
4291 audio_devices_t device)
4292{
4293 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004294 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004295 if (device == AUDIO_DEVICE_NONE) {
4296 device = outputDesc->device();
4297 }
4298
4299 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4300 stream, on, output, outputDesc->mMuteCount[stream], device);
4301
4302 if (on) {
4303 if (outputDesc->mMuteCount[stream] == 0) {
4304 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004305 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4306 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004307 checkAndSetVolume(stream, 0, output, device, delayMs);
4308 }
4309 }
4310 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4311 outputDesc->mMuteCount[stream]++;
4312 } else {
4313 if (outputDesc->mMuteCount[stream] == 0) {
4314 ALOGV("setStreamMute() unmuting non muted stream!");
4315 return;
4316 }
4317 if (--outputDesc->mMuteCount[stream] == 0) {
4318 checkAndSetVolume(stream,
4319 streamDesc.getVolumeIndex(device),
4320 output,
4321 device,
4322 delayMs);
4323 }
4324 }
4325}
4326
Eric Laurente0720872014-03-11 09:30:41 -07004327void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004328 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004329{
4330 // if the stream pertains to sonification strategy and we are in call we must
4331 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4332 // in the device used for phone strategy and play the tone if the selected device does not
4333 // interfere with the device used for phone strategy
4334 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4335 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004336 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004337 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4338 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004339 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004340 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4341 stream, starting, outputDesc->mDevice, stateChange);
4342 if (outputDesc->mRefCount[stream]) {
4343 int muteCount = 1;
4344 if (stateChange) {
4345 muteCount = outputDesc->mRefCount[stream];
4346 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004347 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004348 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4349 for (int i = 0; i < muteCount; i++) {
4350 setStreamMute(stream, starting, mPrimaryOutput);
4351 }
4352 } else {
4353 ALOGV("handleIncallSonification() high visibility");
4354 if (outputDesc->device() &
4355 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4356 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4357 for (int i = 0; i < muteCount; i++) {
4358 setStreamMute(stream, starting, mPrimaryOutput);
4359 }
4360 }
4361 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004362 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4363 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004364 } else {
4365 mpClientInterface->stopTone();
4366 }
4367 }
4368 }
4369 }
4370}
4371
Eric Laurente0720872014-03-11 09:30:41 -07004372bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004373{
4374 return isStateInCall(mPhoneState);
4375}
4376
Eric Laurente0720872014-03-11 09:30:41 -07004377bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004378 return ((state == AUDIO_MODE_IN_CALL) ||
4379 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004380}
4381
Eric Laurente0720872014-03-11 09:30:41 -07004382uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004383{
4384 return MAX_EFFECTS_CPU_LOAD;
4385}
4386
Eric Laurente0720872014-03-11 09:30:41 -07004387uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004388{
4389 return MAX_EFFECTS_MEMORY;
4390}
4391
Eric Laurent6a94d692014-05-20 11:18:06 -07004392
Eric Laurente552edb2014-03-10 17:42:56 -07004393// --- AudioOutputDescriptor class implementation
4394
Eric Laurente0720872014-03-11 09:30:41 -07004395AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent951f4552014-05-20 10:48:17 -07004396 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004397 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent951f4552014-05-20 10:48:17 -07004398 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004399 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4400{
4401 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004402 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004403 mRefCount[i] = 0;
4404 mCurVolume[i] = -1.0;
4405 mMuteCount[i] = 0;
4406 mStopTime[i] = 0;
4407 }
4408 for (int i = 0; i < NUM_STRATEGIES; i++) {
4409 mStrategyMutedByDevice[i] = false;
4410 }
4411 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004412 mAudioPort = profile;
Eric Laurente552edb2014-03-10 17:42:56 -07004413 mSamplingRate = profile->mSamplingRates[0];
4414 mFormat = profile->mFormats[0];
4415 mChannelMask = profile->mChannelMasks[0];
4416 mFlags = profile->mFlags;
4417 }
4418}
4419
Eric Laurente0720872014-03-11 09:30:41 -07004420audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004421{
4422 if (isDuplicated()) {
4423 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4424 } else {
4425 return mDevice;
4426 }
4427}
4428
Eric Laurente0720872014-03-11 09:30:41 -07004429uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004430{
4431 if (isDuplicated()) {
4432 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4433 } else {
4434 return mLatency;
4435 }
4436}
4437
Eric Laurente0720872014-03-11 09:30:41 -07004438bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004439 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004440{
4441 if (isDuplicated()) {
4442 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4443 } else if (outputDesc->isDuplicated()){
4444 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4445 } else {
4446 return (mProfile->mModule == outputDesc->mProfile->mModule);
4447 }
4448}
4449
Eric Laurente0720872014-03-11 09:30:41 -07004450void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004451 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004452{
4453 // forward usage count change to attached outputs
4454 if (isDuplicated()) {
4455 mOutput1->changeRefCount(stream, delta);
4456 mOutput2->changeRefCount(stream, delta);
4457 }
4458 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004459 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4460 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004461 mRefCount[stream] = 0;
4462 return;
4463 }
4464 mRefCount[stream] += delta;
4465 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4466}
4467
Eric Laurente0720872014-03-11 09:30:41 -07004468audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004469{
4470 if (isDuplicated()) {
4471 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4472 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004473 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004474 }
4475}
4476
Eric Laurente0720872014-03-11 09:30:41 -07004477bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004478{
4479 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4480}
4481
Eric Laurente0720872014-03-11 09:30:41 -07004482bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004483 uint32_t inPastMs,
4484 nsecs_t sysTime) const
4485{
4486 if ((sysTime == 0) && (inPastMs != 0)) {
4487 sysTime = systemTime();
4488 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004489 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4490 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004491 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004492 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004493 return true;
4494 }
4495 }
4496 return false;
4497}
4498
Eric Laurente0720872014-03-11 09:30:41 -07004499bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004500 uint32_t inPastMs,
4501 nsecs_t sysTime) const
4502{
4503 if (mRefCount[stream] != 0) {
4504 return true;
4505 }
4506 if (inPastMs == 0) {
4507 return false;
4508 }
4509 if (sysTime == 0) {
4510 sysTime = systemTime();
4511 }
4512 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4513 return true;
4514 }
4515 return false;
4516}
4517
Eric Laurent951f4552014-05-20 10:48:17 -07004518void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004519 struct audio_port_config *dstConfig,
4520 const struct audio_port_config *srcConfig) const
Eric Laurent951f4552014-05-20 10:48:17 -07004521{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004522 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4523 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4524 if (srcConfig != NULL) {
4525 dstConfig->config_mask &= srcConfig->config_mask;
4526 }
4527 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4528
Eric Laurent6a94d692014-05-20 11:18:06 -07004529 dstConfig->id = mId;
4530 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4531 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004532 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4533 dstConfig->ext.mix.handle = mIoHandle;
4534 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent951f4552014-05-20 10:48:17 -07004535}
4536
4537void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4538 struct audio_port *port) const
4539{
4540 mProfile->toAudioPort(port);
4541 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004542 toAudioPortConfig(&port->active_config);
4543 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent951f4552014-05-20 10:48:17 -07004544 port->ext.mix.handle = mIoHandle;
4545 port->ext.mix.latency_class =
4546 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4547}
Eric Laurente552edb2014-03-10 17:42:56 -07004548
Eric Laurente0720872014-03-11 09:30:41 -07004549status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004550{
4551 const size_t SIZE = 256;
4552 char buffer[SIZE];
4553 String8 result;
4554
4555 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4556 result.append(buffer);
4557 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4558 result.append(buffer);
4559 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4560 result.append(buffer);
4561 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4562 result.append(buffer);
4563 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4564 result.append(buffer);
4565 snprintf(buffer, SIZE, " Devices %08x\n", device());
4566 result.append(buffer);
4567 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4568 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004569 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4570 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4571 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004572 result.append(buffer);
4573 }
4574 write(fd, result.string(), result.size());
4575
4576 return NO_ERROR;
4577}
4578
4579// --- AudioInputDescriptor class implementation
4580
Eric Laurent951f4552014-05-20 10:48:17 -07004581AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004582 : mId(0), mIoHandle(0),
Eric Laurent951f4552014-05-20 10:48:17 -07004583 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004584 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004585{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004586 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004587 mAudioPort = profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004588 mSamplingRate = profile->mSamplingRates[0];
4589 mFormat = profile->mFormats[0];
4590 mChannelMask = profile->mChannelMasks[0];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004591 } else {
4592 mSamplingRate = 0;
4593 mFormat = AUDIO_FORMAT_DEFAULT;
4594 mChannelMask = 0;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004595 }
Eric Laurente552edb2014-03-10 17:42:56 -07004596}
4597
Eric Laurent951f4552014-05-20 10:48:17 -07004598void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004599 struct audio_port_config *dstConfig,
4600 const struct audio_port_config *srcConfig) const
Eric Laurent951f4552014-05-20 10:48:17 -07004601{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004602 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4603 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4604 if (srcConfig != NULL) {
4605 dstConfig->config_mask &= srcConfig->config_mask;
4606 }
4607
4608 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4609
Eric Laurent6a94d692014-05-20 11:18:06 -07004610 dstConfig->id = mId;
4611 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4612 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004613 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4614 dstConfig->ext.mix.handle = mIoHandle;
4615 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent951f4552014-05-20 10:48:17 -07004616}
4617
4618void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4619 struct audio_port *port) const
4620{
4621 mProfile->toAudioPort(port);
4622 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004623 toAudioPortConfig(&port->active_config);
4624 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent951f4552014-05-20 10:48:17 -07004625 port->ext.mix.handle = mIoHandle;
4626 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4627}
4628
Eric Laurente0720872014-03-11 09:30:41 -07004629status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004630{
4631 const size_t SIZE = 256;
4632 char buffer[SIZE];
4633 String8 result;
4634
4635 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4636 result.append(buffer);
4637 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4638 result.append(buffer);
4639 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4640 result.append(buffer);
4641 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4642 result.append(buffer);
4643 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4644 result.append(buffer);
4645 write(fd, result.string(), result.size());
4646
4647 return NO_ERROR;
4648}
4649
4650// --- StreamDescriptor class implementation
4651
Eric Laurente0720872014-03-11 09:30:41 -07004652AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004653 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4654{
4655 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4656}
4657
Eric Laurente0720872014-03-11 09:30:41 -07004658int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004659{
Eric Laurente0720872014-03-11 09:30:41 -07004660 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4662 if (mIndexCur.indexOfKey(device) < 0) {
4663 device = AUDIO_DEVICE_OUT_DEFAULT;
4664 }
4665 return mIndexCur.valueFor(device);
4666}
4667
Eric Laurente0720872014-03-11 09:30:41 -07004668void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004669{
4670 const size_t SIZE = 256;
4671 char buffer[SIZE];
4672 String8 result;
4673
4674 snprintf(buffer, SIZE, "%s %02d %02d ",
4675 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4676 result.append(buffer);
4677 for (size_t i = 0; i < mIndexCur.size(); i++) {
4678 snprintf(buffer, SIZE, "%04x : %02d, ",
4679 mIndexCur.keyAt(i),
4680 mIndexCur.valueAt(i));
4681 result.append(buffer);
4682 }
4683 result.append("\n");
4684
4685 write(fd, result.string(), result.size());
4686}
4687
4688// --- EffectDescriptor class implementation
4689
Eric Laurente0720872014-03-11 09:30:41 -07004690status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004691{
4692 const size_t SIZE = 256;
4693 char buffer[SIZE];
4694 String8 result;
4695
4696 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4697 result.append(buffer);
4698 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4699 result.append(buffer);
4700 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4701 result.append(buffer);
4702 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4703 result.append(buffer);
4704 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4705 result.append(buffer);
4706 write(fd, result.string(), result.size());
4707
4708 return NO_ERROR;
4709}
4710
Eric Laurent951f4552014-05-20 10:48:17 -07004711// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004712
Eric Laurente0720872014-03-11 09:30:41 -07004713AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07004714 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
4715{
4716}
4717
Eric Laurente0720872014-03-11 09:30:41 -07004718AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004719{
4720 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004721 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004722 }
4723 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004724 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004725 }
4726 free((void *)mName);
4727}
4728
Eric Laurent1afeecb2014-05-14 08:52:28 -07004729status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4730{
4731 cnode *node = root->first_child;
4732
4733 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4734
4735 while (node) {
4736 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4737 profile->loadSamplingRates((char *)node->value);
4738 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4739 profile->loadFormats((char *)node->value);
4740 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4741 profile->loadInChannels((char *)node->value);
4742 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4743 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4744 mDeclaredDevices);
4745 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4746 profile->loadGains(node);
4747 }
4748 node = node->next;
4749 }
4750 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4751 "loadInput() invalid supported devices");
4752 ALOGW_IF(profile->mChannelMasks.size() == 0,
4753 "loadInput() invalid supported channel masks");
4754 ALOGW_IF(profile->mSamplingRates.size() == 0,
4755 "loadInput() invalid supported sampling rates");
4756 ALOGW_IF(profile->mFormats.size() == 0,
4757 "loadInput() invalid supported formats");
4758 if (!profile->mSupportedDevices.isEmpty() &&
4759 (profile->mChannelMasks.size() != 0) &&
4760 (profile->mSamplingRates.size() != 0) &&
4761 (profile->mFormats.size() != 0)) {
4762
4763 ALOGV("loadInput() adding input Supported Devices %04x",
4764 profile->mSupportedDevices.types());
4765
4766 mInputProfiles.add(profile);
4767 return NO_ERROR;
4768 } else {
4769 return BAD_VALUE;
4770 }
4771}
4772
4773status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4774{
4775 cnode *node = root->first_child;
4776
4777 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4778
4779 while (node) {
4780 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4781 profile->loadSamplingRates((char *)node->value);
4782 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4783 profile->loadFormats((char *)node->value);
4784 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4785 profile->loadOutChannels((char *)node->value);
4786 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4787 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4788 mDeclaredDevices);
4789 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4790 profile->mFlags = parseFlagNames((char *)node->value);
4791 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4792 profile->loadGains(node);
4793 }
4794 node = node->next;
4795 }
4796 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4797 "loadOutput() invalid supported devices");
4798 ALOGW_IF(profile->mChannelMasks.size() == 0,
4799 "loadOutput() invalid supported channel masks");
4800 ALOGW_IF(profile->mSamplingRates.size() == 0,
4801 "loadOutput() invalid supported sampling rates");
4802 ALOGW_IF(profile->mFormats.size() == 0,
4803 "loadOutput() invalid supported formats");
4804 if (!profile->mSupportedDevices.isEmpty() &&
4805 (profile->mChannelMasks.size() != 0) &&
4806 (profile->mSamplingRates.size() != 0) &&
4807 (profile->mFormats.size() != 0)) {
4808
4809 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4810 profile->mSupportedDevices.types(), profile->mFlags);
4811
4812 mOutputProfiles.add(profile);
4813 return NO_ERROR;
4814 } else {
4815 return BAD_VALUE;
4816 }
4817}
4818
4819status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4820{
4821 cnode *node = root->first_child;
4822
4823 audio_devices_t type = AUDIO_DEVICE_NONE;
4824 while (node) {
4825 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4826 type = parseDeviceNames((char *)node->value);
4827 break;
4828 }
4829 node = node->next;
4830 }
4831 if (type == AUDIO_DEVICE_NONE ||
4832 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4833 ALOGW("loadDevice() bad type %08x", type);
4834 return BAD_VALUE;
4835 }
4836 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4837 deviceDesc->mModule = this;
4838
4839 node = root->first_child;
4840 while (node) {
4841 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4842 deviceDesc->mAddress = String8((char *)node->value);
4843 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4844 if (audio_is_input_device(type)) {
4845 deviceDesc->loadInChannels((char *)node->value);
4846 } else {
4847 deviceDesc->loadOutChannels((char *)node->value);
4848 }
4849 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4850 deviceDesc->loadGains(node);
4851 }
4852 node = node->next;
4853 }
4854
4855 ALOGV("loadDevice() adding device name %s type %08x address %s",
4856 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4857
4858 mDeclaredDevices.add(deviceDesc);
4859
4860 return NO_ERROR;
4861}
4862
Eric Laurente0720872014-03-11 09:30:41 -07004863void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004864{
4865 const size_t SIZE = 256;
4866 char buffer[SIZE];
4867 String8 result;
4868
4869 snprintf(buffer, SIZE, " - name: %s\n", mName);
4870 result.append(buffer);
4871 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4872 result.append(buffer);
4873 write(fd, result.string(), result.size());
4874 if (mOutputProfiles.size()) {
4875 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4876 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004877 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004878 write(fd, buffer, strlen(buffer));
4879 mOutputProfiles[i]->dump(fd);
4880 }
4881 }
4882 if (mInputProfiles.size()) {
4883 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4884 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004885 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004886 write(fd, buffer, strlen(buffer));
4887 mInputProfiles[i]->dump(fd);
4888 }
4889 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07004890 if (mDeclaredDevices.size()) {
4891 write(fd, " - devices:\n", strlen(" - devices:\n"));
4892 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
4893 mDeclaredDevices[i]->dump(fd, 4, i);
4894 }
4895 }
Eric Laurente552edb2014-03-10 17:42:56 -07004896}
4897
Eric Laurent951f4552014-05-20 10:48:17 -07004898// --- AudioPort class implementation
4899
4900void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
4901{
4902 port->role = mRole;
4903 port->type = mType;
4904 unsigned int i;
4905 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
4906 port->sample_rates[i] = mSamplingRates[i];
4907 }
4908 port->num_sample_rates = i;
4909 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
4910 port->channel_masks[i] = mChannelMasks[i];
4911 }
4912 port->num_channel_masks = i;
4913 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
4914 port->formats[i] = mFormats[i];
4915 }
4916 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07004917
4918 ALOGV("AudioPort::toAudioPort() num gains %d", mGains.size());
4919
4920 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
4921 port->gains[i] = mGains[i]->mGain;
4922 }
4923 port->num_gains = i;
Eric Laurent951f4552014-05-20 10:48:17 -07004924}
4925
4926
4927void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
4928{
4929 char *str = strtok(name, "|");
4930
4931 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4932 // rates should be read from the output stream after it is opened for the first time
4933 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4934 mSamplingRates.add(0);
4935 return;
4936 }
4937
4938 while (str != NULL) {
4939 uint32_t rate = atoi(str);
4940 if (rate != 0) {
4941 ALOGV("loadSamplingRates() adding rate %d", rate);
4942 mSamplingRates.add(rate);
4943 }
4944 str = strtok(NULL, "|");
4945 }
Eric Laurent951f4552014-05-20 10:48:17 -07004946}
4947
4948void AudioPolicyManager::AudioPort::loadFormats(char *name)
4949{
4950 char *str = strtok(name, "|");
4951
4952 // by convention, "0' in the first entry in mFormats indicates the supported formats
4953 // should be read from the output stream after it is opened for the first time
4954 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4955 mFormats.add(AUDIO_FORMAT_DEFAULT);
4956 return;
4957 }
4958
4959 while (str != NULL) {
4960 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4961 ARRAY_SIZE(sFormatNameToEnumTable),
4962 str);
4963 if (format != AUDIO_FORMAT_DEFAULT) {
4964 mFormats.add(format);
4965 }
4966 str = strtok(NULL, "|");
4967 }
Eric Laurent951f4552014-05-20 10:48:17 -07004968}
4969
4970void AudioPolicyManager::AudioPort::loadInChannels(char *name)
4971{
4972 const char *str = strtok(name, "|");
4973
4974 ALOGV("loadInChannels() %s", name);
4975
4976 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4977 mChannelMasks.add(0);
4978 return;
4979 }
4980
4981 while (str != NULL) {
4982 audio_channel_mask_t channelMask =
4983 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4984 ARRAY_SIZE(sInChannelsNameToEnumTable),
4985 str);
4986 if (channelMask != 0) {
4987 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4988 mChannelMasks.add(channelMask);
4989 }
4990 str = strtok(NULL, "|");
4991 }
Eric Laurent951f4552014-05-20 10:48:17 -07004992}
4993
4994void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
4995{
4996 const char *str = strtok(name, "|");
4997
4998 ALOGV("loadOutChannels() %s", name);
4999
5000 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5001 // masks should be read from the output stream after it is opened for the first time
5002 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5003 mChannelMasks.add(0);
5004 return;
5005 }
5006
5007 while (str != NULL) {
5008 audio_channel_mask_t channelMask =
5009 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5010 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5011 str);
5012 if (channelMask != 0) {
5013 mChannelMasks.add(channelMask);
5014 }
5015 str = strtok(NULL, "|");
5016 }
5017 return;
5018}
5019
Eric Laurent1afeecb2014-05-14 08:52:28 -07005020audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5021{
5022 const char *str = strtok(name, "|");
5023
5024 ALOGV("loadGainMode() %s", name);
5025 audio_gain_mode_t mode = 0;
5026 while (str != NULL) {
5027 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5028 ARRAY_SIZE(sGainModeNameToEnumTable),
5029 str);
5030 str = strtok(NULL, "|");
5031 }
5032 return mode;
5033}
5034
5035void AudioPolicyManager::AudioPort::loadGain(cnode *root)
5036{
5037 cnode *node = root->first_child;
5038
5039 sp<AudioGain> gain = new AudioGain();
5040
5041 while (node) {
5042 if (strcmp(node->name, GAIN_MODE) == 0) {
5043 gain->mGain.mode = loadGainMode((char *)node->value);
5044 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
5045 if ((mType == AUDIO_PORT_TYPE_DEVICE && mRole == AUDIO_PORT_ROLE_SOURCE) ||
5046 (mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK)) {
5047 gain->mGain.channel_mask =
5048 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5049 ARRAY_SIZE(sInChannelsNameToEnumTable),
5050 (char *)node->value);
5051 } else {
5052 gain->mGain.channel_mask =
5053 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5054 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5055 (char *)node->value);
5056 }
5057 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5058 gain->mGain.min_value = atoi((char *)node->value);
5059 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5060 gain->mGain.max_value = atoi((char *)node->value);
5061 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5062 gain->mGain.default_value = atoi((char *)node->value);
5063 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5064 gain->mGain.step_value = atoi((char *)node->value);
5065 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5066 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5067 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5068 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5069 }
5070 node = node->next;
5071 }
5072
5073 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5074 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5075
5076 if (gain->mGain.mode == 0) {
5077 return;
5078 }
5079 mGains.add(gain);
5080}
5081
5082void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5083{
5084 cnode *node = root->first_child;
5085 while (node) {
5086 ALOGV("loadGains() loading gain %s", node->name);
5087 loadGain(node);
5088 node = node->next;
5089 }
5090}
5091
5092void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5093{
5094 const size_t SIZE = 256;
5095 char buffer[SIZE];
5096 String8 result;
5097
5098 if (mName.size() != 0) {
5099 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5100 result.append(buffer);
5101 }
5102
5103 if (mSamplingRates.size() != 0) {
5104 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5105 result.append(buffer);
5106 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5107 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5108 result.append(buffer);
5109 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5110 }
5111 result.append("\n");
5112 }
5113
5114 if (mChannelMasks.size() != 0) {
5115 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5116 result.append(buffer);
5117 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5118 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5119 result.append(buffer);
5120 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5121 }
5122 result.append("\n");
5123 }
5124
5125 if (mFormats.size() != 0) {
5126 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5127 result.append(buffer);
5128 for (size_t i = 0; i < mFormats.size(); i++) {
5129 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5130 ARRAY_SIZE(sFormatNameToEnumTable),
5131 mFormats[i]));
5132 result.append(buffer);
5133 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5134 }
5135 result.append("\n");
5136 }
5137 write(fd, result.string(), result.size());
5138 if (mGains.size() != 0) {
5139 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5140 write(fd, buffer, strlen(buffer) + 1);
5141 result.append(buffer);
5142 for (size_t i = 0; i < mGains.size(); i++) {
5143 mGains[i]->dump(fd, spaces + 2, i);
5144 }
5145 }
5146}
5147
5148// --- AudioGain class implementation
5149
5150AudioPolicyManager::AudioGain::AudioGain()
5151{
5152 memset(&mGain, 0, sizeof(struct audio_gain));
5153}
5154
5155void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5156{
5157 const size_t SIZE = 256;
5158 char buffer[SIZE];
5159 String8 result;
5160
5161 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5162 result.append(buffer);
5163 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5164 result.append(buffer);
5165 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5166 result.append(buffer);
5167 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5168 result.append(buffer);
5169 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5170 result.append(buffer);
5171 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5172 result.append(buffer);
5173 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5174 result.append(buffer);
5175 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5176 result.append(buffer);
5177 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5178 result.append(buffer);
5179
5180 write(fd, result.string(), result.size());
5181}
5182
Eric Laurent1f2f2232014-06-02 12:01:23 -07005183// --- AudioPortConfig class implementation
5184
5185AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5186{
5187 mSamplingRate = 0;
5188 mChannelMask = AUDIO_CHANNEL_NONE;
5189 mFormat = AUDIO_FORMAT_INVALID;
5190 mGain.index = -1;
5191}
5192
5193void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5194 struct audio_port_config *dstConfig,
5195 const struct audio_port_config *srcConfig) const
5196{
5197 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5198 dstConfig->sample_rate = mSamplingRate;
5199 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5200 dstConfig->sample_rate = srcConfig->sample_rate;
5201 }
5202 } else {
5203 dstConfig->sample_rate = 0;
5204 }
5205 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5206 dstConfig->channel_mask = mChannelMask;
5207 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5208 dstConfig->channel_mask = srcConfig->channel_mask;
5209 }
5210 } else {
5211 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5212 }
5213 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5214 dstConfig->format = mFormat;
5215 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5216 dstConfig->format = srcConfig->format;
5217 }
5218 } else {
5219 dstConfig->format = AUDIO_FORMAT_INVALID;
5220 }
5221 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5222 dstConfig->gain = mGain;
5223 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5224 dstConfig->gain = srcConfig->gain;
5225 }
5226 } else {
5227 dstConfig->gain.index = -1;
5228 }
5229 if (dstConfig->gain.index != -1) {
5230 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5231 } else {
5232 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5233 }
5234}
5235
Eric Laurent951f4552014-05-20 10:48:17 -07005236// --- IOProfile class implementation
5237
Eric Laurent1afeecb2014-05-14 08:52:28 -07005238AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005239 const sp<HwModule>& module)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005240 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005241{
5242}
5243
Eric Laurente0720872014-03-11 09:30:41 -07005244AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005245{
5246}
5247
5248// checks if the IO profile is compatible with specified parameters.
5249// Sampling rate, format and channel mask must be specified in order to
5250// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005251bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005252 uint32_t samplingRate,
5253 audio_format_t format,
5254 audio_channel_mask_t channelMask,
5255 audio_output_flags_t flags) const
5256{
5257 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5258 return false;
5259 }
5260
Eric Laurent3a4311c2014-03-17 12:00:47 -07005261 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005262 return false;
5263 }
5264 if ((mFlags & flags) != flags) {
5265 return false;
5266 }
5267 size_t i;
5268 for (i = 0; i < mSamplingRates.size(); i++)
5269 {
5270 if (mSamplingRates[i] == samplingRate) {
5271 break;
5272 }
5273 }
5274 if (i == mSamplingRates.size()) {
5275 return false;
5276 }
5277 for (i = 0; i < mFormats.size(); i++)
5278 {
5279 if (mFormats[i] == format) {
5280 break;
5281 }
5282 }
5283 if (i == mFormats.size()) {
5284 return false;
5285 }
5286 for (i = 0; i < mChannelMasks.size(); i++)
5287 {
5288 if (mChannelMasks[i] == channelMask) {
5289 break;
5290 }
5291 }
5292 if (i == mChannelMasks.size()) {
5293 return false;
5294 }
5295 return true;
5296}
5297
Eric Laurente0720872014-03-11 09:30:41 -07005298void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005299{
5300 const size_t SIZE = 256;
5301 char buffer[SIZE];
5302 String8 result;
5303
Eric Laurent1afeecb2014-05-14 08:52:28 -07005304 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005305
Eric Laurente552edb2014-03-10 17:42:56 -07005306 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5307 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005308 snprintf(buffer, SIZE, " - devices:\n");
5309 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005310 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005311 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5312 mSupportedDevices[i]->dump(fd, 6, i);
5313 }
Eric Laurente552edb2014-03-10 17:42:56 -07005314}
5315
Eric Laurentd4692962014-05-05 18:13:44 -07005316void AudioPolicyManager::IOProfile::log()
5317{
5318 const size_t SIZE = 256;
5319 char buffer[SIZE];
5320 String8 result;
5321
5322 ALOGV(" - sampling rates: ");
5323 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5324 ALOGV(" %d", mSamplingRates[i]);
5325 }
5326
5327 ALOGV(" - channel masks: ");
5328 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5329 ALOGV(" 0x%04x", mChannelMasks[i]);
5330 }
5331
5332 ALOGV(" - formats: ");
5333 for (size_t i = 0; i < mFormats.size(); i++) {
5334 ALOGV(" 0x%08x", mFormats[i]);
5335 }
5336
5337 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5338 ALOGV(" - flags: 0x%04x\n", mFlags);
5339}
5340
5341
Eric Laurent3a4311c2014-03-17 12:00:47 -07005342// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005343
Eric Laurent1f2f2232014-06-02 12:01:23 -07005344
5345AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5346 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5347 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5348 AUDIO_PORT_ROLE_SOURCE,
5349 NULL),
5350 mDeviceType(type), mAddress(""),
5351 mChannelMask(AUDIO_CHANNEL_NONE), mId(0)
5352{
5353 mAudioPort = this;
5354}
5355
Eric Laurent3a4311c2014-03-17 12:00:47 -07005356bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005357{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005358 // Devices are considered equal if they:
5359 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5360 // - have the same address or one device does not specify the address
5361 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent951f4552014-05-20 10:48:17 -07005362 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005363 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005364 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005365 mChannelMask == other->mChannelMask);
5366}
5367
5368void AudioPolicyManager::DeviceVector::refreshTypes()
5369{
Eric Laurent951f4552014-05-20 10:48:17 -07005370 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005371 for(size_t i = 0; i < size(); i++) {
Eric Laurent951f4552014-05-20 10:48:17 -07005372 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005373 }
Eric Laurent951f4552014-05-20 10:48:17 -07005374 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005375}
5376
5377ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5378{
5379 for(size_t i = 0; i < size(); i++) {
5380 if (item->equals(itemAt(i))) {
5381 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005382 }
5383 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005384 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005385}
5386
Eric Laurent3a4311c2014-03-17 12:00:47 -07005387ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005388{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005389 ssize_t ret = indexOf(item);
5390
5391 if (ret < 0) {
5392 ret = SortedVector::add(item);
5393 if (ret >= 0) {
5394 refreshTypes();
5395 }
5396 } else {
Eric Laurent951f4552014-05-20 10:48:17 -07005397 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005398 ret = -1;
5399 }
5400 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005401}
5402
Eric Laurent3a4311c2014-03-17 12:00:47 -07005403ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5404{
5405 size_t i;
5406 ssize_t ret = indexOf(item);
5407
5408 if (ret < 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07005409 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005410 } else {
5411 ret = SortedVector::removeAt(ret);
5412 if (ret >= 0) {
5413 refreshTypes();
5414 }
5415 }
5416 return ret;
5417}
5418
5419void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5420{
5421 DeviceVector deviceList;
5422
5423 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5424 types &= ~role_bit;
5425
5426 while (types) {
5427 uint32_t i = 31 - __builtin_clz(types);
5428 uint32_t type = 1 << i;
5429 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005430 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005431 }
5432}
5433
Eric Laurent1afeecb2014-05-14 08:52:28 -07005434void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5435 const DeviceVector& declaredDevices)
5436{
5437 char *devName = strtok(name, "|");
5438 while (devName != NULL) {
5439 if (strlen(devName) != 0) {
5440 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5441 ARRAY_SIZE(sDeviceNameToEnumTable),
5442 devName);
5443 if (type != AUDIO_DEVICE_NONE) {
5444 add(new DeviceDescriptor(String8(""), type));
5445 } else {
5446 sp<DeviceDescriptor> deviceDesc =
5447 declaredDevices.getDeviceFromName(String8(devName));
5448 if (deviceDesc != 0) {
5449 add(deviceDesc);
5450 }
5451 }
5452 }
5453 devName = strtok(NULL, "|");
5454 }
5455}
5456
Eric Laurent951f4552014-05-20 10:48:17 -07005457sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5458 audio_devices_t type, String8 address) const
5459{
5460 sp<DeviceDescriptor> device;
5461 for (size_t i = 0; i < size(); i++) {
5462 if (itemAt(i)->mDeviceType == type) {
5463 device = itemAt(i);
5464 if (itemAt(i)->mAddress = address) {
5465 break;
5466 }
5467 }
5468 }
5469 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5470 type, address.string(), device.get());
5471 return device;
5472}
5473
Eric Laurent6a94d692014-05-20 11:18:06 -07005474sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5475 audio_port_handle_t id) const
5476{
5477 sp<DeviceDescriptor> device;
5478 for (size_t i = 0; i < size(); i++) {
5479 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%d)->mId %d", id, i, itemAt(i)->mId);
5480 if (itemAt(i)->mId == id) {
5481 device = itemAt(i);
5482 break;
5483 }
5484 }
5485 return device;
5486}
5487
Eric Laurent951f4552014-05-20 10:48:17 -07005488AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5489 audio_devices_t type) const
5490{
5491 DeviceVector devices;
5492 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5493 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5494 devices.add(itemAt(i));
5495 type &= ~itemAt(i)->mDeviceType;
5496 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5497 itemAt(i)->mDeviceType, itemAt(i).get());
5498 }
5499 }
5500 return devices;
5501}
5502
Eric Laurent1afeecb2014-05-14 08:52:28 -07005503sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5504 const String8& name) const
5505{
5506 sp<DeviceDescriptor> device;
5507 for (size_t i = 0; i < size(); i++) {
5508 if (itemAt(i)->mName == name) {
5509 device = itemAt(i);
5510 break;
5511 }
5512 }
5513 return device;
5514}
5515
Eric Laurent6a94d692014-05-20 11:18:06 -07005516void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5517 struct audio_port_config *dstConfig,
5518 const struct audio_port_config *srcConfig) const
Eric Laurent951f4552014-05-20 10:48:17 -07005519{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005520 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
5521 if (srcConfig != NULL) {
5522 dstConfig->config_mask &= srcConfig->config_mask;
5523 }
5524
5525 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5526
Eric Laurent6a94d692014-05-20 11:18:06 -07005527 dstConfig->id = mId;
5528 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent951f4552014-05-20 10:48:17 -07005529 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005530 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005531 dstConfig->ext.device.type = mDeviceType;
5532 dstConfig->ext.device.hw_module = mModule->mHandle;
5533 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent951f4552014-05-20 10:48:17 -07005534}
5535
5536void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5537{
Eric Laurente1715a42014-05-20 11:30:42 -07005538 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent951f4552014-05-20 10:48:17 -07005539 AudioPort::toAudioPort(port);
5540 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005541 toAudioPortConfig(&port->active_config);
Eric Laurent951f4552014-05-20 10:48:17 -07005542 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005543 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent951f4552014-05-20 10:48:17 -07005544 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5545}
5546
Eric Laurent1afeecb2014-05-14 08:52:28 -07005547status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005548{
5549 const size_t SIZE = 256;
5550 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005551 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005552
Eric Laurent1afeecb2014-05-14 08:52:28 -07005553 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5554 result.append(buffer);
5555 if (mId != 0) {
5556 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5557 result.append(buffer);
5558 }
5559 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5560 enumToString(sDeviceNameToEnumTable,
5561 ARRAY_SIZE(sDeviceNameToEnumTable),
5562 mDeviceType));
5563 result.append(buffer);
5564 if (mAddress.size() != 0) {
5565 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5566 result.append(buffer);
5567 }
5568 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5569 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5570 result.append(buffer);
5571 }
5572 write(fd, result.string(), result.size());
5573 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005574
5575 return NO_ERROR;
5576}
5577
5578
5579// --- audio_policy.conf file parsing
5580
Eric Laurente0720872014-03-11 09:30:41 -07005581audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005582{
5583 uint32_t flag = 0;
5584
5585 // it is OK to cast name to non const here as we are not going to use it after
5586 // strtok() modifies it
5587 char *flagName = strtok(name, "|");
5588 while (flagName != NULL) {
5589 if (strlen(flagName) != 0) {
5590 flag |= stringToEnum(sFlagNameToEnumTable,
5591 ARRAY_SIZE(sFlagNameToEnumTable),
5592 flagName);
5593 }
5594 flagName = strtok(NULL, "|");
5595 }
5596 //force direct flag if offload flag is set: offloading implies a direct output stream
5597 // and all common behaviors are driven by checking only the direct flag
5598 // this should normally be set appropriately in the policy configuration file
5599 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5600 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5601 }
5602
5603 return (audio_output_flags_t)flag;
5604}
5605
Eric Laurente0720872014-03-11 09:30:41 -07005606audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005607{
5608 uint32_t device = 0;
5609
5610 char *devName = strtok(name, "|");
5611 while (devName != NULL) {
5612 if (strlen(devName) != 0) {
5613 device |= stringToEnum(sDeviceNameToEnumTable,
5614 ARRAY_SIZE(sDeviceNameToEnumTable),
5615 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005616 }
Eric Laurente552edb2014-03-10 17:42:56 -07005617 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005618 }
Eric Laurente552edb2014-03-10 17:42:56 -07005619 return device;
5620}
5621
Eric Laurente0720872014-03-11 09:30:41 -07005622void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005623{
Eric Laurente552edb2014-03-10 17:42:56 -07005624 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005625 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005626 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07005627
Eric Laurent1afeecb2014-05-14 08:52:28 -07005628 node = config_find(root, DEVICES_TAG);
5629 if (node != NULL) {
5630 node = node->first_child;
5631 while (node) {
5632 ALOGV("loadHwModule() loading device %s", node->name);
5633 status_t tmpStatus = module->loadDevice(node);
5634 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5635 status = tmpStatus;
5636 }
5637 node = node->next;
5638 }
5639 }
5640 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005641 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005642 node = node->first_child;
5643 while (node) {
5644 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005645 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005646 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5647 status = tmpStatus;
5648 }
5649 node = node->next;
5650 }
5651 }
5652 node = config_find(root, INPUTS_TAG);
5653 if (node != NULL) {
5654 node = node->first_child;
5655 while (node) {
5656 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005657 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005658 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5659 status = tmpStatus;
5660 }
5661 node = node->next;
5662 }
5663 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005664 loadGlobalConfig(root, module);
5665
Eric Laurente552edb2014-03-10 17:42:56 -07005666 if (status == NO_ERROR) {
5667 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07005668 }
5669}
5670
Eric Laurente0720872014-03-11 09:30:41 -07005671void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005672{
5673 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5674 if (node == NULL) {
5675 return;
5676 }
5677
5678 node = node->first_child;
5679 while (node) {
5680 ALOGV("loadHwModules() loading module %s", node->name);
5681 loadHwModule(node);
5682 node = node->next;
5683 }
5684}
5685
Eric Laurent1f2f2232014-06-02 12:01:23 -07005686void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07005687{
5688 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
5689 if (node == NULL) {
5690 return;
5691 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005692 DeviceVector declaredDevices;
5693 if (module != NULL) {
5694 declaredDevices = module->mDeclaredDevices;
5695 }
5696
Eric Laurente552edb2014-03-10 17:42:56 -07005697 node = node->first_child;
5698 while (node) {
5699 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005700 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5701 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005702 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5703 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005704 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005705 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005706 ARRAY_SIZE(sDeviceNameToEnumTable),
5707 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005708 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005709 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005710 } else {
5711 ALOGW("loadGlobalConfig() default device not specified");
5712 }
Eric Laurent951f4552014-05-20 10:48:17 -07005713 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005714 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005715 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5716 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005717 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005718 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5719 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5720 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
5721 }
5722 node = node->next;
5723 }
5724}
5725
Eric Laurente0720872014-03-11 09:30:41 -07005726status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005727{
5728 cnode *root;
5729 char *data;
5730
5731 data = (char *)load_file(path, NULL);
5732 if (data == NULL) {
5733 return -ENODEV;
5734 }
5735 root = config_node("", "");
5736 config_load(root, data);
5737
Eric Laurente552edb2014-03-10 17:42:56 -07005738 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005739 // legacy audio_policy.conf files have one global_configuration section
5740 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07005741 config_free(root);
5742 free(root);
5743 free(data);
5744
5745 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5746
5747 return NO_ERROR;
5748}
5749
Eric Laurente0720872014-03-11 09:30:41 -07005750void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07005751{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005752 sp<HwModule> module;
Eric Laurent951f4552014-05-20 10:48:17 -07005753 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005754 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
5755 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005756 mAvailableOutputDevices.add(mDefaultOutputDevice);
5757 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005758
5759 module = new HwModule("primary");
5760
Eric Laurent1afeecb2014-05-14 08:52:28 -07005761 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005762 profile->mSamplingRates.add(44100);
5763 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5764 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005765 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005766 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
5767 module->mOutputProfiles.add(profile);
5768
Eric Laurent1afeecb2014-05-14 08:52:28 -07005769 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005770 profile->mSamplingRates.add(8000);
5771 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5772 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005773 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005774 module->mInputProfiles.add(profile);
5775
5776 mHwModules.add(module);
5777}
5778
5779}; // namespace android