blob: c472b11b865fd21e9cdbe794deee27560047ee29 [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>
41#include <hardware_legacy/audio_policy_conf.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070042#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070043#include "AudioPolicyManager.h"
Eric Laurente552edb2014-03-10 17:42:56 -070044
Eric Laurent3b73df72014-03-11 09:06:29 -070045namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070046
47// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070048// Definitions for audio_policy.conf file parsing
49// ----------------------------------------------------------------------------
50
51struct StringToEnum {
52 const char *name;
53 uint32_t value;
54};
55
56#define STRING_TO_ENUM(string) { #string, string }
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
59const StringToEnum sDeviceNameToEnumTable[] = {
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070073 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070074 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700104};
105
106const StringToEnum sFlagNameToEnumTable[] = {
107 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
113};
114
115const StringToEnum sFormatNameToEnumTable[] = {
116 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
122 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
123 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
124 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
125};
126
127const StringToEnum sOutChannelsNameToEnumTable[] = {
128 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
129 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
130 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
131 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
132};
133
134const StringToEnum sInChannelsNameToEnumTable[] = {
135 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
136 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
137 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
138};
139
140
141uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
142 size_t size,
143 const char *name)
144{
145 for (size_t i = 0; i < size; i++) {
146 if (strcmp(table[i].name, name) == 0) {
147 ALOGV("stringToEnum() found %s", table[i].name);
148 return table[i].value;
149 }
150 }
151 return 0;
152}
153
154const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
155 size_t size,
156 uint32_t value)
157{
158 for (size_t i = 0; i < size; i++) {
159 if (table[i].value == value) {
160 return table[i].name;
161 }
162 }
163 return "";
164}
165
166bool AudioPolicyManager::stringToBool(const char *value)
167{
168 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
169}
170
171
172// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700173// AudioPolicyInterface implementation
174// ----------------------------------------------------------------------------
175
176
Eric Laurente0720872014-03-11 09:30:41 -0700177status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700178 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700179 const char *device_address)
180{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700182
183 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
184
185 // connect/disconnect only 1 device at a time
186 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
187
Eric Laurente552edb2014-03-10 17:42:56 -0700188 // handle output devices
189 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700190 SortedVector <audio_io_handle_t> outputs;
191
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
193 address,
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700194 0);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 // save a copy of the opened output descriptors before any output is opened or closed
198 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
199 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700200 switch (state)
201 {
202 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700203 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700205 ALOGW("setDeviceConnectionState() device already connected: %x", device);
206 return INVALID_OPERATION;
207 }
208 ALOGV("setDeviceConnectionState() connecting device %x", device);
209
Eric Laurent3a4311c2014-03-17 12:00:47 -0700210 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700211 return INVALID_OPERATION;
212 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700213 // outputs should never be empty here
214 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
215 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700216 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700217 outputs.size());
218 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700219 index = mAvailableOutputDevices.add(devDesc);
220 if (index >= 0) {
221 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700222 HwModule *module = getModuleForDevice(device);
223 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
224 "could not find HW module for device %08x", device);
225 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700226 } else {
227 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 }
229
230 break;
231 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700234 ALOGW("setDeviceConnectionState() device not connected: %x", device);
235 return INVALID_OPERATION;
236 }
237
238 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
239 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700240 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700241
Eric Laurent3a4311c2014-03-17 12:00:47 -0700242 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // not currently handling multiple simultaneous submixes: ignoring remote submix
244 // case and address
245 } break;
246
247 default:
248 ALOGE("setDeviceConnectionState() invalid state: %x", state);
249 return BAD_VALUE;
250 }
251
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
253 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700254 checkA2dpSuspend();
255 checkOutputForAllStrategies();
256 // outputs must be closed after checkOutputForAllStrategies() is executed
257 if (!outputs.isEmpty()) {
258 for (size_t i = 0; i < outputs.size(); i++) {
259 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
260 // close unused outputs after device disconnection or direct outputs that have been
261 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700262 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700263 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
264 (desc->mDirectOpenCount == 0))) {
265 closeOutput(outputs[i]);
266 }
267 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700268 // check again after closing A2DP output to reset mA2dpSuspended if needed
269 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700270 }
271
272 updateDevicesAndOutputs();
273 for (size_t i = 0; i < mOutputs.size(); i++) {
274 // do not force device change on duplicated output because if device is 0, it will
275 // also force a device 0 for the two outputs it is duplicated to which may override
276 // a valid device selection on those outputs.
277 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700278 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700279 !mOutputs.valueAt(i)->isDuplicated(),
280 0);
281 }
282
Eric Laurentb71e58b2014-05-29 16:08:11 -0700283 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700284 } // end if is output device
285
Eric Laurente552edb2014-03-10 17:42:56 -0700286 // handle input devices
287 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700288 SortedVector <audio_io_handle_t> inputs;
289
Eric Laurent3a4311c2014-03-17 12:00:47 -0700290 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
291 address,
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700292 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700293
Eric Laurent3a4311c2014-03-17 12:00:47 -0700294 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700295 switch (state)
296 {
297 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700298 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700300 ALOGW("setDeviceConnectionState() device already connected: %d", device);
301 return INVALID_OPERATION;
302 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700303 HwModule *module = getModuleForDevice(device);
304 if (module == NULL) {
305 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
306 device);
307 return INVALID_OPERATION;
308 }
Eric Laurentd4692962014-05-05 18:13:44 -0700309 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
310 return INVALID_OPERATION;
311 }
312
Eric Laurent3a4311c2014-03-17 12:00:47 -0700313 index = mAvailableInputDevices.add(devDesc);
314 if (index >= 0) {
315 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700316 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700317 } else {
318 return NO_MEMORY;
319 }
Eric Laurentd4692962014-05-05 18:13:44 -0700320 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700321
322 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700323 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700324 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700325 ALOGW("setDeviceConnectionState() device not connected: %d", device);
326 return INVALID_OPERATION;
327 }
Eric Laurentd4692962014-05-05 18:13:44 -0700328 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700329 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700330 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700331
332 default:
333 ALOGE("setDeviceConnectionState() invalid state: %x", state);
334 return BAD_VALUE;
335 }
336
Eric Laurentd4692962014-05-05 18:13:44 -0700337 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700338
339 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700340 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700341
342 ALOGW("setDeviceConnectionState() invalid device: %x", device);
343 return BAD_VALUE;
344}
345
Eric Laurente0720872014-03-11 09:30:41 -0700346audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700347 const char *device_address)
348{
Eric Laurent3b73df72014-03-11 09:06:29 -0700349 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700350 String8 address = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
352 String8(device_address),
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700353 0);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 ssize_t index;
355 DeviceVector *deviceVector;
356
Eric Laurente552edb2014-03-10 17:42:56 -0700357 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700359 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 deviceVector = &mAvailableInputDevices;
361 } else {
362 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
363 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700364 }
365
Eric Laurent3a4311c2014-03-17 12:00:47 -0700366 index = deviceVector->indexOf(devDesc);
367 if (index >= 0) {
368 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
369 } else {
370 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
371 }
Eric Laurente552edb2014-03-10 17:42:56 -0700372}
373
Eric Laurente0720872014-03-11 09:30:41 -0700374void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700375{
376 ALOGV("setPhoneState() state %d", state);
377 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700378 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700379 ALOGW("setPhoneState() invalid state %d", state);
380 return;
381 }
382
383 if (state == mPhoneState ) {
384 ALOGW("setPhoneState() setting same state %d", state);
385 return;
386 }
387
388 // if leaving call state, handle special case of active streams
389 // pertaining to sonification strategy see handleIncallSonification()
390 if (isInCall()) {
391 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700392 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
393 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700394 }
395 }
396
397 // store previous phone state for management of sonification strategy below
398 int oldState = mPhoneState;
399 mPhoneState = state;
400 bool force = false;
401
402 // are we entering or starting a call
403 if (!isStateInCall(oldState) && isStateInCall(state)) {
404 ALOGV(" Entering call in setPhoneState()");
405 // force routing command to audio hardware when starting a call
406 // even if no device change is needed
407 force = true;
408 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
409 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
410 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
411 }
412 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
413 ALOGV(" Exiting call in setPhoneState()");
414 // force routing command to audio hardware when exiting a call
415 // even if no device change is needed
416 force = true;
417 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
418 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
419 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
420 }
421 } else if (isStateInCall(state) && (state != oldState)) {
422 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
423 // force routing command to audio hardware when switching between telephony and VoIP
424 // even if no device change is needed
425 force = true;
426 }
427
428 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700429 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700430 checkA2dpSuspend();
431 checkOutputForAllStrategies();
432 updateDevicesAndOutputs();
433
434 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
435
436 // force routing command to audio hardware when ending call
437 // even if no device change is needed
438 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
439 newDevice = hwOutputDesc->device();
440 }
441
442 int delayMs = 0;
443 if (isStateInCall(state)) {
444 nsecs_t sysTime = systemTime();
445 for (size_t i = 0; i < mOutputs.size(); i++) {
446 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
447 // mute media and sonification strategies and delay device switch by the largest
448 // latency of any output where either strategy is active.
449 // This avoid sending the ring tone or music tail into the earpiece or headset.
450 if ((desc->isStrategyActive(STRATEGY_MEDIA,
451 SONIFICATION_HEADSET_MUSIC_DELAY,
452 sysTime) ||
453 desc->isStrategyActive(STRATEGY_SONIFICATION,
454 SONIFICATION_HEADSET_MUSIC_DELAY,
455 sysTime)) &&
456 (delayMs < (int)desc->mLatency*2)) {
457 delayMs = desc->mLatency*2;
458 }
459 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
460 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
461 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
462 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
463 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
464 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
465 }
466 }
467
468 // change routing is necessary
469 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
470
471 // if entering in call state, handle special case of active streams
472 // pertaining to sonification strategy see handleIncallSonification()
473 if (isStateInCall(state)) {
474 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700475 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
476 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700477 }
478 }
479
480 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700481 if (state == AUDIO_MODE_RINGTONE &&
482 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700483 mLimitRingtoneVolume = true;
484 } else {
485 mLimitRingtoneVolume = false;
486 }
487}
488
Eric Laurente0720872014-03-11 09:30:41 -0700489void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700490 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700491{
492 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
493
494 bool forceVolumeReeval = false;
495 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700496 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
497 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
498 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700499 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
500 return;
501 }
502 forceVolumeReeval = true;
503 mForceUse[usage] = config;
504 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700505 case AUDIO_POLICY_FORCE_FOR_MEDIA:
506 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
507 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
508 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
509 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
510 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700511 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
512 return;
513 }
514 mForceUse[usage] = config;
515 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700516 case AUDIO_POLICY_FORCE_FOR_RECORD:
517 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
518 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700519 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
520 return;
521 }
522 mForceUse[usage] = config;
523 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700524 case AUDIO_POLICY_FORCE_FOR_DOCK:
525 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
526 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
527 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
528 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
529 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700530 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
531 }
532 forceVolumeReeval = true;
533 mForceUse[usage] = config;
534 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700535 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
536 if (config != AUDIO_POLICY_FORCE_NONE &&
537 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700538 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
539 }
540 forceVolumeReeval = true;
541 mForceUse[usage] = config;
542 break;
543 default:
544 ALOGW("setForceUse() invalid usage %d", usage);
545 break;
546 }
547
548 // check for device and output changes triggered by new force usage
549 checkA2dpSuspend();
550 checkOutputForAllStrategies();
551 updateDevicesAndOutputs();
552 for (size_t i = 0; i < mOutputs.size(); i++) {
553 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700554 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700555 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
556 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
557 applyStreamVolumes(output, newDevice, 0, true);
558 }
559 }
560
561 audio_io_handle_t activeInput = getActiveInput();
562 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700563 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700564 }
565
566}
567
Eric Laurente0720872014-03-11 09:30:41 -0700568audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700569{
570 return mForceUse[usage];
571}
572
Eric Laurente0720872014-03-11 09:30:41 -0700573void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700574{
575 ALOGV("setSystemProperty() property %s, value %s", property, value);
576}
577
578// Find a direct output profile compatible with the parameters passed, even if the input flags do
579// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700580sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700581 audio_devices_t device,
582 uint32_t samplingRate,
583 audio_format_t format,
584 audio_channel_mask_t channelMask,
585 audio_output_flags_t flags)
586{
587 for (size_t i = 0; i < mHwModules.size(); i++) {
588 if (mHwModules[i]->mHandle == 0) {
589 continue;
590 }
591 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700592 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700593 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700594 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
595 if (profile->isCompatibleProfile(device, samplingRate, format,
596 channelMask,
597 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700598 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700599 }
600 } else {
601 if (profile->isCompatibleProfile(device, samplingRate, format,
602 channelMask,
603 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700604 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700605 }
606 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700607 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
608 return profile;
609 }
Eric Laurente552edb2014-03-10 17:42:56 -0700610 }
611 }
612 return 0;
613}
614
Eric Laurente0720872014-03-11 09:30:41 -0700615audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700616 uint32_t samplingRate,
617 audio_format_t format,
618 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700619 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700620 const audio_offload_info_t *offloadInfo)
621{
622 audio_io_handle_t output = 0;
623 uint32_t latency = 0;
Eric Laurent3b73df72014-03-11 09:06:29 -0700624 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700625 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
626 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
627 device, stream, samplingRate, format, channelMask, flags);
628
629#ifdef AUDIO_POLICY_TEST
630 if (mCurOutput != 0) {
631 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
632 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
633
634 if (mTestOutputs[mCurOutput] == 0) {
635 ALOGV("getOutput() opening test output");
636 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
637 outputDesc->mDevice = mTestDevice;
638 outputDesc->mSamplingRate = mTestSamplingRate;
639 outputDesc->mFormat = mTestFormat;
640 outputDesc->mChannelMask = mTestChannels;
641 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700642 outputDesc->mFlags =
643 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700644 outputDesc->mRefCount[stream] = 0;
645 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
646 &outputDesc->mSamplingRate,
647 &outputDesc->mFormat,
648 &outputDesc->mChannelMask,
649 &outputDesc->mLatency,
650 outputDesc->mFlags,
651 offloadInfo);
652 if (mTestOutputs[mCurOutput]) {
653 AudioParameter outputCmd = AudioParameter();
654 outputCmd.addInt(String8("set_id"),mCurOutput);
655 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
656 addOutput(mTestOutputs[mCurOutput], outputDesc);
657 }
658 }
659 return mTestOutputs[mCurOutput];
660 }
661#endif //AUDIO_POLICY_TEST
662
663 // open a direct output if required by specified parameters
664 //force direct flag if offload flag is set: offloading implies a direct output stream
665 // and all common behaviors are driven by checking only the direct flag
666 // this should normally be set appropriately in the policy configuration file
667 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700668 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700669 }
670
671 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
672 // creating an offloaded track and tearing it down immediately after start when audioflinger
673 // detects there is an active non offloadable effect.
674 // FIXME: We should check the audio session here but we do not have it in this context.
675 // This may prevent offloading in rare situations where effects are left active by apps
676 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700677 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700678 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
679 !isNonOffloadableEffectEnabled()) {
680 profile = getProfileForDirectOutput(device,
681 samplingRate,
682 format,
683 channelMask,
684 (audio_output_flags_t)flags);
685 }
686
Eric Laurent1c333e22014-05-20 10:48:17 -0700687 if (profile != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700688 AudioOutputDescriptor *outputDesc = NULL;
689
690 for (size_t i = 0; i < mOutputs.size(); i++) {
691 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
692 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
693 outputDesc = desc;
694 // reuse direct output if currently open and configured with same parameters
695 if ((samplingRate == outputDesc->mSamplingRate) &&
696 (format == outputDesc->mFormat) &&
697 (channelMask == outputDesc->mChannelMask)) {
698 outputDesc->mDirectOpenCount++;
699 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
700 return mOutputs.keyAt(i);
701 }
702 }
703 }
704 // close direct output if currently open and configured with different parameters
705 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700707 }
708 outputDesc = new AudioOutputDescriptor(profile);
709 outputDesc->mDevice = device;
710 outputDesc->mSamplingRate = samplingRate;
711 outputDesc->mFormat = format;
712 outputDesc->mChannelMask = channelMask;
713 outputDesc->mLatency = 0;
714 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
715 outputDesc->mRefCount[stream] = 0;
716 outputDesc->mStopTime[stream] = 0;
717 outputDesc->mDirectOpenCount = 1;
718 output = mpClientInterface->openOutput(profile->mModule->mHandle,
719 &outputDesc->mDevice,
720 &outputDesc->mSamplingRate,
721 &outputDesc->mFormat,
722 &outputDesc->mChannelMask,
723 &outputDesc->mLatency,
724 outputDesc->mFlags,
725 offloadInfo);
726
727 // only accept an output with the requested parameters
728 if (output == 0 ||
729 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
730 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
731 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
732 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
733 "format %d %d, channelMask %04x %04x", output, samplingRate,
734 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
735 outputDesc->mChannelMask);
736 if (output != 0) {
737 mpClientInterface->closeOutput(output);
738 }
739 delete outputDesc;
740 return 0;
741 }
742 audio_io_handle_t srcOutput = getOutputForEffect();
743 addOutput(output, outputDesc);
744 audio_io_handle_t dstOutput = getOutputForEffect();
745 if (dstOutput == output) {
746 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
747 }
748 mPreviousOutputs = mOutputs;
749 ALOGV("getOutput() returns new direct output %d", output);
750 return output;
751 }
752
753 // ignoring channel mask due to downmix capability in mixer
754
755 // open a non direct output
756
757 // for non direct outputs, only PCM is supported
758 if (audio_is_linear_pcm(format)) {
759 // get which output is suitable for the specified stream. The actual
760 // routing change will happen when startOutput() will be called
761 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
762
763 output = selectOutput(outputs, flags);
764 }
765 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
766 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
767
768 ALOGV("getOutput() returns output %d", output);
769
770 return output;
771}
772
Eric Laurente0720872014-03-11 09:30:41 -0700773audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700774 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700775{
776 // select one output among several that provide a path to a particular device or set of
777 // devices (the list was previously build by getOutputsForDevice()).
778 // The priority is as follows:
779 // 1: the output with the highest number of requested policy flags
780 // 2: the primary output
781 // 3: the first output in the list
782
783 if (outputs.size() == 0) {
784 return 0;
785 }
786 if (outputs.size() == 1) {
787 return outputs[0];
788 }
789
790 int maxCommonFlags = 0;
791 audio_io_handle_t outputFlags = 0;
792 audio_io_handle_t outputPrimary = 0;
793
794 for (size_t i = 0; i < outputs.size(); i++) {
795 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
796 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700797 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700798 if (commonFlags > maxCommonFlags) {
799 outputFlags = outputs[i];
800 maxCommonFlags = commonFlags;
801 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
802 }
803 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
804 outputPrimary = outputs[i];
805 }
806 }
807 }
808
809 if (outputFlags != 0) {
810 return outputFlags;
811 }
812 if (outputPrimary != 0) {
813 return outputPrimary;
814 }
815
816 return outputs[0];
817}
818
Eric Laurente0720872014-03-11 09:30:41 -0700819status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700820 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700821 int session)
822{
823 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
824 ssize_t index = mOutputs.indexOfKey(output);
825 if (index < 0) {
826 ALOGW("startOutput() unknown output %d", output);
827 return BAD_VALUE;
828 }
829
830 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
831
832 // increment usage count for this stream on the requested output:
833 // NOTE that the usage count is the same for duplicated output and hardware output which is
834 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
835 outputDesc->changeRefCount(stream, 1);
836
837 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700838 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700839 routing_strategy strategy = getStrategy(stream);
840 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
841 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
842 uint32_t waitMs = 0;
843 bool force = false;
844 for (size_t i = 0; i < mOutputs.size(); i++) {
845 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
846 if (desc != outputDesc) {
847 // force a device change if any other output is managed by the same hw
848 // module and has a current device selection that differs from selected device.
849 // In this case, the audio HAL must receive the new device selection so that it can
850 // change the device currently selected by the other active output.
851 if (outputDesc->sharesHwModuleWith(desc) &&
852 desc->device() != newDevice) {
853 force = true;
854 }
855 // wait for audio on other active outputs to be presented when starting
856 // a notification so that audio focus effect can propagate.
857 uint32_t latency = desc->latency();
858 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
859 waitMs = latency;
860 }
861 }
862 }
863 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
864
865 // handle special case for sonification while in call
866 if (isInCall()) {
867 handleIncallSonification(stream, true, false);
868 }
869
870 // apply volume rules for current stream and device if necessary
871 checkAndSetVolume(stream,
872 mStreams[stream].getVolumeIndex(newDevice),
873 output,
874 newDevice);
875
876 // update the outputs if starting an output with a stream that can affect notification
877 // routing
878 handleNotificationRoutingForStream(stream);
879 if (waitMs > muteWaitMs) {
880 usleep((waitMs - muteWaitMs) * 2 * 1000);
881 }
882 }
883 return NO_ERROR;
884}
885
886
Eric Laurente0720872014-03-11 09:30:41 -0700887status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700888 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700889 int session)
890{
891 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
892 ssize_t index = mOutputs.indexOfKey(output);
893 if (index < 0) {
894 ALOGW("stopOutput() unknown output %d", output);
895 return BAD_VALUE;
896 }
897
898 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
899
900 // handle special case for sonification while in call
901 if (isInCall()) {
902 handleIncallSonification(stream, false, false);
903 }
904
905 if (outputDesc->mRefCount[stream] > 0) {
906 // decrement usage count of this stream on the output
907 outputDesc->changeRefCount(stream, -1);
908 // store time at which the stream was stopped - see isStreamActive()
909 if (outputDesc->mRefCount[stream] == 0) {
910 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700911 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700912 // delay the device switch by twice the latency because stopOutput() is executed when
913 // the track stop() command is received and at that time the audio track buffer can
914 // still contain data that needs to be drained. The latency only covers the audio HAL
915 // and kernel buffers. Also the latency does not always include additional delay in the
916 // audio path (audio DSP, CODEC ...)
917 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
918
919 // force restoring the device selection on other active outputs if it differs from the
920 // one being selected for this output
921 for (size_t i = 0; i < mOutputs.size(); i++) {
922 audio_io_handle_t curOutput = mOutputs.keyAt(i);
923 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
924 if (curOutput != output &&
925 desc->isActive() &&
926 outputDesc->sharesHwModuleWith(desc) &&
927 (newDevice != desc->device())) {
928 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700929 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700930 true,
931 outputDesc->mLatency*2);
932 }
933 }
934 // update the outputs if stopping one with a stream that can affect notification routing
935 handleNotificationRoutingForStream(stream);
936 }
937 return NO_ERROR;
938 } else {
939 ALOGW("stopOutput() refcount is already 0 for output %d", output);
940 return INVALID_OPERATION;
941 }
942}
943
Eric Laurente0720872014-03-11 09:30:41 -0700944void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700945{
946 ALOGV("releaseOutput() %d", output);
947 ssize_t index = mOutputs.indexOfKey(output);
948 if (index < 0) {
949 ALOGW("releaseOutput() releasing unknown output %d", output);
950 return;
951 }
952
953#ifdef AUDIO_POLICY_TEST
954 int testIndex = testOutputIndex(output);
955 if (testIndex != 0) {
956 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
957 if (outputDesc->isActive()) {
958 mpClientInterface->closeOutput(output);
959 delete mOutputs.valueAt(index);
960 mOutputs.removeItem(output);
961 mTestOutputs[testIndex] = 0;
962 }
963 return;
964 }
965#endif //AUDIO_POLICY_TEST
966
967 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -0700968 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700969 if (desc->mDirectOpenCount <= 0) {
970 ALOGW("releaseOutput() invalid open count %d for output %d",
971 desc->mDirectOpenCount, output);
972 return;
973 }
974 if (--desc->mDirectOpenCount == 0) {
975 closeOutput(output);
976 // If effects where present on the output, audioflinger moved them to the primary
977 // output by default: move them back to the appropriate output.
978 audio_io_handle_t dstOutput = getOutputForEffect();
979 if (dstOutput != mPrimaryOutput) {
980 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
981 }
982 }
983 }
984}
985
986
Eric Laurente0720872014-03-11 09:30:41 -0700987audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -0700988 uint32_t samplingRate,
989 audio_format_t format,
990 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700991 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -0700992{
993 audio_io_handle_t input = 0;
994 audio_devices_t device = getDeviceForInputSource(inputSource);
995
996 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
997 inputSource, samplingRate, format, channelMask, acoustics);
998
999 if (device == AUDIO_DEVICE_NONE) {
1000 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1001 return 0;
1002 }
1003
1004 // adapt channel selection to input source
1005 switch(inputSource) {
1006 case AUDIO_SOURCE_VOICE_UPLINK:
1007 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1008 break;
1009 case AUDIO_SOURCE_VOICE_DOWNLINK:
1010 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1011 break;
1012 case AUDIO_SOURCE_VOICE_CALL:
1013 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1014 break;
1015 default:
1016 break;
1017 }
1018
Eric Laurent1c333e22014-05-20 10:48:17 -07001019 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001020 samplingRate,
1021 format,
1022 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001023 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001024 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1025 "channelMask %04x",
1026 device, samplingRate, format, channelMask);
1027 return 0;
1028 }
1029
1030 if (profile->mModule->mHandle == 0) {
1031 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1032 return 0;
1033 }
1034
1035 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
1036
1037 inputDesc->mInputSource = inputSource;
1038 inputDesc->mDevice = device;
1039 inputDesc->mSamplingRate = samplingRate;
1040 inputDesc->mFormat = format;
1041 inputDesc->mChannelMask = channelMask;
1042 inputDesc->mRefCount = 0;
1043 input = mpClientInterface->openInput(profile->mModule->mHandle,
1044 &inputDesc->mDevice,
1045 &inputDesc->mSamplingRate,
1046 &inputDesc->mFormat,
1047 &inputDesc->mChannelMask);
1048
1049 // only accept input with the exact requested set of parameters
1050 if (input == 0 ||
1051 (samplingRate != inputDesc->mSamplingRate) ||
1052 (format != inputDesc->mFormat) ||
1053 (channelMask != inputDesc->mChannelMask)) {
1054 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1055 samplingRate, format, channelMask);
1056 if (input != 0) {
1057 mpClientInterface->closeInput(input);
1058 }
1059 delete inputDesc;
1060 return 0;
1061 }
Eric Laurentd4692962014-05-05 18:13:44 -07001062 addInput(input, inputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001063 return input;
1064}
1065
Eric Laurente0720872014-03-11 09:30:41 -07001066status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001067{
1068 ALOGV("startInput() input %d", input);
1069 ssize_t index = mInputs.indexOfKey(input);
1070 if (index < 0) {
1071 ALOGW("startInput() unknown input %d", input);
1072 return BAD_VALUE;
1073 }
1074 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1075
1076#ifdef AUDIO_POLICY_TEST
1077 if (mTestInput == 0)
1078#endif //AUDIO_POLICY_TEST
1079 {
1080 // refuse 2 active AudioRecord clients at the same time except if the active input
1081 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1082 audio_io_handle_t activeInput = getActiveInput();
1083 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1084 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1085 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1086 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1087 stopInput(activeInput);
1088 releaseInput(activeInput);
1089 } else {
1090 ALOGW("startInput() input %d failed: other input already started", input);
1091 return INVALID_OPERATION;
1092 }
1093 }
1094 }
1095
Eric Laurent1c333e22014-05-20 10:48:17 -07001096 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001097
1098 // automatically enable the remote submix output when input is started
1099 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1100 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001101 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001102 }
1103
Eric Laurente552edb2014-03-10 17:42:56 -07001104 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1105
Eric Laurente552edb2014-03-10 17:42:56 -07001106 inputDesc->mRefCount = 1;
1107 return NO_ERROR;
1108}
1109
Eric Laurente0720872014-03-11 09:30:41 -07001110status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001111{
1112 ALOGV("stopInput() input %d", input);
1113 ssize_t index = mInputs.indexOfKey(input);
1114 if (index < 0) {
1115 ALOGW("stopInput() unknown input %d", input);
1116 return BAD_VALUE;
1117 }
1118 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1119
1120 if (inputDesc->mRefCount == 0) {
1121 ALOGW("stopInput() input %d already stopped", input);
1122 return INVALID_OPERATION;
1123 } else {
1124 // automatically disable the remote submix output when input is stopped
1125 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1126 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001127 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001128 }
1129
Eric Laurent1c333e22014-05-20 10:48:17 -07001130 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 inputDesc->mRefCount = 0;
1132 return NO_ERROR;
1133 }
1134}
1135
Eric Laurente0720872014-03-11 09:30:41 -07001136void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001137{
1138 ALOGV("releaseInput() %d", input);
1139 ssize_t index = mInputs.indexOfKey(input);
1140 if (index < 0) {
1141 ALOGW("releaseInput() releasing unknown input %d", input);
1142 return;
1143 }
1144 mpClientInterface->closeInput(input);
1145 delete mInputs.valueAt(index);
1146 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001147 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07001148 ALOGV("releaseInput() exit");
1149}
1150
Eric Laurentd4692962014-05-05 18:13:44 -07001151void AudioPolicyManager::closeAllInputs() {
1152 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1153 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1154 }
1155 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001156 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001157}
1158
Eric Laurente0720872014-03-11 09:30:41 -07001159void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001160 int indexMin,
1161 int indexMax)
1162{
1163 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1164 if (indexMin < 0 || indexMin >= indexMax) {
1165 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1166 return;
1167 }
1168 mStreams[stream].mIndexMin = indexMin;
1169 mStreams[stream].mIndexMax = indexMax;
1170}
1171
Eric Laurente0720872014-03-11 09:30:41 -07001172status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001173 int index,
1174 audio_devices_t device)
1175{
1176
1177 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1178 return BAD_VALUE;
1179 }
1180 if (!audio_is_output_device(device)) {
1181 return BAD_VALUE;
1182 }
1183
1184 // Force max volume if stream cannot be muted
1185 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1186
1187 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1188 stream, device, index);
1189
1190 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1191 // clear all device specific values
1192 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1193 mStreams[stream].mIndexCur.clear();
1194 }
1195 mStreams[stream].mIndexCur.add(device, index);
1196
1197 // compute and apply stream volume on all outputs according to connected device
1198 status_t status = NO_ERROR;
1199 for (size_t i = 0; i < mOutputs.size(); i++) {
1200 audio_devices_t curDevice =
1201 getDeviceForVolume(mOutputs.valueAt(i)->device());
1202 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1203 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1204 if (volStatus != NO_ERROR) {
1205 status = volStatus;
1206 }
1207 }
1208 }
1209 return status;
1210}
1211
Eric Laurente0720872014-03-11 09:30:41 -07001212status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001213 int *index,
1214 audio_devices_t device)
1215{
1216 if (index == NULL) {
1217 return BAD_VALUE;
1218 }
1219 if (!audio_is_output_device(device)) {
1220 return BAD_VALUE;
1221 }
1222 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1223 // the strategy the stream belongs to.
1224 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1225 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1226 }
1227 device = getDeviceForVolume(device);
1228
1229 *index = mStreams[stream].getVolumeIndex(device);
1230 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1231 return NO_ERROR;
1232}
1233
Eric Laurente0720872014-03-11 09:30:41 -07001234audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001235 const SortedVector<audio_io_handle_t>& outputs)
1236{
1237 // select one output among several suitable for global effects.
1238 // The priority is as follows:
1239 // 1: An offloaded output. If the effect ends up not being offloadable,
1240 // AudioFlinger will invalidate the track and the offloaded output
1241 // will be closed causing the effect to be moved to a PCM output.
1242 // 2: A deep buffer output
1243 // 3: the first output in the list
1244
1245 if (outputs.size() == 0) {
1246 return 0;
1247 }
1248
1249 audio_io_handle_t outputOffloaded = 0;
1250 audio_io_handle_t outputDeepBuffer = 0;
1251
1252 for (size_t i = 0; i < outputs.size(); i++) {
1253 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001254 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001255 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1256 outputOffloaded = outputs[i];
1257 }
1258 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1259 outputDeepBuffer = outputs[i];
1260 }
1261 }
1262
1263 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1264 outputOffloaded, outputDeepBuffer);
1265 if (outputOffloaded != 0) {
1266 return outputOffloaded;
1267 }
1268 if (outputDeepBuffer != 0) {
1269 return outputDeepBuffer;
1270 }
1271
1272 return outputs[0];
1273}
1274
Eric Laurente0720872014-03-11 09:30:41 -07001275audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001276{
1277 // apply simple rule where global effects are attached to the same output as MUSIC streams
1278
Eric Laurent3b73df72014-03-11 09:06:29 -07001279 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001280 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1281 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1282
1283 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1284 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1285 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1286
1287 return output;
1288}
1289
Eric Laurente0720872014-03-11 09:30:41 -07001290status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001291 audio_io_handle_t io,
1292 uint32_t strategy,
1293 int session,
1294 int id)
1295{
1296 ssize_t index = mOutputs.indexOfKey(io);
1297 if (index < 0) {
1298 index = mInputs.indexOfKey(io);
1299 if (index < 0) {
1300 ALOGW("registerEffect() unknown io %d", io);
1301 return INVALID_OPERATION;
1302 }
1303 }
1304
1305 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1306 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1307 desc->name, desc->memoryUsage);
1308 return INVALID_OPERATION;
1309 }
1310 mTotalEffectsMemory += desc->memoryUsage;
1311 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1312 desc->name, io, strategy, session, id);
1313 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1314
1315 EffectDescriptor *pDesc = new EffectDescriptor();
1316 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1317 pDesc->mIo = io;
1318 pDesc->mStrategy = (routing_strategy)strategy;
1319 pDesc->mSession = session;
1320 pDesc->mEnabled = false;
1321
1322 mEffects.add(id, pDesc);
1323
1324 return NO_ERROR;
1325}
1326
Eric Laurente0720872014-03-11 09:30:41 -07001327status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001328{
1329 ssize_t index = mEffects.indexOfKey(id);
1330 if (index < 0) {
1331 ALOGW("unregisterEffect() unknown effect ID %d", id);
1332 return INVALID_OPERATION;
1333 }
1334
1335 EffectDescriptor *pDesc = mEffects.valueAt(index);
1336
1337 setEffectEnabled(pDesc, false);
1338
1339 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1340 ALOGW("unregisterEffect() memory %d too big for total %d",
1341 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1342 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1343 }
1344 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1345 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1346 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1347
1348 mEffects.removeItem(id);
1349 delete pDesc;
1350
1351 return NO_ERROR;
1352}
1353
Eric Laurente0720872014-03-11 09:30:41 -07001354status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001355{
1356 ssize_t index = mEffects.indexOfKey(id);
1357 if (index < 0) {
1358 ALOGW("unregisterEffect() unknown effect ID %d", id);
1359 return INVALID_OPERATION;
1360 }
1361
1362 return setEffectEnabled(mEffects.valueAt(index), enabled);
1363}
1364
Eric Laurente0720872014-03-11 09:30:41 -07001365status_t AudioPolicyManager::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001366{
1367 if (enabled == pDesc->mEnabled) {
1368 ALOGV("setEffectEnabled(%s) effect already %s",
1369 enabled?"true":"false", enabled?"enabled":"disabled");
1370 return INVALID_OPERATION;
1371 }
1372
1373 if (enabled) {
1374 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1375 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1376 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1377 return INVALID_OPERATION;
1378 }
1379 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1380 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1381 } else {
1382 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1383 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1384 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1385 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1386 }
1387 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1388 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1389 }
1390 pDesc->mEnabled = enabled;
1391 return NO_ERROR;
1392}
1393
Eric Laurente0720872014-03-11 09:30:41 -07001394bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001395{
1396 for (size_t i = 0; i < mEffects.size(); i++) {
1397 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1398 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1399 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1400 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1401 pDesc->mDesc.name, pDesc->mSession);
1402 return true;
1403 }
1404 }
1405 return false;
1406}
1407
Eric Laurente0720872014-03-11 09:30:41 -07001408bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001409{
1410 nsecs_t sysTime = systemTime();
1411 for (size_t i = 0; i < mOutputs.size(); i++) {
1412 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001413 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001414 return true;
1415 }
1416 }
1417 return false;
1418}
1419
Eric Laurente0720872014-03-11 09:30:41 -07001420bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001421 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001422{
1423 nsecs_t sysTime = systemTime();
1424 for (size_t i = 0; i < mOutputs.size(); i++) {
1425 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1426 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001427 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001428 return true;
1429 }
1430 }
1431 return false;
1432}
1433
Eric Laurente0720872014-03-11 09:30:41 -07001434bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001435{
1436 for (size_t i = 0; i < mInputs.size(); i++) {
1437 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1438 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001439 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001440 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1441 && (inputDescriptor->mRefCount > 0)) {
1442 return true;
1443 }
1444 }
1445 return false;
1446}
1447
1448
Eric Laurente0720872014-03-11 09:30:41 -07001449status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001450{
1451 const size_t SIZE = 256;
1452 char buffer[SIZE];
1453 String8 result;
1454
1455 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1456 result.append(buffer);
1457
1458 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1459 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001460 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1461 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001462 snprintf(buffer, SIZE, " Force use for communications %d\n",
1463 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001464 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001465 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001466 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001467 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001468 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001469 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001470 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001471 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001472 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001473
Eric Laurent3a4311c2014-03-17 12:00:47 -07001474 snprintf(buffer, SIZE, " Available output devices:\n");
1475 result.append(buffer);
1476 write(fd, result.string(), result.size());
1477 DeviceDescriptor::dumpHeader(fd, 2);
1478 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
1479 mAvailableOutputDevices[i]->dump(fd, 2);
1480 }
1481 snprintf(buffer, SIZE, "\n Available input devices:\n");
1482 write(fd, buffer, strlen(buffer));
1483 DeviceDescriptor::dumpHeader(fd, 2);
1484 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1485 mAvailableInputDevices[i]->dump(fd, 2);
1486 }
Eric Laurente552edb2014-03-10 17:42:56 -07001487
1488 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1489 write(fd, buffer, strlen(buffer));
1490 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001491 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001492 write(fd, buffer, strlen(buffer));
1493 mHwModules[i]->dump(fd);
1494 }
1495
1496 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1497 write(fd, buffer, strlen(buffer));
1498 for (size_t i = 0; i < mOutputs.size(); i++) {
1499 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1500 write(fd, buffer, strlen(buffer));
1501 mOutputs.valueAt(i)->dump(fd);
1502 }
1503
1504 snprintf(buffer, SIZE, "\nInputs dump:\n");
1505 write(fd, buffer, strlen(buffer));
1506 for (size_t i = 0; i < mInputs.size(); i++) {
1507 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1508 write(fd, buffer, strlen(buffer));
1509 mInputs.valueAt(i)->dump(fd);
1510 }
1511
1512 snprintf(buffer, SIZE, "\nStreams dump:\n");
1513 write(fd, buffer, strlen(buffer));
1514 snprintf(buffer, SIZE,
1515 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1516 write(fd, buffer, strlen(buffer));
Eric Laurent3b73df72014-03-11 09:06:29 -07001517 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001518 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001519 write(fd, buffer, strlen(buffer));
1520 mStreams[i].dump(fd);
1521 }
1522
1523 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1524 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1525 write(fd, buffer, strlen(buffer));
1526
1527 snprintf(buffer, SIZE, "Registered effects:\n");
1528 write(fd, buffer, strlen(buffer));
1529 for (size_t i = 0; i < mEffects.size(); i++) {
1530 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1531 write(fd, buffer, strlen(buffer));
1532 mEffects.valueAt(i)->dump(fd);
1533 }
1534
1535
1536 return NO_ERROR;
1537}
1538
1539// This function checks for the parameters which can be offloaded.
1540// This can be enhanced depending on the capability of the DSP and policy
1541// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001542bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001543{
1544 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001545 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001546 offloadInfo.sample_rate, offloadInfo.channel_mask,
1547 offloadInfo.format,
1548 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1549 offloadInfo.has_video);
1550
1551 // Check if offload has been disabled
1552 char propValue[PROPERTY_VALUE_MAX];
1553 if (property_get("audio.offload.disable", propValue, "0")) {
1554 if (atoi(propValue) != 0) {
1555 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1556 return false;
1557 }
1558 }
1559
1560 // Check if stream type is music, then only allow offload as of now.
1561 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1562 {
1563 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1564 return false;
1565 }
1566
1567 //TODO: enable audio offloading with video when ready
1568 if (offloadInfo.has_video)
1569 {
1570 ALOGV("isOffloadSupported: has_video == true, returning false");
1571 return false;
1572 }
1573
1574 //If duration is less than minimum value defined in property, return false
1575 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1576 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1577 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1578 return false;
1579 }
1580 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1581 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1582 return false;
1583 }
1584
1585 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1586 // creating an offloaded track and tearing it down immediately after start when audioflinger
1587 // detects there is an active non offloadable effect.
1588 // FIXME: We should check the audio session here but we do not have it in this context.
1589 // This may prevent offloading in rare situations where effects are left active by apps
1590 // in the background.
1591 if (isNonOffloadableEffectEnabled()) {
1592 return false;
1593 }
1594
1595 // See if there is a profile to support this.
1596 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001597 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001598 offloadInfo.sample_rate,
1599 offloadInfo.format,
1600 offloadInfo.channel_mask,
1601 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001602 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1603 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001604}
1605
Eric Laurent6a94d692014-05-20 11:18:06 -07001606status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1607 audio_port_type_t type,
1608 unsigned int *num_ports,
1609 struct audio_port *ports,
1610 unsigned int *generation)
1611{
1612 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1613 generation == NULL) {
1614 return BAD_VALUE;
1615 }
1616 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1617 if (ports == NULL) {
1618 *num_ports = 0;
1619 }
1620
1621 size_t portsWritten = 0;
1622 size_t portsMax = *num_ports;
1623 *num_ports = 0;
1624 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1625 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1626 for (size_t i = 0;
1627 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1628 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1629 }
1630 *num_ports += mAvailableOutputDevices.size();
1631 }
1632 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1633 for (size_t i = 0;
1634 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1635 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1636 }
1637 *num_ports += mAvailableInputDevices.size();
1638 }
1639 }
1640 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1641 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1642 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1643 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1644 }
1645 *num_ports += mInputs.size();
1646 }
1647 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1648 for (size_t i = 0; i < mOutputs.size() && portsWritten < portsMax; i++) {
1649 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1650 }
1651 *num_ports += mOutputs.size();
1652 }
1653 }
1654 *generation = curAudioPortGeneration();
1655 ALOGV("listAudioPorts() got %d ports needed %d", portsWritten, *num_ports);
1656 return NO_ERROR;
1657}
1658
1659status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1660{
1661 return NO_ERROR;
1662}
1663
1664AudioPolicyManager::AudioOutputDescriptor *AudioPolicyManager::getOutputFromId(
1665 audio_port_handle_t id) const
1666{
1667 AudioOutputDescriptor *outputDesc = NULL;
1668 for (size_t i = 0; i < mOutputs.size(); i++) {
1669 outputDesc = mOutputs.valueAt(i);
1670 if (outputDesc->mId == id) {
1671 break;
1672 }
1673 }
1674 return outputDesc;
1675}
1676
1677AudioPolicyManager::AudioInputDescriptor *AudioPolicyManager::getInputFromId(
1678 audio_port_handle_t id) const
1679{
1680 AudioInputDescriptor *inputDesc = NULL;
1681 for (size_t i = 0; i < mInputs.size(); i++) {
1682 inputDesc = mInputs.valueAt(i);
1683 if (inputDesc->mId == id) {
1684 break;
1685 }
1686 }
1687 return inputDesc;
1688}
1689
1690AudioPolicyManager::HwModule *AudioPolicyManager::getModuleForDevice(audio_devices_t device) const
1691{
1692 for (size_t i = 0; i < mHwModules.size(); i++) {
1693 if (mHwModules[i]->mHandle == 0) {
1694 continue;
1695 }
1696 if (audio_is_output_device(device)) {
1697 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1698 {
1699 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1700 return mHwModules[i];
1701 }
1702 }
1703 } else {
1704 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1705 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1706 device & ~AUDIO_DEVICE_BIT_IN) {
1707 return mHwModules[i];
1708 }
1709 }
1710 }
1711 }
1712 return NULL;
1713}
1714
1715status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1716 audio_patch_handle_t *handle,
1717 uid_t uid)
1718{
1719 ALOGV("createAudioPatch()");
1720
1721 if (handle == NULL || patch == NULL) {
1722 return BAD_VALUE;
1723 }
1724 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1725
1726 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1727 return INVALID_OPERATION;
1728 }
1729 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1730 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1731 return INVALID_OPERATION;
1732 }
1733
1734 sp<AudioPatch> patchDesc;
1735 ssize_t index = mAudioPatches.indexOfKey(*handle);
1736
1737 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1738 patch->sinks[0].type);
1739 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1740 patch->sources[0].role,
1741 patch->sources[0].type);
1742
1743 if (index >= 0) {
1744 patchDesc = mAudioPatches.valueAt(index);
1745 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1746 mUidCached, patchDesc->mUid, uid);
1747 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1748 return INVALID_OPERATION;
1749 }
1750 } else {
1751 *handle = 0;
1752 }
1753
1754 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1755 // TODO add support for mix to mix connection
1756 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1757 ALOGV("createAudioPatch() source mix sink not device");
1758 return BAD_VALUE;
1759 }
1760 // output mix to output device connection
1761 AudioOutputDescriptor *outputDesc = getOutputFromId(patch->sources[0].id);
1762 if (outputDesc == NULL) {
1763 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1764 return BAD_VALUE;
1765 }
1766 if (patchDesc != 0) {
1767 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1768 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1769 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1770 return BAD_VALUE;
1771 }
1772 }
1773 sp<DeviceDescriptor> devDesc =
1774 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1775 if (devDesc == 0) {
1776 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1777 return BAD_VALUE;
1778 }
1779
1780 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1781 patch->sources[0].sample_rate,
1782 patch->sources[0].format,
1783 patch->sources[0].channel_mask,
1784 AUDIO_OUTPUT_FLAG_NONE)) {
1785 return INVALID_OPERATION;
1786 }
1787 // TODO: reconfigure output format and channels here
1788 ALOGV("createAudioPatch() setting device %08x on output %d",
1789 devDesc->mType, outputDesc->mIoHandle);
1790 setOutputDevice(outputDesc->mIoHandle,
1791 devDesc->mType,
1792 true,
1793 0,
1794 handle);
1795 index = mAudioPatches.indexOfKey(*handle);
1796 if (index >= 0) {
1797 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1798 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1799 }
1800 patchDesc = mAudioPatches.valueAt(index);
1801 patchDesc->mUid = uid;
1802 ALOGV("createAudioPatch() success");
1803 } else {
1804 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1805 return INVALID_OPERATION;
1806 }
1807 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1808 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1809 // input device to input mix connection
1810 AudioInputDescriptor *inputDesc = getInputFromId(patch->sinks[0].id);
1811 if (inputDesc == NULL) {
1812 return BAD_VALUE;
1813 }
1814 if (patchDesc != 0) {
1815 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1816 return BAD_VALUE;
1817 }
1818 }
1819 sp<DeviceDescriptor> devDesc =
1820 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1821 if (devDesc == 0) {
1822 return BAD_VALUE;
1823 }
1824
1825 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1826 patch->sinks[0].sample_rate,
1827 patch->sinks[0].format,
1828 patch->sinks[0].channel_mask,
1829 AUDIO_OUTPUT_FLAG_NONE)) {
1830 return INVALID_OPERATION;
1831 }
1832 // TODO: reconfigure output format and channels here
1833 ALOGV("createAudioPatch() setting device %08x on output %d",
1834 devDesc->mType, inputDesc->mIoHandle);
1835 setInputDevice(inputDesc->mIoHandle,
1836 devDesc->mType,
1837 true,
1838 handle);
1839 index = mAudioPatches.indexOfKey(*handle);
1840 if (index >= 0) {
1841 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1842 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1843 }
1844 patchDesc = mAudioPatches.valueAt(index);
1845 patchDesc->mUid = uid;
1846 ALOGV("createAudioPatch() success");
1847 } else {
1848 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1849 return INVALID_OPERATION;
1850 }
1851 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1852 // device to device connection
1853 if (patchDesc != 0) {
1854 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1855 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1856 return BAD_VALUE;
1857 }
1858 }
1859
1860 sp<DeviceDescriptor> srcDeviceDesc =
1861 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1862 sp<DeviceDescriptor> sinkDeviceDesc =
1863 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1864 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1865 return BAD_VALUE;
1866 }
1867 //update source and sink with our own data as the data passed in the patch may
1868 // be incomplete.
1869 struct audio_patch newPatch = *patch;
1870 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1871 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1872
1873 // TODO: add support for devices on different HW modules
1874 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1875 return INVALID_OPERATION;
1876 }
1877 // TODO: check from routing capabilities in config file and other conflicting patches
1878
1879 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1880 if (index >= 0) {
1881 afPatchHandle = patchDesc->mAfPatchHandle;
1882 }
1883
1884 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1885 &afPatchHandle,
1886 0);
1887 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1888 status, afPatchHandle);
1889 if (status == NO_ERROR) {
1890 if (index < 0) {
1891 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1892 &newPatch, uid);
1893 addAudioPatch(patchDesc->mHandle, patchDesc);
1894 } else {
1895 patchDesc->mPatch = newPatch;
1896 }
1897 patchDesc->mAfPatchHandle = afPatchHandle;
1898 *handle = patchDesc->mHandle;
1899 nextAudioPortGeneration();
1900 } else {
1901 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1902 status);
1903 return INVALID_OPERATION;
1904 }
1905 } else {
1906 return BAD_VALUE;
1907 }
1908 } else {
1909 return BAD_VALUE;
1910 }
1911 return NO_ERROR;
1912}
1913
1914status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1915 uid_t uid)
1916{
1917 ALOGV("releaseAudioPatch() patch %d", handle);
1918
1919 ssize_t index = mAudioPatches.indexOfKey(handle);
1920
1921 if (index < 0) {
1922 return BAD_VALUE;
1923 }
1924 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1925 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1926 mUidCached, patchDesc->mUid, uid);
1927 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1928 return INVALID_OPERATION;
1929 }
1930
1931 struct audio_patch *patch = &patchDesc->mPatch;
1932 patchDesc->mUid = mUidCached;
1933 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1934 AudioOutputDescriptor *outputDesc = getOutputFromId(patch->sources[0].id);
1935 if (outputDesc == NULL) {
1936 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
1937 return BAD_VALUE;
1938 }
1939
1940 setOutputDevice(outputDesc->mIoHandle,
1941 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
1942 true,
1943 0,
1944 NULL);
1945 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1946 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1947 AudioInputDescriptor *inputDesc = getInputFromId(patch->sinks[0].id);
1948 if (inputDesc == NULL) {
1949 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
1950 return BAD_VALUE;
1951 }
1952 setInputDevice(inputDesc->mIoHandle,
1953 getNewInputDevice(inputDesc->mIoHandle),
1954 true,
1955 NULL);
1956 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1957 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
1958 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1959 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
1960 status, patchDesc->mAfPatchHandle);
1961 removeAudioPatch(patchDesc->mHandle);
1962 nextAudioPortGeneration();
1963 } else {
1964 return BAD_VALUE;
1965 }
1966 } else {
1967 return BAD_VALUE;
1968 }
1969 return NO_ERROR;
1970}
1971
1972status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
1973 struct audio_patch *patches,
1974 unsigned int *generation)
1975{
1976 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
1977 generation == NULL) {
1978 return BAD_VALUE;
1979 }
1980 ALOGV("listAudioPatches() num_patches %d patches %p available patches %d",
1981 *num_patches, patches, mAudioPatches.size());
1982 if (patches == NULL) {
1983 *num_patches = 0;
1984 }
1985
1986 size_t patchesWritten = 0;
1987 size_t patchesMax = *num_patches;
1988 for (size_t i = 0;
1989 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
1990 patches[patchesWritten] = mAudioPatches[i]->mPatch;
1991 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
1992 ALOGV("listAudioPatches() patch %d num_sources %d num_sinks %d",
1993 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
1994 }
1995 *num_patches = mAudioPatches.size();
1996
1997 *generation = curAudioPortGeneration();
1998 ALOGV("listAudioPatches() got %d patches needed %d", patchesWritten, *num_patches);
1999 return NO_ERROR;
2000}
2001
2002status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config __unused)
2003{
2004 return NO_ERROR;
2005}
2006
2007void AudioPolicyManager::clearAudioPatches(uid_t uid)
2008{
2009 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2010 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2011 if (patchDesc->mUid == uid) {
2012 // releaseAudioPatch() removes the patch from mAudioPatches
2013 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2014 i--;
2015 }
2016 }
2017 }
2018}
2019
2020status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2021 const sp<AudioPatch>& patch)
2022{
2023 ssize_t index = mAudioPatches.indexOfKey(handle);
2024
2025 if (index >= 0) {
2026 ALOGW("addAudioPatch() patch %d already in", handle);
2027 return ALREADY_EXISTS;
2028 }
2029 mAudioPatches.add(handle, patch);
2030 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2031 "sink handle %d",
2032 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2033 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2034 return NO_ERROR;
2035}
2036
2037status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2038{
2039 ssize_t index = mAudioPatches.indexOfKey(handle);
2040
2041 if (index < 0) {
2042 ALOGW("removeAudioPatch() patch %d not in", handle);
2043 return ALREADY_EXISTS;
2044 }
2045 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2046 mAudioPatches.valueAt(index)->mAfPatchHandle);
2047 mAudioPatches.removeItemsAt(index);
2048 return NO_ERROR;
2049}
2050
Eric Laurente552edb2014-03-10 17:42:56 -07002051// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002052// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002053// ----------------------------------------------------------------------------
2054
Eric Laurent3a4311c2014-03-17 12:00:47 -07002055uint32_t AudioPolicyManager::nextUniqueId()
2056{
2057 return android_atomic_inc(&mNextUniqueId);
2058}
2059
Eric Laurent6a94d692014-05-20 11:18:06 -07002060uint32_t AudioPolicyManager::nextAudioPortGeneration()
2061{
2062 return android_atomic_inc(&mAudioPortGeneration);
2063}
2064
Eric Laurente0720872014-03-11 09:30:41 -07002065AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002066 :
2067#ifdef AUDIO_POLICY_TEST
2068 Thread(false),
2069#endif //AUDIO_POLICY_TEST
2070 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002071 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002072 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2073 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002074 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002075 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2076 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002077{
Eric Laurent6a94d692014-05-20 11:18:06 -07002078 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002079 mpClientInterface = clientInterface;
2080
Eric Laurent3b73df72014-03-11 09:06:29 -07002081 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2082 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
2084
Eric Laurent3a4311c2014-03-17 12:00:47 -07002085 mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002086 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2087 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2088 ALOGE("could not load audio policy configuration file, setting defaults");
2089 defaultAudioPolicyConfig();
2090 }
2091 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002092 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002093
2094 // must be done after reading the policy
2095 initializeVolumeCurves();
2096
2097 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002098 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2099 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002100 for (size_t i = 0; i < mHwModules.size(); i++) {
2101 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2102 if (mHwModules[i]->mHandle == 0) {
2103 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2104 continue;
2105 }
2106 // open all output streams needed to access attached devices
2107 // except for direct output streams that are only opened when they are actually
2108 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002109 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002110 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2111 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002112 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002113
Eric Laurent3a4311c2014-03-17 12:00:47 -07002114 if (outProfile->mSupportedDevices.isEmpty()) {
2115 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2116 continue;
2117 }
2118
2119 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2120 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002121 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
2122 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002123
Eric Laurent1c333e22014-05-20 10:48:17 -07002124 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002125 audio_io_handle_t output = mpClientInterface->openOutput(
2126 outProfile->mModule->mHandle,
2127 &outputDesc->mDevice,
2128 &outputDesc->mSamplingRate,
2129 &outputDesc->mFormat,
2130 &outputDesc->mChannelMask,
2131 &outputDesc->mLatency,
2132 outputDesc->mFlags);
2133 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002134 ALOGW("Cannot open output stream for device %08x on hw module %s",
2135 outputDesc->mDevice,
2136 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002137 delete outputDesc;
2138 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002139 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002140 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002141 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002142 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002143 // give a valid ID to an attached device once confirmed it is reachable
2144 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2145 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002146 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002147 }
2148 }
Eric Laurente552edb2014-03-10 17:42:56 -07002149 if (mPrimaryOutput == 0 &&
2150 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2151 mPrimaryOutput = output;
2152 }
2153 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002154 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002155 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002156 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002157 true);
2158 }
2159 }
2160 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002161 // open input streams needed to access attached devices to validate
2162 // mAvailableInputDevices list
2163 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2164 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002165 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002166
Eric Laurent3a4311c2014-03-17 12:00:47 -07002167 if (inProfile->mSupportedDevices.isEmpty()) {
2168 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2169 continue;
2170 }
2171
2172 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2173 if (profileTypes & inputDeviceTypes) {
2174 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(inProfile);
2175
2176 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002177 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002178 audio_io_handle_t input = mpClientInterface->openInput(
2179 inProfile->mModule->mHandle,
2180 &inputDesc->mDevice,
2181 &inputDesc->mSamplingRate,
2182 &inputDesc->mFormat,
2183 &inputDesc->mChannelMask);
2184
2185 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002186 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002187 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002188 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002189 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002190 // give a valid ID to an attached device once confirmed it is reachable
2191 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2192 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002193 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002194 }
2195 }
2196 mpClientInterface->closeInput(input);
2197 } else {
2198 ALOGW("Cannot open input stream for device %08x on hw module %s",
2199 inputDesc->mDevice,
2200 mHwModules[i]->mName);
2201 }
2202 delete inputDesc;
2203 }
2204 }
2205 }
2206 // make sure all attached devices have been allocated a unique ID
2207 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2208 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002209 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002210 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2211 continue;
2212 }
2213 i++;
2214 }
2215 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2216 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002217 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002218 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2219 continue;
2220 }
2221 i++;
2222 }
2223 // make sure default device is reachable
2224 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002225 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002226 }
Eric Laurente552edb2014-03-10 17:42:56 -07002227
2228 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2229
2230 updateDevicesAndOutputs();
2231
2232#ifdef AUDIO_POLICY_TEST
2233 if (mPrimaryOutput != 0) {
2234 AudioParameter outputCmd = AudioParameter();
2235 outputCmd.addInt(String8("set_id"), 0);
2236 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2237
2238 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2239 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002240 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2241 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002242 mTestLatencyMs = 0;
2243 mCurOutput = 0;
2244 mDirectOutput = false;
2245 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2246 mTestOutputs[i] = 0;
2247 }
2248
2249 const size_t SIZE = 256;
2250 char buffer[SIZE];
2251 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2252 run(buffer, ANDROID_PRIORITY_AUDIO);
2253 }
2254#endif //AUDIO_POLICY_TEST
2255}
2256
Eric Laurente0720872014-03-11 09:30:41 -07002257AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002258{
2259#ifdef AUDIO_POLICY_TEST
2260 exit();
2261#endif //AUDIO_POLICY_TEST
2262 for (size_t i = 0; i < mOutputs.size(); i++) {
2263 mpClientInterface->closeOutput(mOutputs.keyAt(i));
2264 delete mOutputs.valueAt(i);
2265 }
2266 for (size_t i = 0; i < mInputs.size(); i++) {
2267 mpClientInterface->closeInput(mInputs.keyAt(i));
2268 delete mInputs.valueAt(i);
2269 }
2270 for (size_t i = 0; i < mHwModules.size(); i++) {
2271 delete mHwModules[i];
2272 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002273 mAvailableOutputDevices.clear();
2274 mAvailableInputDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002275}
2276
Eric Laurente0720872014-03-11 09:30:41 -07002277status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002278{
2279 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2280}
2281
2282#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002283bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002284{
2285 ALOGV("entering threadLoop()");
2286 while (!exitPending())
2287 {
2288 String8 command;
2289 int valueInt;
2290 String8 value;
2291
2292 Mutex::Autolock _l(mLock);
2293 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2294
2295 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2296 AudioParameter param = AudioParameter(command);
2297
2298 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2299 valueInt != 0) {
2300 ALOGV("Test command %s received", command.string());
2301 String8 target;
2302 if (param.get(String8("target"), target) != NO_ERROR) {
2303 target = "Manager";
2304 }
2305 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2306 param.remove(String8("test_cmd_policy_output"));
2307 mCurOutput = valueInt;
2308 }
2309 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2310 param.remove(String8("test_cmd_policy_direct"));
2311 if (value == "false") {
2312 mDirectOutput = false;
2313 } else if (value == "true") {
2314 mDirectOutput = true;
2315 }
2316 }
2317 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2318 param.remove(String8("test_cmd_policy_input"));
2319 mTestInput = valueInt;
2320 }
2321
2322 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2323 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002324 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002325 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002326 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002327 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002328 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002329 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002330 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002331 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002332 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002333 if (target == "Manager") {
2334 mTestFormat = format;
2335 } else if (mTestOutputs[mCurOutput] != 0) {
2336 AudioParameter outputParam = AudioParameter();
2337 outputParam.addInt(String8("format"), format);
2338 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2339 }
2340 }
2341 }
2342 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2343 param.remove(String8("test_cmd_policy_channels"));
2344 int channels = 0;
2345
2346 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002347 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002348 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002349 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002350 }
2351 if (channels != 0) {
2352 if (target == "Manager") {
2353 mTestChannels = channels;
2354 } else if (mTestOutputs[mCurOutput] != 0) {
2355 AudioParameter outputParam = AudioParameter();
2356 outputParam.addInt(String8("channels"), channels);
2357 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2358 }
2359 }
2360 }
2361 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2362 param.remove(String8("test_cmd_policy_sampleRate"));
2363 if (valueInt >= 0 && valueInt <= 96000) {
2364 int samplingRate = valueInt;
2365 if (target == "Manager") {
2366 mTestSamplingRate = samplingRate;
2367 } else if (mTestOutputs[mCurOutput] != 0) {
2368 AudioParameter outputParam = AudioParameter();
2369 outputParam.addInt(String8("sampling_rate"), samplingRate);
2370 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2371 }
2372 }
2373 }
2374
2375 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2376 param.remove(String8("test_cmd_policy_reopen"));
2377
2378 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2379 mpClientInterface->closeOutput(mPrimaryOutput);
2380
2381 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2382
2383 delete mOutputs.valueFor(mPrimaryOutput);
2384 mOutputs.removeItem(mPrimaryOutput);
2385
2386 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
2387 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2388 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2389 &outputDesc->mDevice,
2390 &outputDesc->mSamplingRate,
2391 &outputDesc->mFormat,
2392 &outputDesc->mChannelMask,
2393 &outputDesc->mLatency,
2394 outputDesc->mFlags);
2395 if (mPrimaryOutput == 0) {
2396 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2397 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2398 } else {
2399 AudioParameter outputCmd = AudioParameter();
2400 outputCmd.addInt(String8("set_id"), 0);
2401 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2402 addOutput(mPrimaryOutput, outputDesc);
2403 }
2404 }
2405
2406
2407 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2408 }
2409 }
2410 return false;
2411}
2412
Eric Laurente0720872014-03-11 09:30:41 -07002413void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002414{
2415 {
2416 AutoMutex _l(mLock);
2417 requestExit();
2418 mWaitWorkCV.signal();
2419 }
2420 requestExitAndWait();
2421}
2422
Eric Laurente0720872014-03-11 09:30:41 -07002423int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002424{
2425 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2426 if (output == mTestOutputs[i]) return i;
2427 }
2428 return 0;
2429}
2430#endif //AUDIO_POLICY_TEST
2431
2432// ---
2433
Eric Laurent1c333e22014-05-20 10:48:17 -07002434void AudioPolicyManager::addOutput(audio_io_handle_t output, AudioOutputDescriptor *outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002435{
Eric Laurent1c333e22014-05-20 10:48:17 -07002436 outputDesc->mIoHandle = output;
2437 outputDesc->mId = nextUniqueId();
2438 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002439 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002440}
2441
Eric Laurent1c333e22014-05-20 10:48:17 -07002442void AudioPolicyManager::addInput(audio_io_handle_t input, AudioInputDescriptor *inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002443{
Eric Laurent1c333e22014-05-20 10:48:17 -07002444 inputDesc->mIoHandle = input;
2445 inputDesc->mId = nextUniqueId();
2446 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002447 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002448}
Eric Laurente552edb2014-03-10 17:42:56 -07002449
Eric Laurent3a4311c2014-03-17 12:00:47 -07002450String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2451{
2452 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2453 return String8("a2dp_sink_address=")+address;
2454 }
2455 return address;
2456}
2457
Eric Laurente0720872014-03-11 09:30:41 -07002458status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002459 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002460 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002461 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002462{
2463 AudioOutputDescriptor *desc;
2464
Eric Laurent3b73df72014-03-11 09:06:29 -07002465 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002466 // first list already open outputs that can be routed to this device
2467 for (size_t i = 0; i < mOutputs.size(); i++) {
2468 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002469 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002470 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2471 outputs.add(mOutputs.keyAt(i));
2472 }
2473 }
2474 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002475 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002476 for (size_t i = 0; i < mHwModules.size(); i++)
2477 {
2478 if (mHwModules[i]->mHandle == 0) {
2479 continue;
2480 }
2481 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2482 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002483 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002484 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002485 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2486 }
2487 }
2488 }
2489
2490 if (profiles.isEmpty() && outputs.isEmpty()) {
2491 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2492 return BAD_VALUE;
2493 }
2494
2495 // open outputs for matching profiles if needed. Direct outputs are also opened to
2496 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2497 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002498 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002499
2500 // nothing to do if one output is already opened for this profile
2501 size_t j;
2502 for (j = 0; j < mOutputs.size(); j++) {
2503 desc = mOutputs.valueAt(j);
2504 if (!desc->isDuplicated() && desc->mProfile == profile) {
2505 break;
2506 }
2507 }
2508 if (j != mOutputs.size()) {
2509 continue;
2510 }
2511
Eric Laurent3a4311c2014-03-17 12:00:47 -07002512 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002513 desc = new AudioOutputDescriptor(profile);
2514 desc->mDevice = device;
2515 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2516 offloadInfo.sample_rate = desc->mSamplingRate;
2517 offloadInfo.format = desc->mFormat;
2518 offloadInfo.channel_mask = desc->mChannelMask;
2519
2520 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2521 &desc->mDevice,
2522 &desc->mSamplingRate,
2523 &desc->mFormat,
2524 &desc->mChannelMask,
2525 &desc->mLatency,
2526 desc->mFlags,
2527 &offloadInfo);
2528 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002529 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002530 if (!address.isEmpty()) {
2531 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002532 }
2533
Eric Laurentd4692962014-05-05 18:13:44 -07002534 // Here is where we step through and resolve any "dynamic" fields
2535 String8 reply;
2536 char *value;
2537 if (profile->mSamplingRates[0] == 0) {
2538 reply = mpClientInterface->getParameters(output,
2539 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2540 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2541 reply.string());
2542 value = strpbrk((char *)reply.string(), "=");
2543 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002544 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002545 }
Eric Laurentd4692962014-05-05 18:13:44 -07002546 }
2547 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2548 reply = mpClientInterface->getParameters(output,
2549 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2550 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2551 reply.string());
2552 value = strpbrk((char *)reply.string(), "=");
2553 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002554 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002555 }
Eric Laurentd4692962014-05-05 18:13:44 -07002556 }
2557 if (profile->mChannelMasks[0] == 0) {
2558 reply = mpClientInterface->getParameters(output,
2559 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2560 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2561 reply.string());
2562 value = strpbrk((char *)reply.string(), "=");
2563 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002564 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002565 }
Eric Laurentd4692962014-05-05 18:13:44 -07002566 }
2567 if (((profile->mSamplingRates[0] == 0) &&
2568 (profile->mSamplingRates.size() < 2)) ||
2569 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2570 (profile->mFormats.size() < 2)) ||
2571 ((profile->mChannelMasks[0] == 0) &&
2572 (profile->mChannelMasks.size() < 2))) {
2573 ALOGW("checkOutputsForDevice() direct output missing param");
2574 mpClientInterface->closeOutput(output);
2575 output = 0;
2576 } else if (profile->mSamplingRates[0] == 0) {
2577 mpClientInterface->closeOutput(output);
2578 desc->mSamplingRate = profile->mSamplingRates[1];
2579 offloadInfo.sample_rate = desc->mSamplingRate;
2580 output = mpClientInterface->openOutput(
2581 profile->mModule->mHandle,
2582 &desc->mDevice,
2583 &desc->mSamplingRate,
2584 &desc->mFormat,
2585 &desc->mChannelMask,
2586 &desc->mLatency,
2587 desc->mFlags,
2588 &offloadInfo);
2589 }
2590
2591 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002592 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002593 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2594 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002595
Eric Laurentd4692962014-05-05 18:13:44 -07002596 // set initial stream volume for device
2597 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002598
Eric Laurentd4692962014-05-05 18:13:44 -07002599 //TODO: configure audio effect output stage here
2600
2601 // open a duplicating output thread for the new output and the primary output
2602 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2603 mPrimaryOutput);
2604 if (duplicatedOutput != 0) {
2605 // add duplicated output descriptor
2606 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
2607 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2608 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2609 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2610 dupOutputDesc->mFormat = desc->mFormat;
2611 dupOutputDesc->mChannelMask = desc->mChannelMask;
2612 dupOutputDesc->mLatency = desc->mLatency;
2613 addOutput(duplicatedOutput, dupOutputDesc);
2614 applyStreamVolumes(duplicatedOutput, device, 0, true);
2615 } else {
2616 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2617 mPrimaryOutput, output);
2618 mpClientInterface->closeOutput(output);
2619 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002620 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002621 output = 0;
2622 }
Eric Laurente552edb2014-03-10 17:42:56 -07002623 }
2624 }
2625 }
2626 if (output == 0) {
2627 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2628 delete desc;
2629 profiles.removeAt(profile_index);
2630 profile_index--;
2631 } else {
2632 outputs.add(output);
2633 ALOGV("checkOutputsForDevice(): adding output %d", output);
2634 }
2635 }
2636
2637 if (profiles.isEmpty()) {
2638 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2639 return BAD_VALUE;
2640 }
Eric Laurentd4692962014-05-05 18:13:44 -07002641 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002642 // check if one opened output is not needed any more after disconnecting one device
2643 for (size_t i = 0; i < mOutputs.size(); i++) {
2644 desc = mOutputs.valueAt(i);
2645 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002646 !(desc->mProfile->mSupportedDevices.types() &
2647 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002648 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2649 outputs.add(mOutputs.keyAt(i));
2650 }
2651 }
Eric Laurentd4692962014-05-05 18:13:44 -07002652 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002653 for (size_t i = 0; i < mHwModules.size(); i++)
2654 {
2655 if (mHwModules[i]->mHandle == 0) {
2656 continue;
2657 }
2658 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2659 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002660 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002661 if (profile->mSupportedDevices.types() & device) {
2662 ALOGV("checkOutputsForDevice(): "
2663 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002664 if (profile->mSamplingRates[0] == 0) {
2665 profile->mSamplingRates.clear();
2666 profile->mSamplingRates.add(0);
2667 }
2668 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2669 profile->mFormats.clear();
2670 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2671 }
2672 if (profile->mChannelMasks[0] == 0) {
2673 profile->mChannelMasks.clear();
2674 profile->mChannelMasks.add(0);
2675 }
2676 }
2677 }
2678 }
2679 }
2680 return NO_ERROR;
2681}
2682
Eric Laurentd4692962014-05-05 18:13:44 -07002683status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2684 audio_policy_dev_state_t state,
2685 SortedVector<audio_io_handle_t>& inputs,
2686 const String8 address)
2687{
2688 AudioInputDescriptor *desc;
2689 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2690 // first list already open inputs that can be routed to this device
2691 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2692 desc = mInputs.valueAt(input_index);
2693 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2694 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2695 inputs.add(mInputs.keyAt(input_index));
2696 }
2697 }
2698
2699 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002700 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002701 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2702 {
2703 if (mHwModules[module_idx]->mHandle == 0) {
2704 continue;
2705 }
2706 for (size_t profile_index = 0;
2707 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2708 profile_index++)
2709 {
2710 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2711 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2712 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2713 profile_index, module_idx);
2714 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2715 }
2716 }
2717 }
2718
2719 if (profiles.isEmpty() && inputs.isEmpty()) {
2720 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2721 return BAD_VALUE;
2722 }
2723
2724 // open inputs for matching profiles if needed. Direct inputs are also opened to
2725 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2726 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2727
Eric Laurent1c333e22014-05-20 10:48:17 -07002728 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002729 // nothing to do if one input is already opened for this profile
2730 size_t input_index;
2731 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2732 desc = mInputs.valueAt(input_index);
2733 if (desc->mProfile == profile) {
2734 break;
2735 }
2736 }
2737 if (input_index != mInputs.size()) {
2738 continue;
2739 }
2740
2741 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2742 desc = new AudioInputDescriptor(profile);
2743 desc->mDevice = device;
2744
2745 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2746 &desc->mDevice,
2747 &desc->mSamplingRate,
2748 &desc->mFormat,
2749 &desc->mChannelMask);
2750
2751 if (input != 0) {
2752 if (!address.isEmpty()) {
2753 mpClientInterface->setParameters(input, addressToParameter(device, address));
2754 }
2755
2756 // Here is where we step through and resolve any "dynamic" fields
2757 String8 reply;
2758 char *value;
2759 if (profile->mSamplingRates[0] == 0) {
2760 reply = mpClientInterface->getParameters(input,
2761 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2762 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2763 reply.string());
2764 value = strpbrk((char *)reply.string(), "=");
2765 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002766 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002767 }
2768 }
2769 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2770 reply = mpClientInterface->getParameters(input,
2771 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2772 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2773 value = strpbrk((char *)reply.string(), "=");
2774 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002775 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002776 }
2777 }
2778 if (profile->mChannelMasks[0] == 0) {
2779 reply = mpClientInterface->getParameters(input,
2780 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2781 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2782 reply.string());
2783 value = strpbrk((char *)reply.string(), "=");
2784 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002785 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002786 }
2787 }
2788 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2789 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2790 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2791 ALOGW("checkInputsForDevice() direct input missing param");
2792 mpClientInterface->closeInput(input);
2793 input = 0;
2794 }
2795
2796 if (input != 0) {
2797 addInput(input, desc);
2798 }
2799 } // endif input != 0
2800
2801 if (input == 0) {
2802 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2803 delete desc;
2804 profiles.removeAt(profile_index);
2805 profile_index--;
2806 } else {
2807 inputs.add(input);
2808 ALOGV("checkInputsForDevice(): adding input %d", input);
2809 }
2810 } // end scan profiles
2811
2812 if (profiles.isEmpty()) {
2813 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2814 return BAD_VALUE;
2815 }
2816 } else {
2817 // Disconnect
2818 // check if one opened input is not needed any more after disconnecting one device
2819 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2820 desc = mInputs.valueAt(input_index);
2821 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2822 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2823 mInputs.keyAt(input_index));
2824 inputs.add(mInputs.keyAt(input_index));
2825 }
2826 }
2827 // Clear any profiles associated with the disconnected device.
2828 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2829 if (mHwModules[module_index]->mHandle == 0) {
2830 continue;
2831 }
2832 for (size_t profile_index = 0;
2833 profile_index < mHwModules[module_index]->mInputProfiles.size();
2834 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002835 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002836 if (profile->mSupportedDevices.types() & device) {
2837 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2838 profile_index, module_index);
2839 if (profile->mSamplingRates[0] == 0) {
2840 profile->mSamplingRates.clear();
2841 profile->mSamplingRates.add(0);
2842 }
2843 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2844 profile->mFormats.clear();
2845 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2846 }
2847 if (profile->mChannelMasks[0] == 0) {
2848 profile->mChannelMasks.clear();
2849 profile->mChannelMasks.add(0);
2850 }
2851 }
2852 }
2853 }
2854 } // end disconnect
2855
2856 return NO_ERROR;
2857}
2858
2859
Eric Laurente0720872014-03-11 09:30:41 -07002860void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002861{
2862 ALOGV("closeOutput(%d)", output);
2863
2864 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2865 if (outputDesc == NULL) {
2866 ALOGW("closeOutput() unknown output %d", output);
2867 return;
2868 }
2869
2870 // look for duplicated outputs connected to the output being removed.
2871 for (size_t i = 0; i < mOutputs.size(); i++) {
2872 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2873 if (dupOutputDesc->isDuplicated() &&
2874 (dupOutputDesc->mOutput1 == outputDesc ||
2875 dupOutputDesc->mOutput2 == outputDesc)) {
2876 AudioOutputDescriptor *outputDesc2;
2877 if (dupOutputDesc->mOutput1 == outputDesc) {
2878 outputDesc2 = dupOutputDesc->mOutput2;
2879 } else {
2880 outputDesc2 = dupOutputDesc->mOutput1;
2881 }
2882 // As all active tracks on duplicated output will be deleted,
2883 // and as they were also referenced on the other output, the reference
2884 // count for their stream type must be adjusted accordingly on
2885 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07002886 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07002887 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07002888 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07002889 }
2890 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2891 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2892
2893 mpClientInterface->closeOutput(duplicatedOutput);
2894 delete mOutputs.valueFor(duplicatedOutput);
2895 mOutputs.removeItem(duplicatedOutput);
2896 }
2897 }
2898
2899 AudioParameter param;
2900 param.add(String8("closing"), String8("true"));
2901 mpClientInterface->setParameters(output, param.toString());
2902
2903 mpClientInterface->closeOutput(output);
2904 delete outputDesc;
2905 mOutputs.removeItem(output);
2906 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002907 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002908}
2909
Eric Laurente0720872014-03-11 09:30:41 -07002910SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07002911 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2912{
2913 SortedVector<audio_io_handle_t> outputs;
2914
2915 ALOGVV("getOutputsForDevice() device %04x", device);
2916 for (size_t i = 0; i < openOutputs.size(); i++) {
2917 ALOGVV("output %d isDuplicated=%d device=%04x",
2918 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2919 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2920 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2921 outputs.add(openOutputs.keyAt(i));
2922 }
2923 }
2924 return outputs;
2925}
2926
Eric Laurente0720872014-03-11 09:30:41 -07002927bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07002928 SortedVector<audio_io_handle_t>& outputs2)
2929{
2930 if (outputs1.size() != outputs2.size()) {
2931 return false;
2932 }
2933 for (size_t i = 0; i < outputs1.size(); i++) {
2934 if (outputs1[i] != outputs2[i]) {
2935 return false;
2936 }
2937 }
2938 return true;
2939}
2940
Eric Laurente0720872014-03-11 09:30:41 -07002941void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07002942{
2943 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2944 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2945 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2946 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2947
2948 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2949 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2950 strategy, srcOutputs[0], dstOutputs[0]);
2951 // mute strategy while moving tracks from one output to another
2952 for (size_t i = 0; i < srcOutputs.size(); i++) {
2953 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2954 if (desc->isStrategyActive(strategy)) {
2955 setStrategyMute(strategy, true, srcOutputs[i]);
2956 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2957 }
2958 }
2959
2960 // Move effects associated to this strategy from previous output to new output
2961 if (strategy == STRATEGY_MEDIA) {
2962 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2963 SortedVector<audio_io_handle_t> moved;
2964 for (size_t i = 0; i < mEffects.size(); i++) {
2965 EffectDescriptor *desc = mEffects.valueAt(i);
2966 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2967 desc->mIo != fxOutput) {
2968 if (moved.indexOf(desc->mIo) < 0) {
2969 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2970 mEffects.keyAt(i), fxOutput);
2971 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2972 fxOutput);
2973 moved.add(desc->mIo);
2974 }
2975 desc->mIo = fxOutput;
2976 }
2977 }
2978 }
2979 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07002980 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2981 if (getStrategy((audio_stream_type_t)i) == strategy) {
2982 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07002983 }
2984 }
2985 }
2986}
2987
Eric Laurente0720872014-03-11 09:30:41 -07002988void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07002989{
2990 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2991 checkOutputForStrategy(STRATEGY_PHONE);
2992 checkOutputForStrategy(STRATEGY_SONIFICATION);
2993 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2994 checkOutputForStrategy(STRATEGY_MEDIA);
2995 checkOutputForStrategy(STRATEGY_DTMF);
2996}
2997
Eric Laurente0720872014-03-11 09:30:41 -07002998audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07002999{
Eric Laurente552edb2014-03-10 17:42:56 -07003000 for (size_t i = 0; i < mOutputs.size(); i++) {
3001 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
3002 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3003 return mOutputs.keyAt(i);
3004 }
3005 }
3006
3007 return 0;
3008}
3009
Eric Laurente0720872014-03-11 09:30:41 -07003010void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003011{
Eric Laurente552edb2014-03-10 17:42:56 -07003012 audio_io_handle_t a2dpOutput = getA2dpOutput();
3013 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003014 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003015 return;
3016 }
3017
Eric Laurent3a4311c2014-03-17 12:00:47 -07003018 bool isScoConnected =
3019 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003020 // suspend A2DP output if:
3021 // (NOT already suspended) &&
3022 // ((SCO device is connected &&
3023 // (forced usage for communication || for record is SCO))) ||
3024 // (phone state is ringing || in call)
3025 //
3026 // restore A2DP output if:
3027 // (Already suspended) &&
3028 // ((SCO device is NOT connected ||
3029 // (forced usage NOT for communication && NOT for record is SCO))) &&
3030 // (phone state is NOT ringing && NOT in call)
3031 //
3032 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003033 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003034 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3035 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3036 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3037 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003038
3039 mpClientInterface->restoreOutput(a2dpOutput);
3040 mA2dpSuspended = false;
3041 }
3042 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003043 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003044 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3045 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3046 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3047 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003048
3049 mpClientInterface->suspendOutput(a2dpOutput);
3050 mA2dpSuspended = true;
3051 }
3052 }
3053}
3054
Eric Laurent1c333e22014-05-20 10:48:17 -07003055audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003056{
3057 audio_devices_t device = AUDIO_DEVICE_NONE;
3058
3059 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003060
3061 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3062 if (index >= 0) {
3063 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3064 if (patchDesc->mUid != mUidCached) {
3065 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3066 outputDesc->device(), outputDesc->mPatchHandle);
3067 return outputDesc->device();
3068 }
3069 }
3070
Eric Laurente552edb2014-03-10 17:42:56 -07003071 // check the following by order of priority to request a routing change if necessary:
3072 // 1: the strategy enforced audible is active on the output:
3073 // use device for strategy enforced audible
3074 // 2: we are in call or the strategy phone is active on the output:
3075 // use device for strategy phone
3076 // 3: the strategy sonification is active on the output:
3077 // use device for strategy sonification
3078 // 4: the strategy "respectful" sonification is active on the output:
3079 // use device for strategy "respectful" sonification
3080 // 5: the strategy media is active on the output:
3081 // use device for strategy media
3082 // 6: the strategy DTMF is active on the output:
3083 // use device for strategy DTMF
3084 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3085 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3086 } else if (isInCall() ||
3087 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3088 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3089 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3090 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3091 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3092 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3093 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3094 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3095 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3096 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3097 }
3098
Eric Laurent1c333e22014-05-20 10:48:17 -07003099 ALOGV("getNewOutputDevice() selected device %x", device);
3100 return device;
3101}
3102
3103audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3104{
3105 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003106
3107 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3108 if (index >= 0) {
3109 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3110 if (patchDesc->mUid != mUidCached) {
3111 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3112 inputDesc->mDevice, inputDesc->mPatchHandle);
3113 return inputDesc->mDevice;
3114 }
3115 }
3116
Eric Laurent1c333e22014-05-20 10:48:17 -07003117 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3118
3119 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003120 return device;
3121}
3122
Eric Laurente0720872014-03-11 09:30:41 -07003123uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003124 return (uint32_t)getStrategy(stream);
3125}
3126
Eric Laurente0720872014-03-11 09:30:41 -07003127audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003128 // By checking the range of stream before calling getStrategy, we avoid
3129 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3130 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003131 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003132 return AUDIO_DEVICE_NONE;
3133 }
3134 audio_devices_t devices;
3135 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3136 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3137 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3138 for (size_t i = 0; i < outputs.size(); i++) {
3139 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
3140 if (outputDesc->isStrategyActive(strategy)) {
3141 devices = outputDesc->device();
3142 break;
3143 }
Eric Laurente552edb2014-03-10 17:42:56 -07003144 }
3145 return devices;
3146}
3147
Eric Laurente0720872014-03-11 09:30:41 -07003148AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003149 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003150 // stream to strategy mapping
3151 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003152 case AUDIO_STREAM_VOICE_CALL:
3153 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003154 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003155 case AUDIO_STREAM_RING:
3156 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003157 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003158 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003159 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003160 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003161 return STRATEGY_DTMF;
3162 default:
3163 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003164 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003165 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3166 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003167 case AUDIO_STREAM_TTS:
3168 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003169 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003170 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003171 return STRATEGY_ENFORCED_AUDIBLE;
3172 }
3173}
3174
Eric Laurente0720872014-03-11 09:30:41 -07003175void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003176 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003177 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003178 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3179 updateDevicesAndOutputs();
3180 break;
3181 default:
3182 break;
3183 }
3184}
3185
Eric Laurente0720872014-03-11 09:30:41 -07003186audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003187 bool fromCache)
3188{
3189 uint32_t device = AUDIO_DEVICE_NONE;
3190
3191 if (fromCache) {
3192 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3193 strategy, mDeviceForStrategy[strategy]);
3194 return mDeviceForStrategy[strategy];
3195 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003196 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003197 switch (strategy) {
3198
3199 case STRATEGY_SONIFICATION_RESPECTFUL:
3200 if (isInCall()) {
3201 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003202 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003203 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3204 // while media is playing on a remote device, use the the sonification behavior.
3205 // Note that we test this usecase before testing if media is playing because
3206 // the isStreamActive() method only informs about the activity of a stream, not
3207 // if it's for local playback. Note also that we use the same delay between both tests
3208 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003209 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003210 // while media is playing (or has recently played), use the same device
3211 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3212 } else {
3213 // when media is not playing anymore, fall back on the sonification behavior
3214 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3215 }
3216
3217 break;
3218
3219 case STRATEGY_DTMF:
3220 if (!isInCall()) {
3221 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3222 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3223 break;
3224 }
3225 // when in call, DTMF and PHONE strategies follow the same rules
3226 // FALL THROUGH
3227
3228 case STRATEGY_PHONE:
3229 // for phone strategy, we first consider the forced use and then the available devices by order
3230 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003231 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3232 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003233 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003234 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003235 if (device) break;
3236 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003237 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003238 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003239 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003240 if (device) break;
3241 // if SCO device is requested but no SCO device is available, fall back to default case
3242 // FALL THROUGH
3243
3244 default: // FORCE_NONE
3245 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003246 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003247 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003248 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003249 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003250 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003251 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003252 if (device) break;
3253 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003254 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003255 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003256 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003257 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003258 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003259 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003260 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003261 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003262 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003263 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003264 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003265 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003266 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003267 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003268 if (device) break;
3269 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003270 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003271 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003272 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003273 if (device == AUDIO_DEVICE_NONE) {
3274 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3275 }
3276 break;
3277
Eric Laurent3b73df72014-03-11 09:06:29 -07003278 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003279 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3280 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003281 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003282 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003283 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003284 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003285 if (device) break;
3286 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003287 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003288 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003289 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003290 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003291 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003292 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003293 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003294 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003295 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003296 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003297 if (device) break;
3298 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003299 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003300 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003301 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003302 if (device == AUDIO_DEVICE_NONE) {
3303 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3304 }
3305 break;
3306 }
3307 break;
3308
3309 case STRATEGY_SONIFICATION:
3310
3311 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3312 // handleIncallSonification().
3313 if (isInCall()) {
3314 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3315 break;
3316 }
3317 // FALL THROUGH
3318
3319 case STRATEGY_ENFORCED_AUDIBLE:
3320 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3321 // except:
3322 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3323 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3324
3325 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003326 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003327 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003328 if (device == AUDIO_DEVICE_NONE) {
3329 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3330 }
3331 }
3332 // The second device used for sonification is the same as the device used by media strategy
3333 // FALL THROUGH
3334
3335 case STRATEGY_MEDIA: {
3336 uint32_t device2 = AUDIO_DEVICE_NONE;
3337 if (strategy != STRATEGY_SONIFICATION) {
3338 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003339 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003340 }
3341 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003342 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003343 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003344 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003345 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003346 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003347 }
3348 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003349 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003350 }
3351 }
3352 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003353 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003354 }
3355 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003356 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003357 }
3358 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003359 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003360 }
3361 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003362 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003363 }
3364 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003365 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003366 }
3367 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3368 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003369 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003370 }
3371 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003372 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003373 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003374 }
3375 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003376 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003377 }
3378
3379 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3380 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3381 device |= device2;
3382 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003383 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003384 if (device == AUDIO_DEVICE_NONE) {
3385 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3386 }
3387 } break;
3388
3389 default:
3390 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3391 break;
3392 }
3393
3394 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3395 return device;
3396}
3397
Eric Laurente0720872014-03-11 09:30:41 -07003398void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003399{
3400 for (int i = 0; i < NUM_STRATEGIES; i++) {
3401 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3402 }
3403 mPreviousOutputs = mOutputs;
3404}
3405
Eric Laurente0720872014-03-11 09:30:41 -07003406uint32_t AudioPolicyManager::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003407 audio_devices_t prevDevice,
3408 uint32_t delayMs)
3409{
3410 // mute/unmute strategies using an incompatible device combination
3411 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3412 // if unmuting, unmute only after the specified delay
3413 if (outputDesc->isDuplicated()) {
3414 return 0;
3415 }
3416
3417 uint32_t muteWaitMs = 0;
3418 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003419 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003420
3421 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3422 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3423 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3424 bool doMute = false;
3425
3426 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3427 doMute = true;
3428 outputDesc->mStrategyMutedByDevice[i] = true;
3429 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3430 doMute = true;
3431 outputDesc->mStrategyMutedByDevice[i] = false;
3432 }
Eric Laurent99401132014-05-07 19:48:15 -07003433 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003434 for (size_t j = 0; j < mOutputs.size(); j++) {
3435 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
3436 // skip output if it does not share any device with current output
3437 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3438 == AUDIO_DEVICE_NONE) {
3439 continue;
3440 }
3441 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3442 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3443 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3444 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3445 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003446 if (mute) {
3447 // FIXME: should not need to double latency if volume could be applied
3448 // immediately by the audioflinger mixer. We must account for the delay
3449 // between now and the next time the audioflinger thread for this output
3450 // will process a buffer (which corresponds to one buffer size,
3451 // usually 1/2 or 1/4 of the latency).
3452 if (muteWaitMs < desc->latency() * 2) {
3453 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003454 }
3455 }
3456 }
3457 }
3458 }
3459 }
3460
Eric Laurent99401132014-05-07 19:48:15 -07003461 // temporary mute output if device selection changes to avoid volume bursts due to
3462 // different per device volumes
3463 if (outputDesc->isActive() && (device != prevDevice)) {
3464 if (muteWaitMs < outputDesc->latency() * 2) {
3465 muteWaitMs = outputDesc->latency() * 2;
3466 }
3467 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3468 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003469 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003470 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003471 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003472 muteWaitMs *2, device);
3473 }
3474 }
3475 }
3476
Eric Laurente552edb2014-03-10 17:42:56 -07003477 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3478 if (muteWaitMs > delayMs) {
3479 muteWaitMs -= delayMs;
3480 usleep(muteWaitMs * 1000);
3481 return muteWaitMs;
3482 }
3483 return 0;
3484}
3485
Eric Laurente0720872014-03-11 09:30:41 -07003486uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003487 audio_devices_t device,
3488 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003489 int delayMs,
3490 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003491{
3492 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
3493 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3494 AudioParameter param;
3495 uint32_t muteWaitMs;
3496
3497 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003498 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3499 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003500 return muteWaitMs;
3501 }
3502 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3503 // output profile
3504 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003505 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003506 return 0;
3507 }
3508
3509 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003510 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003511
3512 audio_devices_t prevDevice = outputDesc->mDevice;
3513
3514 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3515
3516 if (device != AUDIO_DEVICE_NONE) {
3517 outputDesc->mDevice = device;
3518 }
3519 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3520
3521 // Do not change the routing if:
3522 // - the requested device is AUDIO_DEVICE_NONE
3523 // - the requested device is the same as current device and force is not specified.
3524 // Doing this check here allows the caller to call setOutputDevice() without conditions
3525 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3526 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3527 return muteWaitMs;
3528 }
3529
3530 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003531
Eric Laurente552edb2014-03-10 17:42:56 -07003532 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003533 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003534 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003535 } else {
3536 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3537 if (!deviceList.isEmpty()) {
3538 struct audio_patch patch;
3539 outputDesc->toAudioPortConfig(&patch.sources[0]);
3540 patch.num_sources = 1;
3541 patch.num_sinks = 0;
3542 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3543 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003544 patch.num_sinks++;
3545 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003546 ssize_t index;
3547 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3548 index = mAudioPatches.indexOfKey(*patchHandle);
3549 } else {
3550 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3551 }
3552 sp< AudioPatch> patchDesc;
3553 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3554 if (index >= 0) {
3555 patchDesc = mAudioPatches.valueAt(index);
3556 afPatchHandle = patchDesc->mAfPatchHandle;
3557 }
3558
Eric Laurent1c333e22014-05-20 10:48:17 -07003559 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003560 &afPatchHandle,
3561 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003562 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3563 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003564 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003565 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003566 if (index < 0) {
3567 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3568 &patch, mUidCached);
3569 addAudioPatch(patchDesc->mHandle, patchDesc);
3570 } else {
3571 patchDesc->mPatch = patch;
3572 }
3573 patchDesc->mAfPatchHandle = afPatchHandle;
3574 patchDesc->mUid = mUidCached;
3575 if (patchHandle) {
3576 *patchHandle = patchDesc->mHandle;
3577 }
3578 outputDesc->mPatchHandle = patchDesc->mHandle;
3579 nextAudioPortGeneration();
Eric Laurent1c333e22014-05-20 10:48:17 -07003580 }
3581 }
3582 }
Eric Laurente552edb2014-03-10 17:42:56 -07003583
3584 // update stream volumes according to new device
3585 applyStreamVolumes(output, device, delayMs);
3586
3587 return muteWaitMs;
3588}
3589
Eric Laurent1c333e22014-05-20 10:48:17 -07003590status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003591 int delayMs,
3592 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003593{
3594 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003595 ssize_t index;
3596 if (patchHandle) {
3597 index = mAudioPatches.indexOfKey(*patchHandle);
3598 } else {
3599 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3600 }
3601 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003602 return INVALID_OPERATION;
3603 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003604 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3605 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003606 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3607 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003608 removeAudioPatch(patchDesc->mHandle);
3609 nextAudioPortGeneration();
Eric Laurent1c333e22014-05-20 10:48:17 -07003610 return status;
3611}
3612
3613status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3614 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003615 bool force,
3616 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003617{
3618 status_t status = NO_ERROR;
3619
3620 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
3621 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3622 inputDesc->mDevice = device;
3623
3624 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3625 if (!deviceList.isEmpty()) {
3626 struct audio_patch patch;
3627 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3628 patch.num_sinks = 1;
3629 //only one input device for now
3630 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003631 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003632 ssize_t index;
3633 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3634 index = mAudioPatches.indexOfKey(*patchHandle);
3635 } else {
3636 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3637 }
3638 sp< AudioPatch> patchDesc;
3639 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3640 if (index >= 0) {
3641 patchDesc = mAudioPatches.valueAt(index);
3642 afPatchHandle = patchDesc->mAfPatchHandle;
3643 }
3644
Eric Laurent1c333e22014-05-20 10:48:17 -07003645 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003646 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003647 0);
3648 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003649 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003650 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003651 if (index < 0) {
3652 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3653 &patch, mUidCached);
3654 addAudioPatch(patchDesc->mHandle, patchDesc);
3655 } else {
3656 patchDesc->mPatch = patch;
3657 }
3658 patchDesc->mAfPatchHandle = afPatchHandle;
3659 patchDesc->mUid = mUidCached;
3660 if (patchHandle) {
3661 *patchHandle = patchDesc->mHandle;
3662 }
3663 inputDesc->mPatchHandle = patchDesc->mHandle;
3664 nextAudioPortGeneration();
Eric Laurent1c333e22014-05-20 10:48:17 -07003665 }
3666 }
3667 }
3668 return status;
3669}
3670
Eric Laurent6a94d692014-05-20 11:18:06 -07003671status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3672 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003673{
3674 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003675 ssize_t index;
3676 if (patchHandle) {
3677 index = mAudioPatches.indexOfKey(*patchHandle);
3678 } else {
3679 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3680 }
3681 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003682 return INVALID_OPERATION;
3683 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003684 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3685 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003686 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3687 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003688 removeAudioPatch(patchDesc->mHandle);
3689 nextAudioPortGeneration();
Eric Laurent1c333e22014-05-20 10:48:17 -07003690 return status;
3691}
3692
3693sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003694 uint32_t samplingRate,
3695 audio_format_t format,
3696 audio_channel_mask_t channelMask)
3697{
3698 // Choose an input profile based on the requested capture parameters: select the first available
3699 // profile supporting all requested parameters.
3700
3701 for (size_t i = 0; i < mHwModules.size(); i++)
3702 {
3703 if (mHwModules[i]->mHandle == 0) {
3704 continue;
3705 }
3706 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3707 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003708 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003709 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003710 if (profile->isCompatibleProfile(device, samplingRate, format,
3711 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3712 return profile;
3713 }
3714 }
3715 }
3716 return NULL;
3717}
3718
Eric Laurente0720872014-03-11 09:30:41 -07003719audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003720{
3721 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003722 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3723 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003724 switch (inputSource) {
3725 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003726 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003727 device = AUDIO_DEVICE_IN_VOICE_CALL;
3728 break;
3729 }
3730 // FALL THROUGH
3731
3732 case AUDIO_SOURCE_DEFAULT:
3733 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003734 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3735 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3736 break;
3737 }
3738 // FALL THROUGH
3739
Eric Laurente552edb2014-03-10 17:42:56 -07003740 case AUDIO_SOURCE_VOICE_RECOGNITION:
3741 case AUDIO_SOURCE_HOTWORD:
3742 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003743 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003744 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003745 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003746 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003747 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003748 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3749 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003750 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003751 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3752 }
3753 break;
3754 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003755 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003756 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003757 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003758 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3759 }
3760 break;
3761 case AUDIO_SOURCE_VOICE_DOWNLINK:
3762 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003763 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003764 device = AUDIO_DEVICE_IN_VOICE_CALL;
3765 }
3766 break;
3767 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003768 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003769 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3770 }
3771 break;
3772 default:
3773 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3774 break;
3775 }
3776 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3777 return device;
3778}
3779
Eric Laurente0720872014-03-11 09:30:41 -07003780bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003781{
3782 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3783 device &= ~AUDIO_DEVICE_BIT_IN;
3784 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3785 return true;
3786 }
3787 return false;
3788}
3789
Eric Laurente0720872014-03-11 09:30:41 -07003790audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003791{
3792 for (size_t i = 0; i < mInputs.size(); i++) {
3793 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
3794 if ((input_descriptor->mRefCount > 0)
3795 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3796 return mInputs.keyAt(i);
3797 }
3798 }
3799 return 0;
3800}
3801
3802
Eric Laurente0720872014-03-11 09:30:41 -07003803audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003804{
3805 if (device == AUDIO_DEVICE_NONE) {
3806 // this happens when forcing a route update and no track is active on an output.
3807 // In this case the returned category is not important.
3808 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003809 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003810 // Multiple device selection is either:
3811 // - speaker + one other device: give priority to speaker in this case.
3812 // - one A2DP device + another device: happens with duplicated output. In this case
3813 // retain the device on the A2DP output as the other must not correspond to an active
3814 // selection if not the speaker.
3815 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3816 device = AUDIO_DEVICE_OUT_SPEAKER;
3817 } else {
3818 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3819 }
3820 }
3821
Eric Laurent3b73df72014-03-11 09:06:29 -07003822 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003823 "getDeviceForVolume() invalid device combination: %08x",
3824 device);
3825
3826 return device;
3827}
3828
Eric Laurente0720872014-03-11 09:30:41 -07003829AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003830{
3831 switch(getDeviceForVolume(device)) {
3832 case AUDIO_DEVICE_OUT_EARPIECE:
3833 return DEVICE_CATEGORY_EARPIECE;
3834 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3835 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3836 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3837 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3838 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3839 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3840 return DEVICE_CATEGORY_HEADSET;
3841 case AUDIO_DEVICE_OUT_SPEAKER:
3842 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3843 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3844 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3845 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3846 case AUDIO_DEVICE_OUT_USB_DEVICE:
3847 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3848 default:
3849 return DEVICE_CATEGORY_SPEAKER;
3850 }
3851}
3852
Eric Laurente0720872014-03-11 09:30:41 -07003853float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003854 int indexInUi)
3855{
3856 device_category deviceCategory = getDeviceCategory(device);
3857 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3858
3859 // the volume index in the UI is relative to the min and max volume indices for this stream type
3860 int nbSteps = 1 + curve[VOLMAX].mIndex -
3861 curve[VOLMIN].mIndex;
3862 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3863 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3864
3865 // find what part of the curve this index volume belongs to, or if it's out of bounds
3866 int segment = 0;
3867 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3868 return 0.0f;
3869 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3870 segment = 0;
3871 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3872 segment = 1;
3873 } else if (volIdx <= curve[VOLMAX].mIndex) {
3874 segment = 2;
3875 } else { // out of bounds
3876 return 1.0f;
3877 }
3878
3879 // linear interpolation in the attenuation table in dB
3880 float decibels = curve[segment].mDBAttenuation +
3881 ((float)(volIdx - curve[segment].mIndex)) *
3882 ( (curve[segment+1].mDBAttenuation -
3883 curve[segment].mDBAttenuation) /
3884 ((float)(curve[segment+1].mIndex -
3885 curve[segment].mIndex)) );
3886
3887 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3888
3889 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3890 curve[segment].mIndex, volIdx,
3891 curve[segment+1].mIndex,
3892 curve[segment].mDBAttenuation,
3893 decibels,
3894 curve[segment+1].mDBAttenuation,
3895 amplification);
3896
3897 return amplification;
3898}
3899
Eric Laurente0720872014-03-11 09:30:41 -07003900const AudioPolicyManager::VolumeCurvePoint
3901 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003902 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3903};
3904
Eric Laurente0720872014-03-11 09:30:41 -07003905const AudioPolicyManager::VolumeCurvePoint
3906 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003907 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3908};
3909
Eric Laurente0720872014-03-11 09:30:41 -07003910const AudioPolicyManager::VolumeCurvePoint
3911 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003912 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3913};
3914
Eric Laurente0720872014-03-11 09:30:41 -07003915const AudioPolicyManager::VolumeCurvePoint
3916 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003917 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3918};
3919
Eric Laurente0720872014-03-11 09:30:41 -07003920const AudioPolicyManager::VolumeCurvePoint
3921 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003922 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3923};
3924
3925// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3926// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3927// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3928// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3929
Eric Laurente0720872014-03-11 09:30:41 -07003930const AudioPolicyManager::VolumeCurvePoint
3931 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003932 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3933};
3934
Eric Laurente0720872014-03-11 09:30:41 -07003935const AudioPolicyManager::VolumeCurvePoint
3936 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003937 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3938};
3939
Eric Laurente0720872014-03-11 09:30:41 -07003940const AudioPolicyManager::VolumeCurvePoint
3941 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003942 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3943};
3944
Eric Laurente0720872014-03-11 09:30:41 -07003945const AudioPolicyManager::VolumeCurvePoint
3946 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003947 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3948};
3949
Eric Laurente0720872014-03-11 09:30:41 -07003950const AudioPolicyManager::VolumeCurvePoint
3951 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003952 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3953};
3954
Eric Laurente0720872014-03-11 09:30:41 -07003955const AudioPolicyManager::VolumeCurvePoint
3956 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
3957 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003958 { // AUDIO_STREAM_VOICE_CALL
3959 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3960 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3961 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3962 },
3963 { // AUDIO_STREAM_SYSTEM
3964 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3965 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3966 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3967 },
3968 { // AUDIO_STREAM_RING
3969 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3970 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3971 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3972 },
3973 { // AUDIO_STREAM_MUSIC
3974 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3975 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3976 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3977 },
3978 { // AUDIO_STREAM_ALARM
3979 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3980 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3981 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3982 },
3983 { // AUDIO_STREAM_NOTIFICATION
3984 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3985 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3986 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3987 },
3988 { // AUDIO_STREAM_BLUETOOTH_SCO
3989 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3990 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3991 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3992 },
3993 { // AUDIO_STREAM_ENFORCED_AUDIBLE
3994 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3995 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3996 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3997 },
3998 { // AUDIO_STREAM_DTMF
3999 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4000 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4001 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4002 },
4003 { // AUDIO_STREAM_TTS
4004 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4005 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4006 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4007 },
4008};
4009
Eric Laurente0720872014-03-11 09:30:41 -07004010void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004011{
4012 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4013 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4014 mStreams[i].mVolumeCurve[j] =
4015 sVolumeProfiles[i][j];
4016 }
4017 }
4018
4019 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4020 if (mSpeakerDrcEnabled) {
4021 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4022 sDefaultSystemVolumeCurveDrc;
4023 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4024 sSpeakerSonificationVolumeCurveDrc;
4025 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4026 sSpeakerSonificationVolumeCurveDrc;
4027 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4028 sSpeakerSonificationVolumeCurveDrc;
4029 }
4030}
4031
Eric Laurente0720872014-03-11 09:30:41 -07004032float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004033 int index,
4034 audio_io_handle_t output,
4035 audio_devices_t device)
4036{
4037 float volume = 1.0;
4038 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
4039 StreamDescriptor &streamDesc = mStreams[stream];
4040
4041 if (device == AUDIO_DEVICE_NONE) {
4042 device = outputDesc->device();
4043 }
4044
4045 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004046 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004047 index != mStreams[stream].mIndexMin &&
4048 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
4049 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
4050 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
4051 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
4052 return 1.0;
4053 }
4054
4055 volume = volIndexToAmpl(device, streamDesc, index);
4056
4057 // if a headset is connected, apply the following rules to ring tones and notifications
4058 // to avoid sound level bursts in user's ears:
4059 // - always attenuate ring tones and notifications volume by 6dB
4060 // - if music is playing, always limit the volume to current music volume,
4061 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004062 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004063 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4064 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4065 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4066 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4067 ((stream_strategy == STRATEGY_SONIFICATION)
4068 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004069 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004070 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004071 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004072 streamDesc.mCanBeMuted) {
4073 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4074 // when the phone is ringing we must consider that music could have been paused just before
4075 // by the music application and behave as if music was active if the last music track was
4076 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004077 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004078 mLimitRingtoneVolume) {
4079 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004080 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4081 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004082 output,
4083 musicDevice);
4084 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4085 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4086 if (volume > minVol) {
4087 volume = minVol;
4088 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4089 }
4090 }
4091 }
4092
4093 return volume;
4094}
4095
Eric Laurente0720872014-03-11 09:30:41 -07004096status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004097 int index,
4098 audio_io_handle_t output,
4099 audio_devices_t device,
4100 int delayMs,
4101 bool force)
4102{
4103
4104 // do not change actual stream volume if the stream is muted
4105 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4106 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4107 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4108 return NO_ERROR;
4109 }
4110
4111 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004112 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4113 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4114 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4115 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004116 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004117 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004118 return INVALID_OPERATION;
4119 }
4120
4121 float volume = computeVolume(stream, index, output, device);
4122 // We actually change the volume if:
4123 // - the float value returned by computeVolume() changed
4124 // - the force flag is set
4125 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4126 force) {
4127 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4128 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4129 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4130 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004131 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4132 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004133 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004134 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004135 }
4136
Eric Laurent3b73df72014-03-11 09:06:29 -07004137 if (stream == AUDIO_STREAM_VOICE_CALL ||
4138 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004139 float voiceVolume;
4140 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004141 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004142 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4143 } else {
4144 voiceVolume = 1.0;
4145 }
4146
4147 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4148 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4149 mLastVoiceVolume = voiceVolume;
4150 }
4151 }
4152
4153 return NO_ERROR;
4154}
4155
Eric Laurente0720872014-03-11 09:30:41 -07004156void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004157 audio_devices_t device,
4158 int delayMs,
4159 bool force)
4160{
4161 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4162
Eric Laurent3b73df72014-03-11 09:06:29 -07004163 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4164 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004165 mStreams[stream].getVolumeIndex(device),
4166 output,
4167 device,
4168 delayMs,
4169 force);
4170 }
4171}
4172
Eric Laurente0720872014-03-11 09:30:41 -07004173void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004174 bool on,
4175 audio_io_handle_t output,
4176 int delayMs,
4177 audio_devices_t device)
4178{
4179 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004180 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4181 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4182 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004183 }
4184 }
4185}
4186
Eric Laurente0720872014-03-11 09:30:41 -07004187void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004188 bool on,
4189 audio_io_handle_t output,
4190 int delayMs,
4191 audio_devices_t device)
4192{
4193 StreamDescriptor &streamDesc = mStreams[stream];
4194 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
4195 if (device == AUDIO_DEVICE_NONE) {
4196 device = outputDesc->device();
4197 }
4198
4199 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4200 stream, on, output, outputDesc->mMuteCount[stream], device);
4201
4202 if (on) {
4203 if (outputDesc->mMuteCount[stream] == 0) {
4204 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004205 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4206 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004207 checkAndSetVolume(stream, 0, output, device, delayMs);
4208 }
4209 }
4210 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4211 outputDesc->mMuteCount[stream]++;
4212 } else {
4213 if (outputDesc->mMuteCount[stream] == 0) {
4214 ALOGV("setStreamMute() unmuting non muted stream!");
4215 return;
4216 }
4217 if (--outputDesc->mMuteCount[stream] == 0) {
4218 checkAndSetVolume(stream,
4219 streamDesc.getVolumeIndex(device),
4220 output,
4221 device,
4222 delayMs);
4223 }
4224 }
4225}
4226
Eric Laurente0720872014-03-11 09:30:41 -07004227void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004228 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004229{
4230 // if the stream pertains to sonification strategy and we are in call we must
4231 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4232 // in the device used for phone strategy and play the tone if the selected device does not
4233 // interfere with the device used for phone strategy
4234 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4235 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004236 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004237 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4238 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
4239 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
4240 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4241 stream, starting, outputDesc->mDevice, stateChange);
4242 if (outputDesc->mRefCount[stream]) {
4243 int muteCount = 1;
4244 if (stateChange) {
4245 muteCount = outputDesc->mRefCount[stream];
4246 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004247 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004248 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4249 for (int i = 0; i < muteCount; i++) {
4250 setStreamMute(stream, starting, mPrimaryOutput);
4251 }
4252 } else {
4253 ALOGV("handleIncallSonification() high visibility");
4254 if (outputDesc->device() &
4255 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4256 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4257 for (int i = 0; i < muteCount; i++) {
4258 setStreamMute(stream, starting, mPrimaryOutput);
4259 }
4260 }
4261 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004262 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4263 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004264 } else {
4265 mpClientInterface->stopTone();
4266 }
4267 }
4268 }
4269 }
4270}
4271
Eric Laurente0720872014-03-11 09:30:41 -07004272bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004273{
4274 return isStateInCall(mPhoneState);
4275}
4276
Eric Laurente0720872014-03-11 09:30:41 -07004277bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004278 return ((state == AUDIO_MODE_IN_CALL) ||
4279 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004280}
4281
Eric Laurente0720872014-03-11 09:30:41 -07004282uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004283{
4284 return MAX_EFFECTS_CPU_LOAD;
4285}
4286
Eric Laurente0720872014-03-11 09:30:41 -07004287uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004288{
4289 return MAX_EFFECTS_MEMORY;
4290}
4291
Eric Laurent6a94d692014-05-20 11:18:06 -07004292
Eric Laurente552edb2014-03-10 17:42:56 -07004293// --- AudioOutputDescriptor class implementation
4294
Eric Laurente0720872014-03-11 09:30:41 -07004295AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004296 const sp<IOProfile>& profile)
4297 : mId(0), mIoHandle(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
Eric Laurente552edb2014-03-10 17:42:56 -07004298 mChannelMask(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004299 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004300 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4301{
4302 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004303 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004304 mRefCount[i] = 0;
4305 mCurVolume[i] = -1.0;
4306 mMuteCount[i] = 0;
4307 mStopTime[i] = 0;
4308 }
4309 for (int i = 0; i < NUM_STRATEGIES; i++) {
4310 mStrategyMutedByDevice[i] = false;
4311 }
4312 if (profile != NULL) {
4313 mSamplingRate = profile->mSamplingRates[0];
4314 mFormat = profile->mFormats[0];
4315 mChannelMask = profile->mChannelMasks[0];
4316 mFlags = profile->mFlags;
4317 }
4318}
4319
Eric Laurente0720872014-03-11 09:30:41 -07004320audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004321{
4322 if (isDuplicated()) {
4323 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4324 } else {
4325 return mDevice;
4326 }
4327}
4328
Eric Laurente0720872014-03-11 09:30:41 -07004329uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004330{
4331 if (isDuplicated()) {
4332 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4333 } else {
4334 return mLatency;
4335 }
4336}
4337
Eric Laurente0720872014-03-11 09:30:41 -07004338bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurente552edb2014-03-10 17:42:56 -07004339 const AudioOutputDescriptor *outputDesc)
4340{
4341 if (isDuplicated()) {
4342 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4343 } else if (outputDesc->isDuplicated()){
4344 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4345 } else {
4346 return (mProfile->mModule == outputDesc->mProfile->mModule);
4347 }
4348}
4349
Eric Laurente0720872014-03-11 09:30:41 -07004350void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004351 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004352{
4353 // forward usage count change to attached outputs
4354 if (isDuplicated()) {
4355 mOutput1->changeRefCount(stream, delta);
4356 mOutput2->changeRefCount(stream, delta);
4357 }
4358 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004359 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4360 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004361 mRefCount[stream] = 0;
4362 return;
4363 }
4364 mRefCount[stream] += delta;
4365 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4366}
4367
Eric Laurente0720872014-03-11 09:30:41 -07004368audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004369{
4370 if (isDuplicated()) {
4371 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4372 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004373 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004374 }
4375}
4376
Eric Laurente0720872014-03-11 09:30:41 -07004377bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004378{
4379 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4380}
4381
Eric Laurente0720872014-03-11 09:30:41 -07004382bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004383 uint32_t inPastMs,
4384 nsecs_t sysTime) const
4385{
4386 if ((sysTime == 0) && (inPastMs != 0)) {
4387 sysTime = systemTime();
4388 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004389 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4390 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004391 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004392 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004393 return true;
4394 }
4395 }
4396 return false;
4397}
4398
Eric Laurente0720872014-03-11 09:30:41 -07004399bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004400 uint32_t inPastMs,
4401 nsecs_t sysTime) const
4402{
4403 if (mRefCount[stream] != 0) {
4404 return true;
4405 }
4406 if (inPastMs == 0) {
4407 return false;
4408 }
4409 if (sysTime == 0) {
4410 sysTime = systemTime();
4411 }
4412 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4413 return true;
4414 }
4415 return false;
4416}
4417
Eric Laurent1c333e22014-05-20 10:48:17 -07004418void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004419 struct audio_port_config *dstConfig,
4420 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004421{
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 dstConfig->id = mId;
4423 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4424 dstConfig->type = AUDIO_PORT_TYPE_MIX;
4425 dstConfig->sample_rate = mSamplingRate;
4426 dstConfig->channel_mask = mChannelMask;
4427 dstConfig->format = mFormat;
4428 dstConfig->gain.index = -1;
4429 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
Eric Laurent1c333e22014-05-20 10:48:17 -07004430 AUDIO_PORT_CONFIG_FORMAT;
Eric Laurent6a94d692014-05-20 11:18:06 -07004431 // use supplied variable configuration parameters if any
4432 if (srcConfig != NULL) {
4433 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
4434 dstConfig->sample_rate = srcConfig->sample_rate;
4435 }
4436 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
4437 dstConfig->channel_mask = srcConfig->channel_mask;
4438 }
4439 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
4440 dstConfig->format = srcConfig->format;
4441 }
4442 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
4443 dstConfig->gain = srcConfig->gain;
4444 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
4445 }
4446 }
4447 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4448 dstConfig->ext.mix.handle = mIoHandle;
4449 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004450}
4451
4452void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4453 struct audio_port *port) const
4454{
4455 mProfile->toAudioPort(port);
4456 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 toAudioPortConfig(&port->active_config);
4458 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004459 port->ext.mix.handle = mIoHandle;
4460 port->ext.mix.latency_class =
4461 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4462}
Eric Laurente552edb2014-03-10 17:42:56 -07004463
Eric Laurente0720872014-03-11 09:30:41 -07004464status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004465{
4466 const size_t SIZE = 256;
4467 char buffer[SIZE];
4468 String8 result;
4469
4470 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4471 result.append(buffer);
4472 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4473 result.append(buffer);
4474 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4475 result.append(buffer);
4476 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4477 result.append(buffer);
4478 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4479 result.append(buffer);
4480 snprintf(buffer, SIZE, " Devices %08x\n", device());
4481 result.append(buffer);
4482 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4483 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004484 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4485 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4486 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004487 result.append(buffer);
4488 }
4489 write(fd, result.string(), result.size());
4490
4491 return NO_ERROR;
4492}
4493
4494// --- AudioInputDescriptor class implementation
4495
Eric Laurent1c333e22014-05-20 10:48:17 -07004496AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
4497 : mId(0), mIoHandle(0), mSamplingRate(0),
4498 mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
4499 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004500 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004501{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004502 if (profile != NULL) {
4503 mSamplingRate = profile->mSamplingRates[0];
4504 mFormat = profile->mFormats[0];
4505 mChannelMask = profile->mChannelMasks[0];
4506 }
Eric Laurente552edb2014-03-10 17:42:56 -07004507}
4508
Eric Laurent1c333e22014-05-20 10:48:17 -07004509void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004510 struct audio_port_config *dstConfig,
4511 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004512{
Eric Laurent6a94d692014-05-20 11:18:06 -07004513 dstConfig->id = mId;
4514 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4515 dstConfig->type = AUDIO_PORT_TYPE_MIX;
4516 dstConfig->sample_rate = mSamplingRate;
4517 dstConfig->channel_mask = mChannelMask;
4518 dstConfig->format = mFormat;
4519 dstConfig->gain.index = -1;
4520 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4521 AUDIO_PORT_CONFIG_FORMAT;
4522 // use supplied variable configuration parameters if any
4523 if (srcConfig != NULL) {
4524 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
4525 dstConfig->sample_rate = srcConfig->sample_rate;
4526 }
4527 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
4528 dstConfig->channel_mask = srcConfig->channel_mask;
4529 }
4530 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
4531 dstConfig->format = srcConfig->format;
4532 }
4533 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
4534 dstConfig->gain = srcConfig->gain;
4535 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
4536 }
4537 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004538}
4539
4540void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4541 struct audio_port *port) const
4542{
4543 mProfile->toAudioPort(port);
4544 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004545 toAudioPortConfig(&port->active_config);
4546 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004547 port->ext.mix.handle = mIoHandle;
4548 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4549}
4550
Eric Laurente0720872014-03-11 09:30:41 -07004551status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004552{
4553 const size_t SIZE = 256;
4554 char buffer[SIZE];
4555 String8 result;
4556
4557 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4558 result.append(buffer);
4559 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4560 result.append(buffer);
4561 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4562 result.append(buffer);
4563 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4564 result.append(buffer);
4565 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4566 result.append(buffer);
4567 write(fd, result.string(), result.size());
4568
4569 return NO_ERROR;
4570}
4571
4572// --- StreamDescriptor class implementation
4573
Eric Laurente0720872014-03-11 09:30:41 -07004574AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004575 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4576{
4577 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4578}
4579
Eric Laurente0720872014-03-11 09:30:41 -07004580int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004581{
Eric Laurente0720872014-03-11 09:30:41 -07004582 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004583 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4584 if (mIndexCur.indexOfKey(device) < 0) {
4585 device = AUDIO_DEVICE_OUT_DEFAULT;
4586 }
4587 return mIndexCur.valueFor(device);
4588}
4589
Eric Laurente0720872014-03-11 09:30:41 -07004590void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004591{
4592 const size_t SIZE = 256;
4593 char buffer[SIZE];
4594 String8 result;
4595
4596 snprintf(buffer, SIZE, "%s %02d %02d ",
4597 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4598 result.append(buffer);
4599 for (size_t i = 0; i < mIndexCur.size(); i++) {
4600 snprintf(buffer, SIZE, "%04x : %02d, ",
4601 mIndexCur.keyAt(i),
4602 mIndexCur.valueAt(i));
4603 result.append(buffer);
4604 }
4605 result.append("\n");
4606
4607 write(fd, result.string(), result.size());
4608}
4609
4610// --- EffectDescriptor class implementation
4611
Eric Laurente0720872014-03-11 09:30:41 -07004612status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004613{
4614 const size_t SIZE = 256;
4615 char buffer[SIZE];
4616 String8 result;
4617
4618 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4619 result.append(buffer);
4620 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4621 result.append(buffer);
4622 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4623 result.append(buffer);
4624 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4625 result.append(buffer);
4626 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4627 result.append(buffer);
4628 write(fd, result.string(), result.size());
4629
4630 return NO_ERROR;
4631}
4632
Eric Laurent1c333e22014-05-20 10:48:17 -07004633// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004634
Eric Laurente0720872014-03-11 09:30:41 -07004635AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07004636 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
4637{
4638}
4639
Eric Laurente0720872014-03-11 09:30:41 -07004640AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004641{
4642 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004643 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004644 }
4645 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004646 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004647 }
4648 free((void *)mName);
4649}
4650
Eric Laurente0720872014-03-11 09:30:41 -07004651void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004652{
4653 const size_t SIZE = 256;
4654 char buffer[SIZE];
4655 String8 result;
4656
4657 snprintf(buffer, SIZE, " - name: %s\n", mName);
4658 result.append(buffer);
4659 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4660 result.append(buffer);
4661 write(fd, result.string(), result.size());
4662 if (mOutputProfiles.size()) {
4663 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4664 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004665 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004666 write(fd, buffer, strlen(buffer));
4667 mOutputProfiles[i]->dump(fd);
4668 }
4669 }
4670 if (mInputProfiles.size()) {
4671 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4672 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004673 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004674 write(fd, buffer, strlen(buffer));
4675 mInputProfiles[i]->dump(fd);
4676 }
4677 }
4678}
4679
Eric Laurent1c333e22014-05-20 10:48:17 -07004680// --- AudioPort class implementation
4681
4682void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
4683{
4684 port->role = mRole;
4685 port->type = mType;
4686 unsigned int i;
4687 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
4688 port->sample_rates[i] = mSamplingRates[i];
4689 }
4690 port->num_sample_rates = i;
4691 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
4692 port->channel_masks[i] = mChannelMasks[i];
4693 }
4694 port->num_channel_masks = i;
4695 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
4696 port->formats[i] = mFormats[i];
4697 }
4698 port->num_formats = i;
4699 port->num_gains = 0;
4700}
4701
4702
4703void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
4704{
4705 char *str = strtok(name, "|");
4706
4707 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4708 // rates should be read from the output stream after it is opened for the first time
4709 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4710 mSamplingRates.add(0);
4711 return;
4712 }
4713
4714 while (str != NULL) {
4715 uint32_t rate = atoi(str);
4716 if (rate != 0) {
4717 ALOGV("loadSamplingRates() adding rate %d", rate);
4718 mSamplingRates.add(rate);
4719 }
4720 str = strtok(NULL, "|");
4721 }
4722 return;
4723}
4724
4725void AudioPolicyManager::AudioPort::loadFormats(char *name)
4726{
4727 char *str = strtok(name, "|");
4728
4729 // by convention, "0' in the first entry in mFormats indicates the supported formats
4730 // should be read from the output stream after it is opened for the first time
4731 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4732 mFormats.add(AUDIO_FORMAT_DEFAULT);
4733 return;
4734 }
4735
4736 while (str != NULL) {
4737 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4738 ARRAY_SIZE(sFormatNameToEnumTable),
4739 str);
4740 if (format != AUDIO_FORMAT_DEFAULT) {
4741 mFormats.add(format);
4742 }
4743 str = strtok(NULL, "|");
4744 }
4745 return;
4746}
4747
4748void AudioPolicyManager::AudioPort::loadInChannels(char *name)
4749{
4750 const char *str = strtok(name, "|");
4751
4752 ALOGV("loadInChannels() %s", name);
4753
4754 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4755 mChannelMasks.add(0);
4756 return;
4757 }
4758
4759 while (str != NULL) {
4760 audio_channel_mask_t channelMask =
4761 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4762 ARRAY_SIZE(sInChannelsNameToEnumTable),
4763 str);
4764 if (channelMask != 0) {
4765 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4766 mChannelMasks.add(channelMask);
4767 }
4768 str = strtok(NULL, "|");
4769 }
4770 return;
4771}
4772
4773void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
4774{
4775 const char *str = strtok(name, "|");
4776
4777 ALOGV("loadOutChannels() %s", name);
4778
4779 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4780 // masks should be read from the output stream after it is opened for the first time
4781 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4782 mChannelMasks.add(0);
4783 return;
4784 }
4785
4786 while (str != NULL) {
4787 audio_channel_mask_t channelMask =
4788 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4789 ARRAY_SIZE(sOutChannelsNameToEnumTable),
4790 str);
4791 if (channelMask != 0) {
4792 mChannelMasks.add(channelMask);
4793 }
4794 str = strtok(NULL, "|");
4795 }
4796 return;
4797}
4798
4799// --- IOProfile class implementation
4800
4801AudioPolicyManager::IOProfile::IOProfile(audio_port_role_t role, HwModule *module)
4802 : AudioPort(AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07004803{
4804}
4805
Eric Laurente0720872014-03-11 09:30:41 -07004806AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07004807{
4808}
4809
4810// checks if the IO profile is compatible with specified parameters.
4811// Sampling rate, format and channel mask must be specified in order to
4812// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07004813bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07004814 uint32_t samplingRate,
4815 audio_format_t format,
4816 audio_channel_mask_t channelMask,
4817 audio_output_flags_t flags) const
4818{
4819 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
4820 return false;
4821 }
4822
Eric Laurent3a4311c2014-03-17 12:00:47 -07004823 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07004824 return false;
4825 }
4826 if ((mFlags & flags) != flags) {
4827 return false;
4828 }
4829 size_t i;
4830 for (i = 0; i < mSamplingRates.size(); i++)
4831 {
4832 if (mSamplingRates[i] == samplingRate) {
4833 break;
4834 }
4835 }
4836 if (i == mSamplingRates.size()) {
4837 return false;
4838 }
4839 for (i = 0; i < mFormats.size(); i++)
4840 {
4841 if (mFormats[i] == format) {
4842 break;
4843 }
4844 }
4845 if (i == mFormats.size()) {
4846 return false;
4847 }
4848 for (i = 0; i < mChannelMasks.size(); i++)
4849 {
4850 if (mChannelMasks[i] == channelMask) {
4851 break;
4852 }
4853 }
4854 if (i == mChannelMasks.size()) {
4855 return false;
4856 }
4857 return true;
4858}
4859
Eric Laurente0720872014-03-11 09:30:41 -07004860void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004861{
4862 const size_t SIZE = 256;
4863 char buffer[SIZE];
4864 String8 result;
4865
4866 snprintf(buffer, SIZE, " - sampling rates: ");
4867 result.append(buffer);
4868 for (size_t i = 0; i < mSamplingRates.size(); i++) {
4869 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
4870 result.append(buffer);
4871 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
4872 }
4873
4874 snprintf(buffer, SIZE, " - channel masks: ");
4875 result.append(buffer);
4876 for (size_t i = 0; i < mChannelMasks.size(); i++) {
4877 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
4878 result.append(buffer);
4879 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
4880 }
4881
4882 snprintf(buffer, SIZE, " - formats: ");
4883 result.append(buffer);
4884 for (size_t i = 0; i < mFormats.size(); i++) {
4885 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
4886 result.append(buffer);
4887 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
4888 }
4889
Eric Laurent3a4311c2014-03-17 12:00:47 -07004890 snprintf(buffer, SIZE, " - devices:\n");
Eric Laurente552edb2014-03-10 17:42:56 -07004891 result.append(buffer);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004892 write(fd, result.string(), result.size());
4893 DeviceDescriptor::dumpHeader(fd, 6);
4894 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
4895 mSupportedDevices[i]->dump(fd, 6);
4896 }
4897
Eric Laurente552edb2014-03-10 17:42:56 -07004898 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
4899 result.append(buffer);
4900
4901 write(fd, result.string(), result.size());
4902}
4903
Eric Laurentd4692962014-05-05 18:13:44 -07004904void AudioPolicyManager::IOProfile::log()
4905{
4906 const size_t SIZE = 256;
4907 char buffer[SIZE];
4908 String8 result;
4909
4910 ALOGV(" - sampling rates: ");
4911 for (size_t i = 0; i < mSamplingRates.size(); i++) {
4912 ALOGV(" %d", mSamplingRates[i]);
4913 }
4914
4915 ALOGV(" - channel masks: ");
4916 for (size_t i = 0; i < mChannelMasks.size(); i++) {
4917 ALOGV(" 0x%04x", mChannelMasks[i]);
4918 }
4919
4920 ALOGV(" - formats: ");
4921 for (size_t i = 0; i < mFormats.size(); i++) {
4922 ALOGV(" 0x%08x", mFormats[i]);
4923 }
4924
4925 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
4926 ALOGV(" - flags: 0x%04x\n", mFlags);
4927}
4928
4929
Eric Laurent3a4311c2014-03-17 12:00:47 -07004930// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004931
Eric Laurent3a4311c2014-03-17 12:00:47 -07004932bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07004933{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004934 // Devices are considered equal if they:
4935 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
4936 // - have the same address or one device does not specify the address
4937 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004939 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07004940 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07004941 mChannelMask == other->mChannelMask);
4942}
4943
4944void AudioPolicyManager::DeviceVector::refreshTypes()
4945{
Eric Laurent1c333e22014-05-20 10:48:17 -07004946 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004947 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004948 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004949 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004950 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004951}
4952
4953ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
4954{
4955 for(size_t i = 0; i < size(); i++) {
4956 if (item->equals(itemAt(i))) {
4957 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07004958 }
4959 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004960 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07004961}
4962
Eric Laurent3a4311c2014-03-17 12:00:47 -07004963ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07004964{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004965 ssize_t ret = indexOf(item);
4966
4967 if (ret < 0) {
4968 ret = SortedVector::add(item);
4969 if (ret >= 0) {
4970 refreshTypes();
4971 }
4972 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07004973 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004974 ret = -1;
4975 }
4976 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07004977}
4978
Eric Laurent3a4311c2014-03-17 12:00:47 -07004979ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
4980{
4981 size_t i;
4982 ssize_t ret = indexOf(item);
4983
4984 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004986 } else {
4987 ret = SortedVector::removeAt(ret);
4988 if (ret >= 0) {
4989 refreshTypes();
4990 }
4991 }
4992 return ret;
4993}
4994
4995void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
4996{
4997 DeviceVector deviceList;
4998
4999 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5000 types &= ~role_bit;
5001
5002 while (types) {
5003 uint32_t i = 31 - __builtin_clz(types);
5004 uint32_t type = 1 << i;
5005 types &= ~type;
5006 add(new DeviceDescriptor(type | role_bit));
5007 }
5008}
5009
Eric Laurent1c333e22014-05-20 10:48:17 -07005010sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5011 audio_devices_t type, String8 address) const
5012{
5013 sp<DeviceDescriptor> device;
5014 for (size_t i = 0; i < size(); i++) {
5015 if (itemAt(i)->mDeviceType == type) {
5016 device = itemAt(i);
5017 if (itemAt(i)->mAddress = address) {
5018 break;
5019 }
5020 }
5021 }
5022 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5023 type, address.string(), device.get());
5024 return device;
5025}
5026
Eric Laurent6a94d692014-05-20 11:18:06 -07005027sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5028 audio_port_handle_t id) const
5029{
5030 sp<DeviceDescriptor> device;
5031 for (size_t i = 0; i < size(); i++) {
5032 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%d)->mId %d", id, i, itemAt(i)->mId);
5033 if (itemAt(i)->mId == id) {
5034 device = itemAt(i);
5035 break;
5036 }
5037 }
5038 return device;
5039}
5040
Eric Laurent1c333e22014-05-20 10:48:17 -07005041AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5042 audio_devices_t type) const
5043{
5044 DeviceVector devices;
5045 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5046 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5047 devices.add(itemAt(i));
5048 type &= ~itemAt(i)->mDeviceType;
5049 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5050 itemAt(i)->mDeviceType, itemAt(i).get());
5051 }
5052 }
5053 return devices;
5054}
5055
Eric Laurent6a94d692014-05-20 11:18:06 -07005056void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5057 struct audio_port_config *dstConfig,
5058 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005059{
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 dstConfig->id = mId;
5061 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005062 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005063 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
5064 dstConfig->channel_mask = mChannelMask;
5065 dstConfig->gain.index = -1;
5066 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK;
5067 // use supplied variable configuration parameters if any
5068 if (srcConfig != NULL) {
5069 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5070 dstConfig->channel_mask = srcConfig->channel_mask;
5071 }
5072 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5073 dstConfig->gain = srcConfig->gain;
5074 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5075 }
5076 }
5077 dstConfig->ext.device.type = mDeviceType;
5078 dstConfig->ext.device.hw_module = mModule->mHandle;
5079 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005080}
5081
5082void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5083{
5084 AudioPort::toAudioPort(port);
5085 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005087 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005088 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005089 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5090}
5091
Eric Laurent3a4311c2014-03-17 12:00:47 -07005092void AudioPolicyManager::DeviceDescriptor::dumpHeader(int fd, int spaces)
5093{
5094 const size_t SIZE = 256;
5095 char buffer[SIZE];
5096
5097 snprintf(buffer, SIZE, "%*s%-48s %-2s %-8s %-32s \n",
5098 spaces, "", "Type", "ID", "Cnl Mask", "Address");
5099 write(fd, buffer, strlen(buffer));
5100}
5101
5102status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces) const
5103{
5104 const size_t SIZE = 256;
5105 char buffer[SIZE];
5106
5107 snprintf(buffer, SIZE, "%*s%-48s %2d %08x %-32s \n",
5108 spaces, "",
5109 enumToString(sDeviceNameToEnumTable,
5110 ARRAY_SIZE(sDeviceNameToEnumTable),
Eric Laurent1c333e22014-05-20 10:48:17 -07005111 mDeviceType),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005112 mId, mChannelMask, mAddress.string());
5113 write(fd, buffer, strlen(buffer));
5114
5115 return NO_ERROR;
5116}
5117
5118
5119// --- audio_policy.conf file parsing
5120
Eric Laurente0720872014-03-11 09:30:41 -07005121audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005122{
5123 uint32_t flag = 0;
5124
5125 // it is OK to cast name to non const here as we are not going to use it after
5126 // strtok() modifies it
5127 char *flagName = strtok(name, "|");
5128 while (flagName != NULL) {
5129 if (strlen(flagName) != 0) {
5130 flag |= stringToEnum(sFlagNameToEnumTable,
5131 ARRAY_SIZE(sFlagNameToEnumTable),
5132 flagName);
5133 }
5134 flagName = strtok(NULL, "|");
5135 }
5136 //force direct flag if offload flag is set: offloading implies a direct output stream
5137 // and all common behaviors are driven by checking only the direct flag
5138 // this should normally be set appropriately in the policy configuration file
5139 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5140 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5141 }
5142
5143 return (audio_output_flags_t)flag;
5144}
5145
Eric Laurente0720872014-03-11 09:30:41 -07005146audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005147{
5148 uint32_t device = 0;
5149
5150 char *devName = strtok(name, "|");
5151 while (devName != NULL) {
5152 if (strlen(devName) != 0) {
5153 device |= stringToEnum(sDeviceNameToEnumTable,
5154 ARRAY_SIZE(sDeviceNameToEnumTable),
5155 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005156 }
Eric Laurente552edb2014-03-10 17:42:56 -07005157 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005158 }
Eric Laurente552edb2014-03-10 17:42:56 -07005159 return device;
5160}
5161
Eric Laurente0720872014-03-11 09:30:41 -07005162status_t AudioPolicyManager::loadInput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07005163{
5164 cnode *node = root->first_child;
5165
Eric Laurent1c333e22014-05-20 10:48:17 -07005166 sp<IOProfile> profile = new IOProfile(AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005167
5168 while (node) {
5169 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005170 profile->loadSamplingRates((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005171 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005172 profile->loadFormats((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005173 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005174 profile->loadInChannels((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005175 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005176 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07005177 }
5178 node = node->next;
5179 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005180 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07005181 "loadInput() invalid supported devices");
5182 ALOGW_IF(profile->mChannelMasks.size() == 0,
5183 "loadInput() invalid supported channel masks");
5184 ALOGW_IF(profile->mSamplingRates.size() == 0,
5185 "loadInput() invalid supported sampling rates");
5186 ALOGW_IF(profile->mFormats.size() == 0,
5187 "loadInput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005188 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07005189 (profile->mChannelMasks.size() != 0) &&
5190 (profile->mSamplingRates.size() != 0) &&
5191 (profile->mFormats.size() != 0)) {
5192
Eric Laurent3a4311c2014-03-17 12:00:47 -07005193 ALOGV("loadInput() adding input Supported Devices %04x",
5194 profile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005195
5196 module->mInputProfiles.add(profile);
5197 return NO_ERROR;
5198 } else {
Eric Laurente552edb2014-03-10 17:42:56 -07005199 return BAD_VALUE;
5200 }
5201}
5202
Eric Laurente0720872014-03-11 09:30:41 -07005203status_t AudioPolicyManager::loadOutput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07005204{
5205 cnode *node = root->first_child;
5206
Eric Laurent1c333e22014-05-20 10:48:17 -07005207 sp<IOProfile> profile = new IOProfile(AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005208
5209 while (node) {
5210 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005211 profile->loadSamplingRates((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005212 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005213 profile->loadFormats((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005214 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005215 profile->loadOutChannels((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005216 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005217 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07005218 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5219 profile->mFlags = parseFlagNames((char *)node->value);
5220 }
5221 node = node->next;
5222 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005223 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07005224 "loadOutput() invalid supported devices");
5225 ALOGW_IF(profile->mChannelMasks.size() == 0,
5226 "loadOutput() invalid supported channel masks");
5227 ALOGW_IF(profile->mSamplingRates.size() == 0,
5228 "loadOutput() invalid supported sampling rates");
5229 ALOGW_IF(profile->mFormats.size() == 0,
5230 "loadOutput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005231 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07005232 (profile->mChannelMasks.size() != 0) &&
5233 (profile->mSamplingRates.size() != 0) &&
5234 (profile->mFormats.size() != 0)) {
5235
Eric Laurent3a4311c2014-03-17 12:00:47 -07005236 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5237 profile->mSupportedDevices.types(), profile->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07005238
5239 module->mOutputProfiles.add(profile);
5240 return NO_ERROR;
5241 } else {
Eric Laurente552edb2014-03-10 17:42:56 -07005242 return BAD_VALUE;
5243 }
5244}
5245
Eric Laurente0720872014-03-11 09:30:41 -07005246void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005247{
5248 cnode *node = config_find(root, OUTPUTS_TAG);
5249 status_t status = NAME_NOT_FOUND;
5250
5251 HwModule *module = new HwModule(root->name);
5252
5253 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005254 node = node->first_child;
5255 while (node) {
5256 ALOGV("loadHwModule() loading output %s", node->name);
5257 status_t tmpStatus = loadOutput(node, module);
5258 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5259 status = tmpStatus;
5260 }
5261 node = node->next;
5262 }
5263 }
5264 node = config_find(root, INPUTS_TAG);
5265 if (node != NULL) {
5266 node = node->first_child;
5267 while (node) {
5268 ALOGV("loadHwModule() loading input %s", node->name);
5269 status_t tmpStatus = loadInput(node, module);
5270 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5271 status = tmpStatus;
5272 }
5273 node = node->next;
5274 }
5275 }
5276 if (status == NO_ERROR) {
5277 mHwModules.add(module);
5278 } else {
5279 delete module;
5280 }
5281}
5282
Eric Laurente0720872014-03-11 09:30:41 -07005283void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005284{
5285 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5286 if (node == NULL) {
5287 return;
5288 }
5289
5290 node = node->first_child;
5291 while (node) {
5292 ALOGV("loadHwModules() loading module %s", node->name);
5293 loadHwModule(node);
5294 node = node->next;
5295 }
5296}
5297
Eric Laurente0720872014-03-11 09:30:41 -07005298void AudioPolicyManager::loadGlobalConfig(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005299{
5300 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
5301 if (node == NULL) {
5302 return;
5303 }
5304 node = node->first_child;
5305 while (node) {
5306 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005307 mAvailableOutputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
5308 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5309 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005310 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005311 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005312 ARRAY_SIZE(sDeviceNameToEnumTable),
5313 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005314 if (device != AUDIO_DEVICE_NONE) {
5315 mDefaultOutputDevice = new DeviceDescriptor(device);
5316 } else {
5317 ALOGW("loadGlobalConfig() default device not specified");
5318 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005319 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005320 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005321 mAvailableInputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
5322 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005323 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5324 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5325 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
5326 }
5327 node = node->next;
5328 }
5329}
5330
Eric Laurente0720872014-03-11 09:30:41 -07005331status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005332{
5333 cnode *root;
5334 char *data;
5335
5336 data = (char *)load_file(path, NULL);
5337 if (data == NULL) {
5338 return -ENODEV;
5339 }
5340 root = config_node("", "");
5341 config_load(root, data);
5342
5343 loadGlobalConfig(root);
5344 loadHwModules(root);
5345
5346 config_free(root);
5347 free(root);
5348 free(data);
5349
5350 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5351
5352 return NO_ERROR;
5353}
5354
Eric Laurente0720872014-03-11 09:30:41 -07005355void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07005356{
5357 HwModule *module;
Eric Laurent1c333e22014-05-20 10:48:17 -07005358 sp<IOProfile> profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005359 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUILTIN_MIC);
5360 mAvailableOutputDevices.add(mDefaultOutputDevice);
5361 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005362
5363 module = new HwModule("primary");
5364
Eric Laurent1c333e22014-05-20 10:48:17 -07005365 profile = new IOProfile(AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005366 profile->mSamplingRates.add(44100);
5367 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5368 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005369 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005370 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
5371 module->mOutputProfiles.add(profile);
5372
Eric Laurent1c333e22014-05-20 10:48:17 -07005373 profile = new IOProfile(AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005374 profile->mSamplingRates.add(8000);
5375 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5376 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005377 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005378 module->mInputProfiles.add(profile);
5379
5380 mHwModules.add(module);
5381}
5382
5383}; // namespace android