blob: ee0c987212d14f318a05fd22387fd7ebb41d8f32 [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 Laurent72aa32f2014-05-30 18:51:48 -0700283 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700284 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } // end if is output device
286
Eric Laurente552edb2014-03-10 17:42:56 -0700287 // handle input devices
288 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700289 SortedVector <audio_io_handle_t> inputs;
290
Eric Laurent3a4311c2014-03-17 12:00:47 -0700291 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
292 address,
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700293 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700294
Eric Laurent3a4311c2014-03-17 12:00:47 -0700295 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700296 switch (state)
297 {
298 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700299 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700300 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700301 ALOGW("setDeviceConnectionState() device already connected: %d", device);
302 return INVALID_OPERATION;
303 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700304 HwModule *module = getModuleForDevice(device);
305 if (module == NULL) {
306 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
307 device);
308 return INVALID_OPERATION;
309 }
Eric Laurentd4692962014-05-05 18:13:44 -0700310 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
311 return INVALID_OPERATION;
312 }
313
Eric Laurent3a4311c2014-03-17 12:00:47 -0700314 index = mAvailableInputDevices.add(devDesc);
315 if (index >= 0) {
316 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700317 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700318 } else {
319 return NO_MEMORY;
320 }
Eric Laurentd4692962014-05-05 18:13:44 -0700321 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700322
323 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700324 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700326 ALOGW("setDeviceConnectionState() device not connected: %d", device);
327 return INVALID_OPERATION;
328 }
Eric Laurentd4692962014-05-05 18:13:44 -0700329 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700330 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700331 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700332
333 default:
334 ALOGE("setDeviceConnectionState() invalid state: %x", state);
335 return BAD_VALUE;
336 }
337
Eric Laurentd4692962014-05-05 18:13:44 -0700338 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700339
Eric Laurentb52c1522014-05-20 11:27:36 -0700340 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700341 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700342 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700343
344 ALOGW("setDeviceConnectionState() invalid device: %x", device);
345 return BAD_VALUE;
346}
347
Eric Laurente0720872014-03-11 09:30:41 -0700348audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700349 const char *device_address)
350{
Eric Laurent3b73df72014-03-11 09:06:29 -0700351 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700352 String8 address = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
354 String8(device_address),
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700355 0);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 ssize_t index;
357 DeviceVector *deviceVector;
358
Eric Laurente552edb2014-03-10 17:42:56 -0700359 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700361 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700362 deviceVector = &mAvailableInputDevices;
363 } else {
364 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
365 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700366 }
367
Eric Laurent3a4311c2014-03-17 12:00:47 -0700368 index = deviceVector->indexOf(devDesc);
369 if (index >= 0) {
370 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
371 } else {
372 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
373 }
Eric Laurente552edb2014-03-10 17:42:56 -0700374}
375
Eric Laurente0720872014-03-11 09:30:41 -0700376void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700377{
378 ALOGV("setPhoneState() state %d", state);
379 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700380 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700381 ALOGW("setPhoneState() invalid state %d", state);
382 return;
383 }
384
385 if (state == mPhoneState ) {
386 ALOGW("setPhoneState() setting same state %d", state);
387 return;
388 }
389
390 // if leaving call state, handle special case of active streams
391 // pertaining to sonification strategy see handleIncallSonification()
392 if (isInCall()) {
393 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700394 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
395 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700396 }
397 }
398
399 // store previous phone state for management of sonification strategy below
400 int oldState = mPhoneState;
401 mPhoneState = state;
402 bool force = false;
403
404 // are we entering or starting a call
405 if (!isStateInCall(oldState) && isStateInCall(state)) {
406 ALOGV(" Entering call in setPhoneState()");
407 // force routing command to audio hardware when starting a call
408 // even if no device change is needed
409 force = true;
410 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
411 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
412 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
413 }
414 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
415 ALOGV(" Exiting call in setPhoneState()");
416 // force routing command to audio hardware when exiting a call
417 // even if no device change is needed
418 force = true;
419 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
420 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
421 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
422 }
423 } else if (isStateInCall(state) && (state != oldState)) {
424 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
425 // force routing command to audio hardware when switching between telephony and VoIP
426 // even if no device change is needed
427 force = true;
428 }
429
430 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700431 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700432 checkA2dpSuspend();
433 checkOutputForAllStrategies();
434 updateDevicesAndOutputs();
435
436 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
437
438 // force routing command to audio hardware when ending call
439 // even if no device change is needed
440 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
441 newDevice = hwOutputDesc->device();
442 }
443
444 int delayMs = 0;
445 if (isStateInCall(state)) {
446 nsecs_t sysTime = systemTime();
447 for (size_t i = 0; i < mOutputs.size(); i++) {
448 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
449 // mute media and sonification strategies and delay device switch by the largest
450 // latency of any output where either strategy is active.
451 // This avoid sending the ring tone or music tail into the earpiece or headset.
452 if ((desc->isStrategyActive(STRATEGY_MEDIA,
453 SONIFICATION_HEADSET_MUSIC_DELAY,
454 sysTime) ||
455 desc->isStrategyActive(STRATEGY_SONIFICATION,
456 SONIFICATION_HEADSET_MUSIC_DELAY,
457 sysTime)) &&
458 (delayMs < (int)desc->mLatency*2)) {
459 delayMs = desc->mLatency*2;
460 }
461 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
462 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
463 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
464 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
465 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
466 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
467 }
468 }
469
470 // change routing is necessary
471 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
472
473 // if entering in call state, handle special case of active streams
474 // pertaining to sonification strategy see handleIncallSonification()
475 if (isStateInCall(state)) {
476 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700477 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
478 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700479 }
480 }
481
482 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700483 if (state == AUDIO_MODE_RINGTONE &&
484 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700485 mLimitRingtoneVolume = true;
486 } else {
487 mLimitRingtoneVolume = false;
488 }
489}
490
Eric Laurente0720872014-03-11 09:30:41 -0700491void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700492 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700493{
494 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
495
496 bool forceVolumeReeval = false;
497 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700498 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
499 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
500 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700501 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
502 return;
503 }
504 forceVolumeReeval = true;
505 mForceUse[usage] = config;
506 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700507 case AUDIO_POLICY_FORCE_FOR_MEDIA:
508 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
509 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
510 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
511 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
512 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700513 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
514 return;
515 }
516 mForceUse[usage] = config;
517 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700518 case AUDIO_POLICY_FORCE_FOR_RECORD:
519 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
520 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700521 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
522 return;
523 }
524 mForceUse[usage] = config;
525 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700526 case AUDIO_POLICY_FORCE_FOR_DOCK:
527 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
528 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
529 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
530 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
531 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700532 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
533 }
534 forceVolumeReeval = true;
535 mForceUse[usage] = config;
536 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700537 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
538 if (config != AUDIO_POLICY_FORCE_NONE &&
539 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
541 }
542 forceVolumeReeval = true;
543 mForceUse[usage] = config;
544 break;
545 default:
546 ALOGW("setForceUse() invalid usage %d", usage);
547 break;
548 }
549
550 // check for device and output changes triggered by new force usage
551 checkA2dpSuspend();
552 checkOutputForAllStrategies();
553 updateDevicesAndOutputs();
554 for (size_t i = 0; i < mOutputs.size(); i++) {
555 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700556 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700557 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
558 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
559 applyStreamVolumes(output, newDevice, 0, true);
560 }
561 }
562
563 audio_io_handle_t activeInput = getActiveInput();
564 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700565 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700566 }
567
568}
569
Eric Laurente0720872014-03-11 09:30:41 -0700570audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700571{
572 return mForceUse[usage];
573}
574
Eric Laurente0720872014-03-11 09:30:41 -0700575void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700576{
577 ALOGV("setSystemProperty() property %s, value %s", property, value);
578}
579
580// Find a direct output profile compatible with the parameters passed, even if the input flags do
581// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700582sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700583 audio_devices_t device,
584 uint32_t samplingRate,
585 audio_format_t format,
586 audio_channel_mask_t channelMask,
587 audio_output_flags_t flags)
588{
589 for (size_t i = 0; i < mHwModules.size(); i++) {
590 if (mHwModules[i]->mHandle == 0) {
591 continue;
592 }
593 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700594 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700595 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700596 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
597 if (profile->isCompatibleProfile(device, samplingRate, format,
598 channelMask,
599 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700600 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700601 }
602 } else {
603 if (profile->isCompatibleProfile(device, samplingRate, format,
604 channelMask,
605 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700606 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700607 }
608 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700609 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
610 return profile;
611 }
Eric Laurente552edb2014-03-10 17:42:56 -0700612 }
613 }
614 return 0;
615}
616
Eric Laurente0720872014-03-11 09:30:41 -0700617audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700618 uint32_t samplingRate,
619 audio_format_t format,
620 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700621 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700622 const audio_offload_info_t *offloadInfo)
623{
624 audio_io_handle_t output = 0;
625 uint32_t latency = 0;
Eric Laurent3b73df72014-03-11 09:06:29 -0700626 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700627 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
628 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
629 device, stream, samplingRate, format, channelMask, flags);
630
631#ifdef AUDIO_POLICY_TEST
632 if (mCurOutput != 0) {
633 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
634 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
635
636 if (mTestOutputs[mCurOutput] == 0) {
637 ALOGV("getOutput() opening test output");
638 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
639 outputDesc->mDevice = mTestDevice;
640 outputDesc->mSamplingRate = mTestSamplingRate;
641 outputDesc->mFormat = mTestFormat;
642 outputDesc->mChannelMask = mTestChannels;
643 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 outputDesc->mFlags =
645 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700646 outputDesc->mRefCount[stream] = 0;
647 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
648 &outputDesc->mSamplingRate,
649 &outputDesc->mFormat,
650 &outputDesc->mChannelMask,
651 &outputDesc->mLatency,
652 outputDesc->mFlags,
653 offloadInfo);
654 if (mTestOutputs[mCurOutput]) {
655 AudioParameter outputCmd = AudioParameter();
656 outputCmd.addInt(String8("set_id"),mCurOutput);
657 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
658 addOutput(mTestOutputs[mCurOutput], outputDesc);
659 }
660 }
661 return mTestOutputs[mCurOutput];
662 }
663#endif //AUDIO_POLICY_TEST
664
665 // open a direct output if required by specified parameters
666 //force direct flag if offload flag is set: offloading implies a direct output stream
667 // and all common behaviors are driven by checking only the direct flag
668 // this should normally be set appropriately in the policy configuration file
669 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700670 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700671 }
672
673 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
674 // creating an offloaded track and tearing it down immediately after start when audioflinger
675 // detects there is an active non offloadable effect.
676 // FIXME: We should check the audio session here but we do not have it in this context.
677 // This may prevent offloading in rare situations where effects are left active by apps
678 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700679 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700680 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
681 !isNonOffloadableEffectEnabled()) {
682 profile = getProfileForDirectOutput(device,
683 samplingRate,
684 format,
685 channelMask,
686 (audio_output_flags_t)flags);
687 }
688
Eric Laurent1c333e22014-05-20 10:48:17 -0700689 if (profile != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700690 AudioOutputDescriptor *outputDesc = NULL;
691
692 for (size_t i = 0; i < mOutputs.size(); i++) {
693 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
694 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
695 outputDesc = desc;
696 // reuse direct output if currently open and configured with same parameters
697 if ((samplingRate == outputDesc->mSamplingRate) &&
698 (format == outputDesc->mFormat) &&
699 (channelMask == outputDesc->mChannelMask)) {
700 outputDesc->mDirectOpenCount++;
701 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
702 return mOutputs.keyAt(i);
703 }
704 }
705 }
706 // close direct output if currently open and configured with different parameters
707 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700708 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700709 }
710 outputDesc = new AudioOutputDescriptor(profile);
711 outputDesc->mDevice = device;
712 outputDesc->mSamplingRate = samplingRate;
713 outputDesc->mFormat = format;
714 outputDesc->mChannelMask = channelMask;
715 outputDesc->mLatency = 0;
716 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
717 outputDesc->mRefCount[stream] = 0;
718 outputDesc->mStopTime[stream] = 0;
719 outputDesc->mDirectOpenCount = 1;
720 output = mpClientInterface->openOutput(profile->mModule->mHandle,
721 &outputDesc->mDevice,
722 &outputDesc->mSamplingRate,
723 &outputDesc->mFormat,
724 &outputDesc->mChannelMask,
725 &outputDesc->mLatency,
726 outputDesc->mFlags,
727 offloadInfo);
728
729 // only accept an output with the requested parameters
730 if (output == 0 ||
731 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
732 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
733 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
734 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
735 "format %d %d, channelMask %04x %04x", output, samplingRate,
736 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
737 outputDesc->mChannelMask);
738 if (output != 0) {
739 mpClientInterface->closeOutput(output);
740 }
741 delete outputDesc;
742 return 0;
743 }
744 audio_io_handle_t srcOutput = getOutputForEffect();
745 addOutput(output, outputDesc);
746 audio_io_handle_t dstOutput = getOutputForEffect();
747 if (dstOutput == output) {
748 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
749 }
750 mPreviousOutputs = mOutputs;
751 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700752 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700753 return output;
754 }
755
756 // ignoring channel mask due to downmix capability in mixer
757
758 // open a non direct output
759
760 // for non direct outputs, only PCM is supported
761 if (audio_is_linear_pcm(format)) {
762 // get which output is suitable for the specified stream. The actual
763 // routing change will happen when startOutput() will be called
764 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
765
766 output = selectOutput(outputs, flags);
767 }
768 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
769 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
770
771 ALOGV("getOutput() returns output %d", output);
772
773 return output;
774}
775
Eric Laurente0720872014-03-11 09:30:41 -0700776audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700777 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700778{
779 // select one output among several that provide a path to a particular device or set of
780 // devices (the list was previously build by getOutputsForDevice()).
781 // The priority is as follows:
782 // 1: the output with the highest number of requested policy flags
783 // 2: the primary output
784 // 3: the first output in the list
785
786 if (outputs.size() == 0) {
787 return 0;
788 }
789 if (outputs.size() == 1) {
790 return outputs[0];
791 }
792
793 int maxCommonFlags = 0;
794 audio_io_handle_t outputFlags = 0;
795 audio_io_handle_t outputPrimary = 0;
796
797 for (size_t i = 0; i < outputs.size(); i++) {
798 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
799 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700800 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700801 if (commonFlags > maxCommonFlags) {
802 outputFlags = outputs[i];
803 maxCommonFlags = commonFlags;
804 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
805 }
806 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
807 outputPrimary = outputs[i];
808 }
809 }
810 }
811
812 if (outputFlags != 0) {
813 return outputFlags;
814 }
815 if (outputPrimary != 0) {
816 return outputPrimary;
817 }
818
819 return outputs[0];
820}
821
Eric Laurente0720872014-03-11 09:30:41 -0700822status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700823 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700824 int session)
825{
826 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
827 ssize_t index = mOutputs.indexOfKey(output);
828 if (index < 0) {
829 ALOGW("startOutput() unknown output %d", output);
830 return BAD_VALUE;
831 }
832
833 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
834
835 // increment usage count for this stream on the requested output:
836 // NOTE that the usage count is the same for duplicated output and hardware output which is
837 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
838 outputDesc->changeRefCount(stream, 1);
839
840 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700841 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700842 routing_strategy strategy = getStrategy(stream);
843 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
844 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
845 uint32_t waitMs = 0;
846 bool force = false;
847 for (size_t i = 0; i < mOutputs.size(); i++) {
848 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
849 if (desc != outputDesc) {
850 // force a device change if any other output is managed by the same hw
851 // module and has a current device selection that differs from selected device.
852 // In this case, the audio HAL must receive the new device selection so that it can
853 // change the device currently selected by the other active output.
854 if (outputDesc->sharesHwModuleWith(desc) &&
855 desc->device() != newDevice) {
856 force = true;
857 }
858 // wait for audio on other active outputs to be presented when starting
859 // a notification so that audio focus effect can propagate.
860 uint32_t latency = desc->latency();
861 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
862 waitMs = latency;
863 }
864 }
865 }
866 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
867
868 // handle special case for sonification while in call
869 if (isInCall()) {
870 handleIncallSonification(stream, true, false);
871 }
872
873 // apply volume rules for current stream and device if necessary
874 checkAndSetVolume(stream,
875 mStreams[stream].getVolumeIndex(newDevice),
876 output,
877 newDevice);
878
879 // update the outputs if starting an output with a stream that can affect notification
880 // routing
881 handleNotificationRoutingForStream(stream);
882 if (waitMs > muteWaitMs) {
883 usleep((waitMs - muteWaitMs) * 2 * 1000);
884 }
885 }
886 return NO_ERROR;
887}
888
889
Eric Laurente0720872014-03-11 09:30:41 -0700890status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700891 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700892 int session)
893{
894 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
895 ssize_t index = mOutputs.indexOfKey(output);
896 if (index < 0) {
897 ALOGW("stopOutput() unknown output %d", output);
898 return BAD_VALUE;
899 }
900
901 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
902
903 // handle special case for sonification while in call
904 if (isInCall()) {
905 handleIncallSonification(stream, false, false);
906 }
907
908 if (outputDesc->mRefCount[stream] > 0) {
909 // decrement usage count of this stream on the output
910 outputDesc->changeRefCount(stream, -1);
911 // store time at which the stream was stopped - see isStreamActive()
912 if (outputDesc->mRefCount[stream] == 0) {
913 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700914 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700915 // delay the device switch by twice the latency because stopOutput() is executed when
916 // the track stop() command is received and at that time the audio track buffer can
917 // still contain data that needs to be drained. The latency only covers the audio HAL
918 // and kernel buffers. Also the latency does not always include additional delay in the
919 // audio path (audio DSP, CODEC ...)
920 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
921
922 // force restoring the device selection on other active outputs if it differs from the
923 // one being selected for this output
924 for (size_t i = 0; i < mOutputs.size(); i++) {
925 audio_io_handle_t curOutput = mOutputs.keyAt(i);
926 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
927 if (curOutput != output &&
928 desc->isActive() &&
929 outputDesc->sharesHwModuleWith(desc) &&
930 (newDevice != desc->device())) {
931 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700932 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700933 true,
934 outputDesc->mLatency*2);
935 }
936 }
937 // update the outputs if stopping one with a stream that can affect notification routing
938 handleNotificationRoutingForStream(stream);
939 }
940 return NO_ERROR;
941 } else {
942 ALOGW("stopOutput() refcount is already 0 for output %d", output);
943 return INVALID_OPERATION;
944 }
945}
946
Eric Laurente0720872014-03-11 09:30:41 -0700947void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700948{
949 ALOGV("releaseOutput() %d", output);
950 ssize_t index = mOutputs.indexOfKey(output);
951 if (index < 0) {
952 ALOGW("releaseOutput() releasing unknown output %d", output);
953 return;
954 }
955
956#ifdef AUDIO_POLICY_TEST
957 int testIndex = testOutputIndex(output);
958 if (testIndex != 0) {
959 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
960 if (outputDesc->isActive()) {
961 mpClientInterface->closeOutput(output);
962 delete mOutputs.valueAt(index);
963 mOutputs.removeItem(output);
964 mTestOutputs[testIndex] = 0;
965 }
966 return;
967 }
968#endif //AUDIO_POLICY_TEST
969
970 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -0700971 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700972 if (desc->mDirectOpenCount <= 0) {
973 ALOGW("releaseOutput() invalid open count %d for output %d",
974 desc->mDirectOpenCount, output);
975 return;
976 }
977 if (--desc->mDirectOpenCount == 0) {
978 closeOutput(output);
979 // If effects where present on the output, audioflinger moved them to the primary
980 // output by default: move them back to the appropriate output.
981 audio_io_handle_t dstOutput = getOutputForEffect();
982 if (dstOutput != mPrimaryOutput) {
983 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
984 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700985 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700986 }
987 }
988}
989
990
Eric Laurente0720872014-03-11 09:30:41 -0700991audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -0700992 uint32_t samplingRate,
993 audio_format_t format,
994 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700995 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -0700996{
997 audio_io_handle_t input = 0;
998 audio_devices_t device = getDeviceForInputSource(inputSource);
999
1000 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1001 inputSource, samplingRate, format, channelMask, acoustics);
1002
1003 if (device == AUDIO_DEVICE_NONE) {
1004 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1005 return 0;
1006 }
1007
1008 // adapt channel selection to input source
1009 switch(inputSource) {
1010 case AUDIO_SOURCE_VOICE_UPLINK:
1011 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1012 break;
1013 case AUDIO_SOURCE_VOICE_DOWNLINK:
1014 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1015 break;
1016 case AUDIO_SOURCE_VOICE_CALL:
1017 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1018 break;
1019 default:
1020 break;
1021 }
1022
Eric Laurent1c333e22014-05-20 10:48:17 -07001023 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001024 samplingRate,
1025 format,
1026 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001027 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001028 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1029 "channelMask %04x",
1030 device, samplingRate, format, channelMask);
1031 return 0;
1032 }
1033
1034 if (profile->mModule->mHandle == 0) {
1035 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1036 return 0;
1037 }
1038
1039 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
1040
1041 inputDesc->mInputSource = inputSource;
1042 inputDesc->mDevice = device;
1043 inputDesc->mSamplingRate = samplingRate;
1044 inputDesc->mFormat = format;
1045 inputDesc->mChannelMask = channelMask;
1046 inputDesc->mRefCount = 0;
1047 input = mpClientInterface->openInput(profile->mModule->mHandle,
1048 &inputDesc->mDevice,
1049 &inputDesc->mSamplingRate,
1050 &inputDesc->mFormat,
1051 &inputDesc->mChannelMask);
1052
1053 // only accept input with the exact requested set of parameters
1054 if (input == 0 ||
1055 (samplingRate != inputDesc->mSamplingRate) ||
1056 (format != inputDesc->mFormat) ||
1057 (channelMask != inputDesc->mChannelMask)) {
1058 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1059 samplingRate, format, channelMask);
1060 if (input != 0) {
1061 mpClientInterface->closeInput(input);
1062 }
1063 delete inputDesc;
1064 return 0;
1065 }
Eric Laurentd4692962014-05-05 18:13:44 -07001066 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001067 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001068 return input;
1069}
1070
Eric Laurente0720872014-03-11 09:30:41 -07001071status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001072{
1073 ALOGV("startInput() input %d", input);
1074 ssize_t index = mInputs.indexOfKey(input);
1075 if (index < 0) {
1076 ALOGW("startInput() unknown input %d", input);
1077 return BAD_VALUE;
1078 }
1079 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1080
1081#ifdef AUDIO_POLICY_TEST
1082 if (mTestInput == 0)
1083#endif //AUDIO_POLICY_TEST
1084 {
1085 // refuse 2 active AudioRecord clients at the same time except if the active input
1086 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1087 audio_io_handle_t activeInput = getActiveInput();
1088 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1089 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1090 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1091 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1092 stopInput(activeInput);
1093 releaseInput(activeInput);
1094 } else {
1095 ALOGW("startInput() input %d failed: other input already started", input);
1096 return INVALID_OPERATION;
1097 }
1098 }
1099 }
1100
Eric Laurent1c333e22014-05-20 10:48:17 -07001101 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001102
1103 // automatically enable the remote submix output when input is started
1104 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1105 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001106 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001107 }
1108
Eric Laurente552edb2014-03-10 17:42:56 -07001109 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1110
Eric Laurente552edb2014-03-10 17:42:56 -07001111 inputDesc->mRefCount = 1;
1112 return NO_ERROR;
1113}
1114
Eric Laurente0720872014-03-11 09:30:41 -07001115status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001116{
1117 ALOGV("stopInput() input %d", input);
1118 ssize_t index = mInputs.indexOfKey(input);
1119 if (index < 0) {
1120 ALOGW("stopInput() unknown input %d", input);
1121 return BAD_VALUE;
1122 }
1123 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1124
1125 if (inputDesc->mRefCount == 0) {
1126 ALOGW("stopInput() input %d already stopped", input);
1127 return INVALID_OPERATION;
1128 } else {
1129 // automatically disable the remote submix output when input is stopped
1130 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1131 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001132 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001133 }
1134
Eric Laurent1c333e22014-05-20 10:48:17 -07001135 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001136 inputDesc->mRefCount = 0;
1137 return NO_ERROR;
1138 }
1139}
1140
Eric Laurente0720872014-03-11 09:30:41 -07001141void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001142{
1143 ALOGV("releaseInput() %d", input);
1144 ssize_t index = mInputs.indexOfKey(input);
1145 if (index < 0) {
1146 ALOGW("releaseInput() releasing unknown input %d", input);
1147 return;
1148 }
1149 mpClientInterface->closeInput(input);
1150 delete mInputs.valueAt(index);
1151 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001152 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001153 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001154 ALOGV("releaseInput() exit");
1155}
1156
Eric Laurentd4692962014-05-05 18:13:44 -07001157void AudioPolicyManager::closeAllInputs() {
1158 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1159 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1160 }
1161 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001162 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001163}
1164
Eric Laurente0720872014-03-11 09:30:41 -07001165void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001166 int indexMin,
1167 int indexMax)
1168{
1169 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1170 if (indexMin < 0 || indexMin >= indexMax) {
1171 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1172 return;
1173 }
1174 mStreams[stream].mIndexMin = indexMin;
1175 mStreams[stream].mIndexMax = indexMax;
1176}
1177
Eric Laurente0720872014-03-11 09:30:41 -07001178status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001179 int index,
1180 audio_devices_t device)
1181{
1182
1183 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1184 return BAD_VALUE;
1185 }
1186 if (!audio_is_output_device(device)) {
1187 return BAD_VALUE;
1188 }
1189
1190 // Force max volume if stream cannot be muted
1191 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1192
1193 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1194 stream, device, index);
1195
1196 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1197 // clear all device specific values
1198 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1199 mStreams[stream].mIndexCur.clear();
1200 }
1201 mStreams[stream].mIndexCur.add(device, index);
1202
1203 // compute and apply stream volume on all outputs according to connected device
1204 status_t status = NO_ERROR;
1205 for (size_t i = 0; i < mOutputs.size(); i++) {
1206 audio_devices_t curDevice =
1207 getDeviceForVolume(mOutputs.valueAt(i)->device());
1208 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1209 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1210 if (volStatus != NO_ERROR) {
1211 status = volStatus;
1212 }
1213 }
1214 }
1215 return status;
1216}
1217
Eric Laurente0720872014-03-11 09:30:41 -07001218status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001219 int *index,
1220 audio_devices_t device)
1221{
1222 if (index == NULL) {
1223 return BAD_VALUE;
1224 }
1225 if (!audio_is_output_device(device)) {
1226 return BAD_VALUE;
1227 }
1228 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1229 // the strategy the stream belongs to.
1230 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1231 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1232 }
1233 device = getDeviceForVolume(device);
1234
1235 *index = mStreams[stream].getVolumeIndex(device);
1236 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1237 return NO_ERROR;
1238}
1239
Eric Laurente0720872014-03-11 09:30:41 -07001240audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001241 const SortedVector<audio_io_handle_t>& outputs)
1242{
1243 // select one output among several suitable for global effects.
1244 // The priority is as follows:
1245 // 1: An offloaded output. If the effect ends up not being offloadable,
1246 // AudioFlinger will invalidate the track and the offloaded output
1247 // will be closed causing the effect to be moved to a PCM output.
1248 // 2: A deep buffer output
1249 // 3: the first output in the list
1250
1251 if (outputs.size() == 0) {
1252 return 0;
1253 }
1254
1255 audio_io_handle_t outputOffloaded = 0;
1256 audio_io_handle_t outputDeepBuffer = 0;
1257
1258 for (size_t i = 0; i < outputs.size(); i++) {
1259 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001260 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001261 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1262 outputOffloaded = outputs[i];
1263 }
1264 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1265 outputDeepBuffer = outputs[i];
1266 }
1267 }
1268
1269 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1270 outputOffloaded, outputDeepBuffer);
1271 if (outputOffloaded != 0) {
1272 return outputOffloaded;
1273 }
1274 if (outputDeepBuffer != 0) {
1275 return outputDeepBuffer;
1276 }
1277
1278 return outputs[0];
1279}
1280
Eric Laurente0720872014-03-11 09:30:41 -07001281audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001282{
1283 // apply simple rule where global effects are attached to the same output as MUSIC streams
1284
Eric Laurent3b73df72014-03-11 09:06:29 -07001285 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001286 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1287 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1288
1289 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1290 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1291 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1292
1293 return output;
1294}
1295
Eric Laurente0720872014-03-11 09:30:41 -07001296status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001297 audio_io_handle_t io,
1298 uint32_t strategy,
1299 int session,
1300 int id)
1301{
1302 ssize_t index = mOutputs.indexOfKey(io);
1303 if (index < 0) {
1304 index = mInputs.indexOfKey(io);
1305 if (index < 0) {
1306 ALOGW("registerEffect() unknown io %d", io);
1307 return INVALID_OPERATION;
1308 }
1309 }
1310
1311 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1312 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1313 desc->name, desc->memoryUsage);
1314 return INVALID_OPERATION;
1315 }
1316 mTotalEffectsMemory += desc->memoryUsage;
1317 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1318 desc->name, io, strategy, session, id);
1319 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1320
1321 EffectDescriptor *pDesc = new EffectDescriptor();
1322 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1323 pDesc->mIo = io;
1324 pDesc->mStrategy = (routing_strategy)strategy;
1325 pDesc->mSession = session;
1326 pDesc->mEnabled = false;
1327
1328 mEffects.add(id, pDesc);
1329
1330 return NO_ERROR;
1331}
1332
Eric Laurente0720872014-03-11 09:30:41 -07001333status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001334{
1335 ssize_t index = mEffects.indexOfKey(id);
1336 if (index < 0) {
1337 ALOGW("unregisterEffect() unknown effect ID %d", id);
1338 return INVALID_OPERATION;
1339 }
1340
1341 EffectDescriptor *pDesc = mEffects.valueAt(index);
1342
1343 setEffectEnabled(pDesc, false);
1344
1345 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1346 ALOGW("unregisterEffect() memory %d too big for total %d",
1347 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1348 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1349 }
1350 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1351 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1352 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1353
1354 mEffects.removeItem(id);
1355 delete pDesc;
1356
1357 return NO_ERROR;
1358}
1359
Eric Laurente0720872014-03-11 09:30:41 -07001360status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001361{
1362 ssize_t index = mEffects.indexOfKey(id);
1363 if (index < 0) {
1364 ALOGW("unregisterEffect() unknown effect ID %d", id);
1365 return INVALID_OPERATION;
1366 }
1367
1368 return setEffectEnabled(mEffects.valueAt(index), enabled);
1369}
1370
Eric Laurente0720872014-03-11 09:30:41 -07001371status_t AudioPolicyManager::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001372{
1373 if (enabled == pDesc->mEnabled) {
1374 ALOGV("setEffectEnabled(%s) effect already %s",
1375 enabled?"true":"false", enabled?"enabled":"disabled");
1376 return INVALID_OPERATION;
1377 }
1378
1379 if (enabled) {
1380 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1381 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1382 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1383 return INVALID_OPERATION;
1384 }
1385 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1386 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1387 } else {
1388 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1389 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1390 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1391 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1392 }
1393 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1394 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1395 }
1396 pDesc->mEnabled = enabled;
1397 return NO_ERROR;
1398}
1399
Eric Laurente0720872014-03-11 09:30:41 -07001400bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001401{
1402 for (size_t i = 0; i < mEffects.size(); i++) {
1403 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1404 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1405 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1406 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1407 pDesc->mDesc.name, pDesc->mSession);
1408 return true;
1409 }
1410 }
1411 return false;
1412}
1413
Eric Laurente0720872014-03-11 09:30:41 -07001414bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001415{
1416 nsecs_t sysTime = systemTime();
1417 for (size_t i = 0; i < mOutputs.size(); i++) {
1418 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001419 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001420 return true;
1421 }
1422 }
1423 return false;
1424}
1425
Eric Laurente0720872014-03-11 09:30:41 -07001426bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001427 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001428{
1429 nsecs_t sysTime = systemTime();
1430 for (size_t i = 0; i < mOutputs.size(); i++) {
1431 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1432 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001433 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001434 return true;
1435 }
1436 }
1437 return false;
1438}
1439
Eric Laurente0720872014-03-11 09:30:41 -07001440bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001441{
1442 for (size_t i = 0; i < mInputs.size(); i++) {
1443 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1444 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001445 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001446 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1447 && (inputDescriptor->mRefCount > 0)) {
1448 return true;
1449 }
1450 }
1451 return false;
1452}
1453
1454
Eric Laurente0720872014-03-11 09:30:41 -07001455status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001456{
1457 const size_t SIZE = 256;
1458 char buffer[SIZE];
1459 String8 result;
1460
1461 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1462 result.append(buffer);
1463
1464 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1465 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001466 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1467 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001468 snprintf(buffer, SIZE, " Force use for communications %d\n",
1469 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
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 media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001472 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001473 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001474 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001475 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001476 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001477 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001478 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001479
Eric Laurent3a4311c2014-03-17 12:00:47 -07001480 snprintf(buffer, SIZE, " Available output devices:\n");
1481 result.append(buffer);
1482 write(fd, result.string(), result.size());
1483 DeviceDescriptor::dumpHeader(fd, 2);
1484 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
1485 mAvailableOutputDevices[i]->dump(fd, 2);
1486 }
1487 snprintf(buffer, SIZE, "\n Available input devices:\n");
1488 write(fd, buffer, strlen(buffer));
1489 DeviceDescriptor::dumpHeader(fd, 2);
1490 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1491 mAvailableInputDevices[i]->dump(fd, 2);
1492 }
Eric Laurente552edb2014-03-10 17:42:56 -07001493
1494 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1495 write(fd, buffer, strlen(buffer));
1496 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001497 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001498 write(fd, buffer, strlen(buffer));
1499 mHwModules[i]->dump(fd);
1500 }
1501
1502 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1503 write(fd, buffer, strlen(buffer));
1504 for (size_t i = 0; i < mOutputs.size(); i++) {
1505 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1506 write(fd, buffer, strlen(buffer));
1507 mOutputs.valueAt(i)->dump(fd);
1508 }
1509
1510 snprintf(buffer, SIZE, "\nInputs dump:\n");
1511 write(fd, buffer, strlen(buffer));
1512 for (size_t i = 0; i < mInputs.size(); i++) {
1513 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1514 write(fd, buffer, strlen(buffer));
1515 mInputs.valueAt(i)->dump(fd);
1516 }
1517
1518 snprintf(buffer, SIZE, "\nStreams dump:\n");
1519 write(fd, buffer, strlen(buffer));
1520 snprintf(buffer, SIZE,
1521 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1522 write(fd, buffer, strlen(buffer));
Eric Laurent3b73df72014-03-11 09:06:29 -07001523 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001524 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001525 write(fd, buffer, strlen(buffer));
1526 mStreams[i].dump(fd);
1527 }
1528
1529 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1530 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1531 write(fd, buffer, strlen(buffer));
1532
1533 snprintf(buffer, SIZE, "Registered effects:\n");
1534 write(fd, buffer, strlen(buffer));
1535 for (size_t i = 0; i < mEffects.size(); i++) {
1536 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1537 write(fd, buffer, strlen(buffer));
1538 mEffects.valueAt(i)->dump(fd);
1539 }
1540
1541
1542 return NO_ERROR;
1543}
1544
1545// This function checks for the parameters which can be offloaded.
1546// This can be enhanced depending on the capability of the DSP and policy
1547// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001548bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001549{
1550 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001551 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001552 offloadInfo.sample_rate, offloadInfo.channel_mask,
1553 offloadInfo.format,
1554 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1555 offloadInfo.has_video);
1556
1557 // Check if offload has been disabled
1558 char propValue[PROPERTY_VALUE_MAX];
1559 if (property_get("audio.offload.disable", propValue, "0")) {
1560 if (atoi(propValue) != 0) {
1561 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1562 return false;
1563 }
1564 }
1565
1566 // Check if stream type is music, then only allow offload as of now.
1567 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1568 {
1569 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1570 return false;
1571 }
1572
1573 //TODO: enable audio offloading with video when ready
1574 if (offloadInfo.has_video)
1575 {
1576 ALOGV("isOffloadSupported: has_video == true, returning false");
1577 return false;
1578 }
1579
1580 //If duration is less than minimum value defined in property, return false
1581 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1582 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1583 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1584 return false;
1585 }
1586 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1587 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1588 return false;
1589 }
1590
1591 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1592 // creating an offloaded track and tearing it down immediately after start when audioflinger
1593 // detects there is an active non offloadable effect.
1594 // FIXME: We should check the audio session here but we do not have it in this context.
1595 // This may prevent offloading in rare situations where effects are left active by apps
1596 // in the background.
1597 if (isNonOffloadableEffectEnabled()) {
1598 return false;
1599 }
1600
1601 // See if there is a profile to support this.
1602 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001603 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001604 offloadInfo.sample_rate,
1605 offloadInfo.format,
1606 offloadInfo.channel_mask,
1607 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001608 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1609 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001610}
1611
Eric Laurent6a94d692014-05-20 11:18:06 -07001612status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1613 audio_port_type_t type,
1614 unsigned int *num_ports,
1615 struct audio_port *ports,
1616 unsigned int *generation)
1617{
1618 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1619 generation == NULL) {
1620 return BAD_VALUE;
1621 }
1622 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1623 if (ports == NULL) {
1624 *num_ports = 0;
1625 }
1626
1627 size_t portsWritten = 0;
1628 size_t portsMax = *num_ports;
1629 *num_ports = 0;
1630 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1631 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1632 for (size_t i = 0;
1633 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1634 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1635 }
1636 *num_ports += mAvailableOutputDevices.size();
1637 }
1638 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1639 for (size_t i = 0;
1640 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1641 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1642 }
1643 *num_ports += mAvailableInputDevices.size();
1644 }
1645 }
1646 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1647 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1648 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1649 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1650 }
1651 *num_ports += mInputs.size();
1652 }
1653 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1654 for (size_t i = 0; i < mOutputs.size() && portsWritten < portsMax; i++) {
1655 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1656 }
1657 *num_ports += mOutputs.size();
1658 }
1659 }
1660 *generation = curAudioPortGeneration();
1661 ALOGV("listAudioPorts() got %d ports needed %d", portsWritten, *num_ports);
1662 return NO_ERROR;
1663}
1664
1665status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1666{
1667 return NO_ERROR;
1668}
1669
1670AudioPolicyManager::AudioOutputDescriptor *AudioPolicyManager::getOutputFromId(
1671 audio_port_handle_t id) const
1672{
1673 AudioOutputDescriptor *outputDesc = NULL;
1674 for (size_t i = 0; i < mOutputs.size(); i++) {
1675 outputDesc = mOutputs.valueAt(i);
1676 if (outputDesc->mId == id) {
1677 break;
1678 }
1679 }
1680 return outputDesc;
1681}
1682
1683AudioPolicyManager::AudioInputDescriptor *AudioPolicyManager::getInputFromId(
1684 audio_port_handle_t id) const
1685{
1686 AudioInputDescriptor *inputDesc = NULL;
1687 for (size_t i = 0; i < mInputs.size(); i++) {
1688 inputDesc = mInputs.valueAt(i);
1689 if (inputDesc->mId == id) {
1690 break;
1691 }
1692 }
1693 return inputDesc;
1694}
1695
1696AudioPolicyManager::HwModule *AudioPolicyManager::getModuleForDevice(audio_devices_t device) const
1697{
1698 for (size_t i = 0; i < mHwModules.size(); i++) {
1699 if (mHwModules[i]->mHandle == 0) {
1700 continue;
1701 }
1702 if (audio_is_output_device(device)) {
1703 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1704 {
1705 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1706 return mHwModules[i];
1707 }
1708 }
1709 } else {
1710 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1711 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1712 device & ~AUDIO_DEVICE_BIT_IN) {
1713 return mHwModules[i];
1714 }
1715 }
1716 }
1717 }
1718 return NULL;
1719}
1720
1721status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1722 audio_patch_handle_t *handle,
1723 uid_t uid)
1724{
1725 ALOGV("createAudioPatch()");
1726
1727 if (handle == NULL || patch == NULL) {
1728 return BAD_VALUE;
1729 }
1730 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1731
1732 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1733 return INVALID_OPERATION;
1734 }
1735 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1736 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1737 return INVALID_OPERATION;
1738 }
1739
1740 sp<AudioPatch> patchDesc;
1741 ssize_t index = mAudioPatches.indexOfKey(*handle);
1742
1743 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1744 patch->sinks[0].type);
1745 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1746 patch->sources[0].role,
1747 patch->sources[0].type);
1748
1749 if (index >= 0) {
1750 patchDesc = mAudioPatches.valueAt(index);
1751 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1752 mUidCached, patchDesc->mUid, uid);
1753 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1754 return INVALID_OPERATION;
1755 }
1756 } else {
1757 *handle = 0;
1758 }
1759
1760 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1761 // TODO add support for mix to mix connection
1762 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1763 ALOGV("createAudioPatch() source mix sink not device");
1764 return BAD_VALUE;
1765 }
1766 // output mix to output device connection
1767 AudioOutputDescriptor *outputDesc = getOutputFromId(patch->sources[0].id);
1768 if (outputDesc == NULL) {
1769 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1770 return BAD_VALUE;
1771 }
1772 if (patchDesc != 0) {
1773 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1774 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1775 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1776 return BAD_VALUE;
1777 }
1778 }
1779 sp<DeviceDescriptor> devDesc =
1780 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1781 if (devDesc == 0) {
1782 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1783 return BAD_VALUE;
1784 }
1785
1786 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1787 patch->sources[0].sample_rate,
1788 patch->sources[0].format,
1789 patch->sources[0].channel_mask,
1790 AUDIO_OUTPUT_FLAG_NONE)) {
1791 return INVALID_OPERATION;
1792 }
1793 // TODO: reconfigure output format and channels here
1794 ALOGV("createAudioPatch() setting device %08x on output %d",
1795 devDesc->mType, outputDesc->mIoHandle);
1796 setOutputDevice(outputDesc->mIoHandle,
1797 devDesc->mType,
1798 true,
1799 0,
1800 handle);
1801 index = mAudioPatches.indexOfKey(*handle);
1802 if (index >= 0) {
1803 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1804 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1805 }
1806 patchDesc = mAudioPatches.valueAt(index);
1807 patchDesc->mUid = uid;
1808 ALOGV("createAudioPatch() success");
1809 } else {
1810 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1811 return INVALID_OPERATION;
1812 }
1813 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1814 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1815 // input device to input mix connection
1816 AudioInputDescriptor *inputDesc = getInputFromId(patch->sinks[0].id);
1817 if (inputDesc == NULL) {
1818 return BAD_VALUE;
1819 }
1820 if (patchDesc != 0) {
1821 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1822 return BAD_VALUE;
1823 }
1824 }
1825 sp<DeviceDescriptor> devDesc =
1826 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1827 if (devDesc == 0) {
1828 return BAD_VALUE;
1829 }
1830
1831 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1832 patch->sinks[0].sample_rate,
1833 patch->sinks[0].format,
1834 patch->sinks[0].channel_mask,
1835 AUDIO_OUTPUT_FLAG_NONE)) {
1836 return INVALID_OPERATION;
1837 }
1838 // TODO: reconfigure output format and channels here
1839 ALOGV("createAudioPatch() setting device %08x on output %d",
1840 devDesc->mType, inputDesc->mIoHandle);
1841 setInputDevice(inputDesc->mIoHandle,
1842 devDesc->mType,
1843 true,
1844 handle);
1845 index = mAudioPatches.indexOfKey(*handle);
1846 if (index >= 0) {
1847 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1848 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1849 }
1850 patchDesc = mAudioPatches.valueAt(index);
1851 patchDesc->mUid = uid;
1852 ALOGV("createAudioPatch() success");
1853 } else {
1854 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1855 return INVALID_OPERATION;
1856 }
1857 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1858 // device to device connection
1859 if (patchDesc != 0) {
1860 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1861 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1862 return BAD_VALUE;
1863 }
1864 }
1865
1866 sp<DeviceDescriptor> srcDeviceDesc =
1867 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1868 sp<DeviceDescriptor> sinkDeviceDesc =
1869 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1870 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1871 return BAD_VALUE;
1872 }
1873 //update source and sink with our own data as the data passed in the patch may
1874 // be incomplete.
1875 struct audio_patch newPatch = *patch;
1876 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1877 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1878
1879 // TODO: add support for devices on different HW modules
1880 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1881 return INVALID_OPERATION;
1882 }
1883 // TODO: check from routing capabilities in config file and other conflicting patches
1884
1885 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1886 if (index >= 0) {
1887 afPatchHandle = patchDesc->mAfPatchHandle;
1888 }
1889
1890 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1891 &afPatchHandle,
1892 0);
1893 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1894 status, afPatchHandle);
1895 if (status == NO_ERROR) {
1896 if (index < 0) {
1897 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1898 &newPatch, uid);
1899 addAudioPatch(patchDesc->mHandle, patchDesc);
1900 } else {
1901 patchDesc->mPatch = newPatch;
1902 }
1903 patchDesc->mAfPatchHandle = afPatchHandle;
1904 *handle = patchDesc->mHandle;
1905 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001906 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001907 } else {
1908 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1909 status);
1910 return INVALID_OPERATION;
1911 }
1912 } else {
1913 return BAD_VALUE;
1914 }
1915 } else {
1916 return BAD_VALUE;
1917 }
1918 return NO_ERROR;
1919}
1920
1921status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1922 uid_t uid)
1923{
1924 ALOGV("releaseAudioPatch() patch %d", handle);
1925
1926 ssize_t index = mAudioPatches.indexOfKey(handle);
1927
1928 if (index < 0) {
1929 return BAD_VALUE;
1930 }
1931 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1932 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1933 mUidCached, patchDesc->mUid, uid);
1934 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1935 return INVALID_OPERATION;
1936 }
1937
1938 struct audio_patch *patch = &patchDesc->mPatch;
1939 patchDesc->mUid = mUidCached;
1940 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1941 AudioOutputDescriptor *outputDesc = getOutputFromId(patch->sources[0].id);
1942 if (outputDesc == NULL) {
1943 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
1944 return BAD_VALUE;
1945 }
1946
1947 setOutputDevice(outputDesc->mIoHandle,
1948 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
1949 true,
1950 0,
1951 NULL);
1952 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1953 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1954 AudioInputDescriptor *inputDesc = getInputFromId(patch->sinks[0].id);
1955 if (inputDesc == NULL) {
1956 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
1957 return BAD_VALUE;
1958 }
1959 setInputDevice(inputDesc->mIoHandle,
1960 getNewInputDevice(inputDesc->mIoHandle),
1961 true,
1962 NULL);
1963 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1964 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
1965 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1966 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
1967 status, patchDesc->mAfPatchHandle);
1968 removeAudioPatch(patchDesc->mHandle);
1969 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001970 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001971 } else {
1972 return BAD_VALUE;
1973 }
1974 } else {
1975 return BAD_VALUE;
1976 }
1977 return NO_ERROR;
1978}
1979
1980status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
1981 struct audio_patch *patches,
1982 unsigned int *generation)
1983{
1984 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
1985 generation == NULL) {
1986 return BAD_VALUE;
1987 }
1988 ALOGV("listAudioPatches() num_patches %d patches %p available patches %d",
1989 *num_patches, patches, mAudioPatches.size());
1990 if (patches == NULL) {
1991 *num_patches = 0;
1992 }
1993
1994 size_t patchesWritten = 0;
1995 size_t patchesMax = *num_patches;
1996 for (size_t i = 0;
1997 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
1998 patches[patchesWritten] = mAudioPatches[i]->mPatch;
1999 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
2000 ALOGV("listAudioPatches() patch %d num_sources %d num_sinks %d",
2001 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2002 }
2003 *num_patches = mAudioPatches.size();
2004
2005 *generation = curAudioPortGeneration();
2006 ALOGV("listAudioPatches() got %d patches needed %d", patchesWritten, *num_patches);
2007 return NO_ERROR;
2008}
2009
2010status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config __unused)
2011{
2012 return NO_ERROR;
2013}
2014
2015void AudioPolicyManager::clearAudioPatches(uid_t uid)
2016{
2017 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2018 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2019 if (patchDesc->mUid == uid) {
2020 // releaseAudioPatch() removes the patch from mAudioPatches
2021 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2022 i--;
2023 }
2024 }
2025 }
2026}
2027
2028status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2029 const sp<AudioPatch>& patch)
2030{
2031 ssize_t index = mAudioPatches.indexOfKey(handle);
2032
2033 if (index >= 0) {
2034 ALOGW("addAudioPatch() patch %d already in", handle);
2035 return ALREADY_EXISTS;
2036 }
2037 mAudioPatches.add(handle, patch);
2038 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2039 "sink handle %d",
2040 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2041 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2042 return NO_ERROR;
2043}
2044
2045status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2046{
2047 ssize_t index = mAudioPatches.indexOfKey(handle);
2048
2049 if (index < 0) {
2050 ALOGW("removeAudioPatch() patch %d not in", handle);
2051 return ALREADY_EXISTS;
2052 }
2053 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2054 mAudioPatches.valueAt(index)->mAfPatchHandle);
2055 mAudioPatches.removeItemsAt(index);
2056 return NO_ERROR;
2057}
2058
Eric Laurente552edb2014-03-10 17:42:56 -07002059// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002060// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002061// ----------------------------------------------------------------------------
2062
Eric Laurent3a4311c2014-03-17 12:00:47 -07002063uint32_t AudioPolicyManager::nextUniqueId()
2064{
2065 return android_atomic_inc(&mNextUniqueId);
2066}
2067
Eric Laurent6a94d692014-05-20 11:18:06 -07002068uint32_t AudioPolicyManager::nextAudioPortGeneration()
2069{
2070 return android_atomic_inc(&mAudioPortGeneration);
2071}
2072
Eric Laurente0720872014-03-11 09:30:41 -07002073AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002074 :
2075#ifdef AUDIO_POLICY_TEST
2076 Thread(false),
2077#endif //AUDIO_POLICY_TEST
2078 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002079 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002080 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2081 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002082 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002083 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2084 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002085{
Eric Laurent6a94d692014-05-20 11:18:06 -07002086 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002087 mpClientInterface = clientInterface;
2088
Eric Laurent3b73df72014-03-11 09:06:29 -07002089 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2090 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002091 }
2092
Eric Laurent3a4311c2014-03-17 12:00:47 -07002093 mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002094 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2095 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2096 ALOGE("could not load audio policy configuration file, setting defaults");
2097 defaultAudioPolicyConfig();
2098 }
2099 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002100 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002101
2102 // must be done after reading the policy
2103 initializeVolumeCurves();
2104
2105 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002106 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2107 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002108 for (size_t i = 0; i < mHwModules.size(); i++) {
2109 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2110 if (mHwModules[i]->mHandle == 0) {
2111 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2112 continue;
2113 }
2114 // open all output streams needed to access attached devices
2115 // except for direct output streams that are only opened when they are actually
2116 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002117 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002118 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2119 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002120 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002121
Eric Laurent3a4311c2014-03-17 12:00:47 -07002122 if (outProfile->mSupportedDevices.isEmpty()) {
2123 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2124 continue;
2125 }
2126
2127 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2128 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002129 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
2130 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002131
Eric Laurent1c333e22014-05-20 10:48:17 -07002132 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002133 audio_io_handle_t output = mpClientInterface->openOutput(
2134 outProfile->mModule->mHandle,
2135 &outputDesc->mDevice,
2136 &outputDesc->mSamplingRate,
2137 &outputDesc->mFormat,
2138 &outputDesc->mChannelMask,
2139 &outputDesc->mLatency,
2140 outputDesc->mFlags);
2141 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002142 ALOGW("Cannot open output stream for device %08x on hw module %s",
2143 outputDesc->mDevice,
2144 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002145 delete outputDesc;
2146 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002147 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002148 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002149 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002150 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002151 // give a valid ID to an attached device once confirmed it is reachable
2152 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2153 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002154 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002155 }
2156 }
Eric Laurente552edb2014-03-10 17:42:56 -07002157 if (mPrimaryOutput == 0 &&
2158 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2159 mPrimaryOutput = output;
2160 }
2161 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002162 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002163 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002164 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002165 true);
2166 }
2167 }
2168 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002169 // open input streams needed to access attached devices to validate
2170 // mAvailableInputDevices list
2171 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2172 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002173 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002174
Eric Laurent3a4311c2014-03-17 12:00:47 -07002175 if (inProfile->mSupportedDevices.isEmpty()) {
2176 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2177 continue;
2178 }
2179
2180 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2181 if (profileTypes & inputDeviceTypes) {
2182 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(inProfile);
2183
2184 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002185 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002186 audio_io_handle_t input = mpClientInterface->openInput(
2187 inProfile->mModule->mHandle,
2188 &inputDesc->mDevice,
2189 &inputDesc->mSamplingRate,
2190 &inputDesc->mFormat,
2191 &inputDesc->mChannelMask);
2192
2193 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002194 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002195 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002196 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002197 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002198 // give a valid ID to an attached device once confirmed it is reachable
2199 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2200 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002201 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002202 }
2203 }
2204 mpClientInterface->closeInput(input);
2205 } else {
2206 ALOGW("Cannot open input stream for device %08x on hw module %s",
2207 inputDesc->mDevice,
2208 mHwModules[i]->mName);
2209 }
2210 delete inputDesc;
2211 }
2212 }
2213 }
2214 // make sure all attached devices have been allocated a unique ID
2215 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2216 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002217 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002218 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2219 continue;
2220 }
2221 i++;
2222 }
2223 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2224 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002225 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002226 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2227 continue;
2228 }
2229 i++;
2230 }
2231 // make sure default device is reachable
2232 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002233 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002234 }
Eric Laurente552edb2014-03-10 17:42:56 -07002235
2236 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2237
2238 updateDevicesAndOutputs();
2239
2240#ifdef AUDIO_POLICY_TEST
2241 if (mPrimaryOutput != 0) {
2242 AudioParameter outputCmd = AudioParameter();
2243 outputCmd.addInt(String8("set_id"), 0);
2244 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2245
2246 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2247 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002248 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2249 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002250 mTestLatencyMs = 0;
2251 mCurOutput = 0;
2252 mDirectOutput = false;
2253 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2254 mTestOutputs[i] = 0;
2255 }
2256
2257 const size_t SIZE = 256;
2258 char buffer[SIZE];
2259 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2260 run(buffer, ANDROID_PRIORITY_AUDIO);
2261 }
2262#endif //AUDIO_POLICY_TEST
2263}
2264
Eric Laurente0720872014-03-11 09:30:41 -07002265AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002266{
2267#ifdef AUDIO_POLICY_TEST
2268 exit();
2269#endif //AUDIO_POLICY_TEST
2270 for (size_t i = 0; i < mOutputs.size(); i++) {
2271 mpClientInterface->closeOutput(mOutputs.keyAt(i));
2272 delete mOutputs.valueAt(i);
2273 }
2274 for (size_t i = 0; i < mInputs.size(); i++) {
2275 mpClientInterface->closeInput(mInputs.keyAt(i));
2276 delete mInputs.valueAt(i);
2277 }
2278 for (size_t i = 0; i < mHwModules.size(); i++) {
2279 delete mHwModules[i];
2280 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002281 mAvailableOutputDevices.clear();
2282 mAvailableInputDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002283}
2284
Eric Laurente0720872014-03-11 09:30:41 -07002285status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002286{
2287 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2288}
2289
2290#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002291bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002292{
2293 ALOGV("entering threadLoop()");
2294 while (!exitPending())
2295 {
2296 String8 command;
2297 int valueInt;
2298 String8 value;
2299
2300 Mutex::Autolock _l(mLock);
2301 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2302
2303 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2304 AudioParameter param = AudioParameter(command);
2305
2306 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2307 valueInt != 0) {
2308 ALOGV("Test command %s received", command.string());
2309 String8 target;
2310 if (param.get(String8("target"), target) != NO_ERROR) {
2311 target = "Manager";
2312 }
2313 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2314 param.remove(String8("test_cmd_policy_output"));
2315 mCurOutput = valueInt;
2316 }
2317 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2318 param.remove(String8("test_cmd_policy_direct"));
2319 if (value == "false") {
2320 mDirectOutput = false;
2321 } else if (value == "true") {
2322 mDirectOutput = true;
2323 }
2324 }
2325 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2326 param.remove(String8("test_cmd_policy_input"));
2327 mTestInput = valueInt;
2328 }
2329
2330 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2331 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002332 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002333 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002334 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002335 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002336 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002337 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002338 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002339 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002340 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002341 if (target == "Manager") {
2342 mTestFormat = format;
2343 } else if (mTestOutputs[mCurOutput] != 0) {
2344 AudioParameter outputParam = AudioParameter();
2345 outputParam.addInt(String8("format"), format);
2346 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2347 }
2348 }
2349 }
2350 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2351 param.remove(String8("test_cmd_policy_channels"));
2352 int channels = 0;
2353
2354 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002355 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002356 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002357 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002358 }
2359 if (channels != 0) {
2360 if (target == "Manager") {
2361 mTestChannels = channels;
2362 } else if (mTestOutputs[mCurOutput] != 0) {
2363 AudioParameter outputParam = AudioParameter();
2364 outputParam.addInt(String8("channels"), channels);
2365 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2366 }
2367 }
2368 }
2369 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2370 param.remove(String8("test_cmd_policy_sampleRate"));
2371 if (valueInt >= 0 && valueInt <= 96000) {
2372 int samplingRate = valueInt;
2373 if (target == "Manager") {
2374 mTestSamplingRate = samplingRate;
2375 } else if (mTestOutputs[mCurOutput] != 0) {
2376 AudioParameter outputParam = AudioParameter();
2377 outputParam.addInt(String8("sampling_rate"), samplingRate);
2378 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2379 }
2380 }
2381 }
2382
2383 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2384 param.remove(String8("test_cmd_policy_reopen"));
2385
2386 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2387 mpClientInterface->closeOutput(mPrimaryOutput);
2388
2389 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2390
2391 delete mOutputs.valueFor(mPrimaryOutput);
2392 mOutputs.removeItem(mPrimaryOutput);
2393
2394 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
2395 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2396 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2397 &outputDesc->mDevice,
2398 &outputDesc->mSamplingRate,
2399 &outputDesc->mFormat,
2400 &outputDesc->mChannelMask,
2401 &outputDesc->mLatency,
2402 outputDesc->mFlags);
2403 if (mPrimaryOutput == 0) {
2404 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2405 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2406 } else {
2407 AudioParameter outputCmd = AudioParameter();
2408 outputCmd.addInt(String8("set_id"), 0);
2409 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2410 addOutput(mPrimaryOutput, outputDesc);
2411 }
2412 }
2413
2414
2415 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2416 }
2417 }
2418 return false;
2419}
2420
Eric Laurente0720872014-03-11 09:30:41 -07002421void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002422{
2423 {
2424 AutoMutex _l(mLock);
2425 requestExit();
2426 mWaitWorkCV.signal();
2427 }
2428 requestExitAndWait();
2429}
2430
Eric Laurente0720872014-03-11 09:30:41 -07002431int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002432{
2433 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2434 if (output == mTestOutputs[i]) return i;
2435 }
2436 return 0;
2437}
2438#endif //AUDIO_POLICY_TEST
2439
2440// ---
2441
Eric Laurent1c333e22014-05-20 10:48:17 -07002442void AudioPolicyManager::addOutput(audio_io_handle_t output, AudioOutputDescriptor *outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002443{
Eric Laurent1c333e22014-05-20 10:48:17 -07002444 outputDesc->mIoHandle = output;
2445 outputDesc->mId = nextUniqueId();
2446 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002447 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002448}
2449
Eric Laurent1c333e22014-05-20 10:48:17 -07002450void AudioPolicyManager::addInput(audio_io_handle_t input, AudioInputDescriptor *inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002451{
Eric Laurent1c333e22014-05-20 10:48:17 -07002452 inputDesc->mIoHandle = input;
2453 inputDesc->mId = nextUniqueId();
2454 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002455 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002456}
Eric Laurente552edb2014-03-10 17:42:56 -07002457
Eric Laurent3a4311c2014-03-17 12:00:47 -07002458String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2459{
2460 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2461 return String8("a2dp_sink_address=")+address;
2462 }
2463 return address;
2464}
2465
Eric Laurente0720872014-03-11 09:30:41 -07002466status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002467 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002468 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002469 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002470{
2471 AudioOutputDescriptor *desc;
2472
Eric Laurent3b73df72014-03-11 09:06:29 -07002473 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002474 // first list already open outputs that can be routed to this device
2475 for (size_t i = 0; i < mOutputs.size(); i++) {
2476 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002477 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002478 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2479 outputs.add(mOutputs.keyAt(i));
2480 }
2481 }
2482 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002483 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002484 for (size_t i = 0; i < mHwModules.size(); i++)
2485 {
2486 if (mHwModules[i]->mHandle == 0) {
2487 continue;
2488 }
2489 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2490 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002491 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002492 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002493 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2494 }
2495 }
2496 }
2497
2498 if (profiles.isEmpty() && outputs.isEmpty()) {
2499 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2500 return BAD_VALUE;
2501 }
2502
2503 // open outputs for matching profiles if needed. Direct outputs are also opened to
2504 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2505 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002506 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002507
2508 // nothing to do if one output is already opened for this profile
2509 size_t j;
2510 for (j = 0; j < mOutputs.size(); j++) {
2511 desc = mOutputs.valueAt(j);
2512 if (!desc->isDuplicated() && desc->mProfile == profile) {
2513 break;
2514 }
2515 }
2516 if (j != mOutputs.size()) {
2517 continue;
2518 }
2519
Eric Laurent3a4311c2014-03-17 12:00:47 -07002520 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002521 desc = new AudioOutputDescriptor(profile);
2522 desc->mDevice = device;
2523 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2524 offloadInfo.sample_rate = desc->mSamplingRate;
2525 offloadInfo.format = desc->mFormat;
2526 offloadInfo.channel_mask = desc->mChannelMask;
2527
2528 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2529 &desc->mDevice,
2530 &desc->mSamplingRate,
2531 &desc->mFormat,
2532 &desc->mChannelMask,
2533 &desc->mLatency,
2534 desc->mFlags,
2535 &offloadInfo);
2536 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002537 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002538 if (!address.isEmpty()) {
2539 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002540 }
2541
Eric Laurentd4692962014-05-05 18:13:44 -07002542 // Here is where we step through and resolve any "dynamic" fields
2543 String8 reply;
2544 char *value;
2545 if (profile->mSamplingRates[0] == 0) {
2546 reply = mpClientInterface->getParameters(output,
2547 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2548 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2549 reply.string());
2550 value = strpbrk((char *)reply.string(), "=");
2551 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002552 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002553 }
Eric Laurentd4692962014-05-05 18:13:44 -07002554 }
2555 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2556 reply = mpClientInterface->getParameters(output,
2557 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2558 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2559 reply.string());
2560 value = strpbrk((char *)reply.string(), "=");
2561 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002562 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002563 }
Eric Laurentd4692962014-05-05 18:13:44 -07002564 }
2565 if (profile->mChannelMasks[0] == 0) {
2566 reply = mpClientInterface->getParameters(output,
2567 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2568 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2569 reply.string());
2570 value = strpbrk((char *)reply.string(), "=");
2571 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002572 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002573 }
Eric Laurentd4692962014-05-05 18:13:44 -07002574 }
2575 if (((profile->mSamplingRates[0] == 0) &&
2576 (profile->mSamplingRates.size() < 2)) ||
2577 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2578 (profile->mFormats.size() < 2)) ||
2579 ((profile->mChannelMasks[0] == 0) &&
2580 (profile->mChannelMasks.size() < 2))) {
2581 ALOGW("checkOutputsForDevice() direct output missing param");
2582 mpClientInterface->closeOutput(output);
2583 output = 0;
2584 } else if (profile->mSamplingRates[0] == 0) {
2585 mpClientInterface->closeOutput(output);
2586 desc->mSamplingRate = profile->mSamplingRates[1];
2587 offloadInfo.sample_rate = desc->mSamplingRate;
2588 output = mpClientInterface->openOutput(
2589 profile->mModule->mHandle,
2590 &desc->mDevice,
2591 &desc->mSamplingRate,
2592 &desc->mFormat,
2593 &desc->mChannelMask,
2594 &desc->mLatency,
2595 desc->mFlags,
2596 &offloadInfo);
2597 }
2598
2599 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002600 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002601 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2602 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002603
Eric Laurentd4692962014-05-05 18:13:44 -07002604 // set initial stream volume for device
2605 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002606
Eric Laurentd4692962014-05-05 18:13:44 -07002607 //TODO: configure audio effect output stage here
2608
2609 // open a duplicating output thread for the new output and the primary output
2610 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2611 mPrimaryOutput);
2612 if (duplicatedOutput != 0) {
2613 // add duplicated output descriptor
2614 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
2615 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2616 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2617 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2618 dupOutputDesc->mFormat = desc->mFormat;
2619 dupOutputDesc->mChannelMask = desc->mChannelMask;
2620 dupOutputDesc->mLatency = desc->mLatency;
2621 addOutput(duplicatedOutput, dupOutputDesc);
2622 applyStreamVolumes(duplicatedOutput, device, 0, true);
2623 } else {
2624 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2625 mPrimaryOutput, output);
2626 mpClientInterface->closeOutput(output);
2627 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002628 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002629 output = 0;
2630 }
Eric Laurente552edb2014-03-10 17:42:56 -07002631 }
2632 }
2633 }
2634 if (output == 0) {
2635 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2636 delete desc;
2637 profiles.removeAt(profile_index);
2638 profile_index--;
2639 } else {
2640 outputs.add(output);
2641 ALOGV("checkOutputsForDevice(): adding output %d", output);
2642 }
2643 }
2644
2645 if (profiles.isEmpty()) {
2646 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2647 return BAD_VALUE;
2648 }
Eric Laurentd4692962014-05-05 18:13:44 -07002649 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002650 // check if one opened output is not needed any more after disconnecting one device
2651 for (size_t i = 0; i < mOutputs.size(); i++) {
2652 desc = mOutputs.valueAt(i);
2653 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002654 !(desc->mProfile->mSupportedDevices.types() &
2655 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002656 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2657 outputs.add(mOutputs.keyAt(i));
2658 }
2659 }
Eric Laurentd4692962014-05-05 18:13:44 -07002660 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002661 for (size_t i = 0; i < mHwModules.size(); i++)
2662 {
2663 if (mHwModules[i]->mHandle == 0) {
2664 continue;
2665 }
2666 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2667 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002668 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002669 if (profile->mSupportedDevices.types() & device) {
2670 ALOGV("checkOutputsForDevice(): "
2671 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002672 if (profile->mSamplingRates[0] == 0) {
2673 profile->mSamplingRates.clear();
2674 profile->mSamplingRates.add(0);
2675 }
2676 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2677 profile->mFormats.clear();
2678 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2679 }
2680 if (profile->mChannelMasks[0] == 0) {
2681 profile->mChannelMasks.clear();
2682 profile->mChannelMasks.add(0);
2683 }
2684 }
2685 }
2686 }
2687 }
2688 return NO_ERROR;
2689}
2690
Eric Laurentd4692962014-05-05 18:13:44 -07002691status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2692 audio_policy_dev_state_t state,
2693 SortedVector<audio_io_handle_t>& inputs,
2694 const String8 address)
2695{
2696 AudioInputDescriptor *desc;
2697 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2698 // first list already open inputs that can be routed to this device
2699 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2700 desc = mInputs.valueAt(input_index);
2701 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2702 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2703 inputs.add(mInputs.keyAt(input_index));
2704 }
2705 }
2706
2707 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002708 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002709 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2710 {
2711 if (mHwModules[module_idx]->mHandle == 0) {
2712 continue;
2713 }
2714 for (size_t profile_index = 0;
2715 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2716 profile_index++)
2717 {
2718 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2719 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2720 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2721 profile_index, module_idx);
2722 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2723 }
2724 }
2725 }
2726
2727 if (profiles.isEmpty() && inputs.isEmpty()) {
2728 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2729 return BAD_VALUE;
2730 }
2731
2732 // open inputs for matching profiles if needed. Direct inputs are also opened to
2733 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2734 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2735
Eric Laurent1c333e22014-05-20 10:48:17 -07002736 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002737 // nothing to do if one input is already opened for this profile
2738 size_t input_index;
2739 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2740 desc = mInputs.valueAt(input_index);
2741 if (desc->mProfile == profile) {
2742 break;
2743 }
2744 }
2745 if (input_index != mInputs.size()) {
2746 continue;
2747 }
2748
2749 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2750 desc = new AudioInputDescriptor(profile);
2751 desc->mDevice = device;
2752
2753 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2754 &desc->mDevice,
2755 &desc->mSamplingRate,
2756 &desc->mFormat,
2757 &desc->mChannelMask);
2758
2759 if (input != 0) {
2760 if (!address.isEmpty()) {
2761 mpClientInterface->setParameters(input, addressToParameter(device, address));
2762 }
2763
2764 // Here is where we step through and resolve any "dynamic" fields
2765 String8 reply;
2766 char *value;
2767 if (profile->mSamplingRates[0] == 0) {
2768 reply = mpClientInterface->getParameters(input,
2769 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2770 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2771 reply.string());
2772 value = strpbrk((char *)reply.string(), "=");
2773 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002774 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002775 }
2776 }
2777 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2778 reply = mpClientInterface->getParameters(input,
2779 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2780 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2781 value = strpbrk((char *)reply.string(), "=");
2782 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002783 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002784 }
2785 }
2786 if (profile->mChannelMasks[0] == 0) {
2787 reply = mpClientInterface->getParameters(input,
2788 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2789 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2790 reply.string());
2791 value = strpbrk((char *)reply.string(), "=");
2792 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002793 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002794 }
2795 }
2796 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2797 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2798 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2799 ALOGW("checkInputsForDevice() direct input missing param");
2800 mpClientInterface->closeInput(input);
2801 input = 0;
2802 }
2803
2804 if (input != 0) {
2805 addInput(input, desc);
2806 }
2807 } // endif input != 0
2808
2809 if (input == 0) {
2810 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2811 delete desc;
2812 profiles.removeAt(profile_index);
2813 profile_index--;
2814 } else {
2815 inputs.add(input);
2816 ALOGV("checkInputsForDevice(): adding input %d", input);
2817 }
2818 } // end scan profiles
2819
2820 if (profiles.isEmpty()) {
2821 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2822 return BAD_VALUE;
2823 }
2824 } else {
2825 // Disconnect
2826 // check if one opened input is not needed any more after disconnecting one device
2827 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2828 desc = mInputs.valueAt(input_index);
2829 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2830 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2831 mInputs.keyAt(input_index));
2832 inputs.add(mInputs.keyAt(input_index));
2833 }
2834 }
2835 // Clear any profiles associated with the disconnected device.
2836 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2837 if (mHwModules[module_index]->mHandle == 0) {
2838 continue;
2839 }
2840 for (size_t profile_index = 0;
2841 profile_index < mHwModules[module_index]->mInputProfiles.size();
2842 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002843 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002844 if (profile->mSupportedDevices.types() & device) {
2845 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2846 profile_index, module_index);
2847 if (profile->mSamplingRates[0] == 0) {
2848 profile->mSamplingRates.clear();
2849 profile->mSamplingRates.add(0);
2850 }
2851 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2852 profile->mFormats.clear();
2853 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2854 }
2855 if (profile->mChannelMasks[0] == 0) {
2856 profile->mChannelMasks.clear();
2857 profile->mChannelMasks.add(0);
2858 }
2859 }
2860 }
2861 }
2862 } // end disconnect
2863
2864 return NO_ERROR;
2865}
2866
2867
Eric Laurente0720872014-03-11 09:30:41 -07002868void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002869{
2870 ALOGV("closeOutput(%d)", output);
2871
2872 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2873 if (outputDesc == NULL) {
2874 ALOGW("closeOutput() unknown output %d", output);
2875 return;
2876 }
2877
2878 // look for duplicated outputs connected to the output being removed.
2879 for (size_t i = 0; i < mOutputs.size(); i++) {
2880 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2881 if (dupOutputDesc->isDuplicated() &&
2882 (dupOutputDesc->mOutput1 == outputDesc ||
2883 dupOutputDesc->mOutput2 == outputDesc)) {
2884 AudioOutputDescriptor *outputDesc2;
2885 if (dupOutputDesc->mOutput1 == outputDesc) {
2886 outputDesc2 = dupOutputDesc->mOutput2;
2887 } else {
2888 outputDesc2 = dupOutputDesc->mOutput1;
2889 }
2890 // As all active tracks on duplicated output will be deleted,
2891 // and as they were also referenced on the other output, the reference
2892 // count for their stream type must be adjusted accordingly on
2893 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07002894 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07002895 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07002896 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07002897 }
2898 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2899 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2900
2901 mpClientInterface->closeOutput(duplicatedOutput);
2902 delete mOutputs.valueFor(duplicatedOutput);
2903 mOutputs.removeItem(duplicatedOutput);
2904 }
2905 }
2906
2907 AudioParameter param;
2908 param.add(String8("closing"), String8("true"));
2909 mpClientInterface->setParameters(output, param.toString());
2910
2911 mpClientInterface->closeOutput(output);
2912 delete outputDesc;
2913 mOutputs.removeItem(output);
2914 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002915 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002916}
2917
Eric Laurente0720872014-03-11 09:30:41 -07002918SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07002919 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2920{
2921 SortedVector<audio_io_handle_t> outputs;
2922
2923 ALOGVV("getOutputsForDevice() device %04x", device);
2924 for (size_t i = 0; i < openOutputs.size(); i++) {
2925 ALOGVV("output %d isDuplicated=%d device=%04x",
2926 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2927 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2928 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2929 outputs.add(openOutputs.keyAt(i));
2930 }
2931 }
2932 return outputs;
2933}
2934
Eric Laurente0720872014-03-11 09:30:41 -07002935bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07002936 SortedVector<audio_io_handle_t>& outputs2)
2937{
2938 if (outputs1.size() != outputs2.size()) {
2939 return false;
2940 }
2941 for (size_t i = 0; i < outputs1.size(); i++) {
2942 if (outputs1[i] != outputs2[i]) {
2943 return false;
2944 }
2945 }
2946 return true;
2947}
2948
Eric Laurente0720872014-03-11 09:30:41 -07002949void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07002950{
2951 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2952 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2953 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2954 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2955
2956 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2957 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2958 strategy, srcOutputs[0], dstOutputs[0]);
2959 // mute strategy while moving tracks from one output to another
2960 for (size_t i = 0; i < srcOutputs.size(); i++) {
2961 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2962 if (desc->isStrategyActive(strategy)) {
2963 setStrategyMute(strategy, true, srcOutputs[i]);
2964 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2965 }
2966 }
2967
2968 // Move effects associated to this strategy from previous output to new output
2969 if (strategy == STRATEGY_MEDIA) {
2970 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2971 SortedVector<audio_io_handle_t> moved;
2972 for (size_t i = 0; i < mEffects.size(); i++) {
2973 EffectDescriptor *desc = mEffects.valueAt(i);
2974 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2975 desc->mIo != fxOutput) {
2976 if (moved.indexOf(desc->mIo) < 0) {
2977 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2978 mEffects.keyAt(i), fxOutput);
2979 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2980 fxOutput);
2981 moved.add(desc->mIo);
2982 }
2983 desc->mIo = fxOutput;
2984 }
2985 }
2986 }
2987 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07002988 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2989 if (getStrategy((audio_stream_type_t)i) == strategy) {
2990 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07002991 }
2992 }
2993 }
2994}
2995
Eric Laurente0720872014-03-11 09:30:41 -07002996void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07002997{
2998 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2999 checkOutputForStrategy(STRATEGY_PHONE);
3000 checkOutputForStrategy(STRATEGY_SONIFICATION);
3001 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3002 checkOutputForStrategy(STRATEGY_MEDIA);
3003 checkOutputForStrategy(STRATEGY_DTMF);
3004}
3005
Eric Laurente0720872014-03-11 09:30:41 -07003006audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003007{
Eric Laurente552edb2014-03-10 17:42:56 -07003008 for (size_t i = 0; i < mOutputs.size(); i++) {
3009 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
3010 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3011 return mOutputs.keyAt(i);
3012 }
3013 }
3014
3015 return 0;
3016}
3017
Eric Laurente0720872014-03-11 09:30:41 -07003018void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003019{
Eric Laurente552edb2014-03-10 17:42:56 -07003020 audio_io_handle_t a2dpOutput = getA2dpOutput();
3021 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003022 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003023 return;
3024 }
3025
Eric Laurent3a4311c2014-03-17 12:00:47 -07003026 bool isScoConnected =
3027 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003028 // suspend A2DP output if:
3029 // (NOT already suspended) &&
3030 // ((SCO device is connected &&
3031 // (forced usage for communication || for record is SCO))) ||
3032 // (phone state is ringing || in call)
3033 //
3034 // restore A2DP output if:
3035 // (Already suspended) &&
3036 // ((SCO device is NOT connected ||
3037 // (forced usage NOT for communication && NOT for record is SCO))) &&
3038 // (phone state is NOT ringing && NOT in call)
3039 //
3040 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003041 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003042 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3043 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3044 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3045 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003046
3047 mpClientInterface->restoreOutput(a2dpOutput);
3048 mA2dpSuspended = false;
3049 }
3050 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003051 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003052 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3053 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3054 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3055 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003056
3057 mpClientInterface->suspendOutput(a2dpOutput);
3058 mA2dpSuspended = true;
3059 }
3060 }
3061}
3062
Eric Laurent1c333e22014-05-20 10:48:17 -07003063audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003064{
3065 audio_devices_t device = AUDIO_DEVICE_NONE;
3066
3067 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003068
3069 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3070 if (index >= 0) {
3071 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3072 if (patchDesc->mUid != mUidCached) {
3073 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3074 outputDesc->device(), outputDesc->mPatchHandle);
3075 return outputDesc->device();
3076 }
3077 }
3078
Eric Laurente552edb2014-03-10 17:42:56 -07003079 // check the following by order of priority to request a routing change if necessary:
3080 // 1: the strategy enforced audible is active on the output:
3081 // use device for strategy enforced audible
3082 // 2: we are in call or the strategy phone is active on the output:
3083 // use device for strategy phone
3084 // 3: the strategy sonification is active on the output:
3085 // use device for strategy sonification
3086 // 4: the strategy "respectful" sonification is active on the output:
3087 // use device for strategy "respectful" sonification
3088 // 5: the strategy media is active on the output:
3089 // use device for strategy media
3090 // 6: the strategy DTMF is active on the output:
3091 // use device for strategy DTMF
3092 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3093 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3094 } else if (isInCall() ||
3095 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3096 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3097 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3098 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3099 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3100 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3101 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3102 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3103 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3104 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3105 }
3106
Eric Laurent1c333e22014-05-20 10:48:17 -07003107 ALOGV("getNewOutputDevice() selected device %x", device);
3108 return device;
3109}
3110
3111audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3112{
3113 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003114
3115 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3116 if (index >= 0) {
3117 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3118 if (patchDesc->mUid != mUidCached) {
3119 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3120 inputDesc->mDevice, inputDesc->mPatchHandle);
3121 return inputDesc->mDevice;
3122 }
3123 }
3124
Eric Laurent1c333e22014-05-20 10:48:17 -07003125 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3126
3127 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003128 return device;
3129}
3130
Eric Laurente0720872014-03-11 09:30:41 -07003131uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003132 return (uint32_t)getStrategy(stream);
3133}
3134
Eric Laurente0720872014-03-11 09:30:41 -07003135audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003136 // By checking the range of stream before calling getStrategy, we avoid
3137 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3138 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003139 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003140 return AUDIO_DEVICE_NONE;
3141 }
3142 audio_devices_t devices;
3143 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3144 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3145 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3146 for (size_t i = 0; i < outputs.size(); i++) {
3147 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
3148 if (outputDesc->isStrategyActive(strategy)) {
3149 devices = outputDesc->device();
3150 break;
3151 }
Eric Laurente552edb2014-03-10 17:42:56 -07003152 }
3153 return devices;
3154}
3155
Eric Laurente0720872014-03-11 09:30:41 -07003156AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003157 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003158 // stream to strategy mapping
3159 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003160 case AUDIO_STREAM_VOICE_CALL:
3161 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003162 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003163 case AUDIO_STREAM_RING:
3164 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003165 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003166 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003167 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003168 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003169 return STRATEGY_DTMF;
3170 default:
3171 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003172 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003173 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3174 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003175 case AUDIO_STREAM_TTS:
3176 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003177 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003178 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003179 return STRATEGY_ENFORCED_AUDIBLE;
3180 }
3181}
3182
Eric Laurente0720872014-03-11 09:30:41 -07003183void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003184 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003185 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003186 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3187 updateDevicesAndOutputs();
3188 break;
3189 default:
3190 break;
3191 }
3192}
3193
Eric Laurente0720872014-03-11 09:30:41 -07003194audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003195 bool fromCache)
3196{
3197 uint32_t device = AUDIO_DEVICE_NONE;
3198
3199 if (fromCache) {
3200 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3201 strategy, mDeviceForStrategy[strategy]);
3202 return mDeviceForStrategy[strategy];
3203 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003204 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003205 switch (strategy) {
3206
3207 case STRATEGY_SONIFICATION_RESPECTFUL:
3208 if (isInCall()) {
3209 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003210 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003211 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3212 // while media is playing on a remote device, use the the sonification behavior.
3213 // Note that we test this usecase before testing if media is playing because
3214 // the isStreamActive() method only informs about the activity of a stream, not
3215 // if it's for local playback. Note also that we use the same delay between both tests
3216 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003217 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003218 // while media is playing (or has recently played), use the same device
3219 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3220 } else {
3221 // when media is not playing anymore, fall back on the sonification behavior
3222 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3223 }
3224
3225 break;
3226
3227 case STRATEGY_DTMF:
3228 if (!isInCall()) {
3229 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3230 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3231 break;
3232 }
3233 // when in call, DTMF and PHONE strategies follow the same rules
3234 // FALL THROUGH
3235
3236 case STRATEGY_PHONE:
3237 // for phone strategy, we first consider the forced use and then the available devices by order
3238 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003239 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3240 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003241 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003242 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003243 if (device) break;
3244 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003245 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003246 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003247 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003248 if (device) break;
3249 // if SCO device is requested but no SCO device is available, fall back to default case
3250 // FALL THROUGH
3251
3252 default: // FORCE_NONE
3253 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003254 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003255 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003256 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003257 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003258 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003259 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003260 if (device) break;
3261 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003262 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003263 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003264 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003265 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003266 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003267 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003268 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003269 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003270 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003271 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003272 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003273 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003274 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003275 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003276 if (device) break;
3277 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003278 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003279 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003280 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003281 if (device == AUDIO_DEVICE_NONE) {
3282 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3283 }
3284 break;
3285
Eric Laurent3b73df72014-03-11 09:06:29 -07003286 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003287 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3288 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003289 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003290 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003291 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003292 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003293 if (device) break;
3294 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003295 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003296 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003297 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003298 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003299 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003300 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003301 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003302 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003303 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003304 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003305 if (device) break;
3306 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003307 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003308 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003309 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003310 if (device == AUDIO_DEVICE_NONE) {
3311 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3312 }
3313 break;
3314 }
3315 break;
3316
3317 case STRATEGY_SONIFICATION:
3318
3319 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3320 // handleIncallSonification().
3321 if (isInCall()) {
3322 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3323 break;
3324 }
3325 // FALL THROUGH
3326
3327 case STRATEGY_ENFORCED_AUDIBLE:
3328 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3329 // except:
3330 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3331 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3332
3333 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003334 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003335 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003336 if (device == AUDIO_DEVICE_NONE) {
3337 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3338 }
3339 }
3340 // The second device used for sonification is the same as the device used by media strategy
3341 // FALL THROUGH
3342
3343 case STRATEGY_MEDIA: {
3344 uint32_t device2 = AUDIO_DEVICE_NONE;
3345 if (strategy != STRATEGY_SONIFICATION) {
3346 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003347 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003348 }
3349 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003350 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003351 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003352 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003353 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003354 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003355 }
3356 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003357 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003358 }
3359 }
3360 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003361 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003362 }
3363 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003364 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003365 }
3366 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003367 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003368 }
3369 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003370 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003371 }
3372 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003373 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003374 }
3375 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3376 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003377 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003378 }
3379 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003380 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003381 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003382 }
3383 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003384 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003385 }
3386
3387 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3388 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3389 device |= device2;
3390 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003391 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003392 if (device == AUDIO_DEVICE_NONE) {
3393 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3394 }
3395 } break;
3396
3397 default:
3398 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3399 break;
3400 }
3401
3402 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3403 return device;
3404}
3405
Eric Laurente0720872014-03-11 09:30:41 -07003406void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003407{
3408 for (int i = 0; i < NUM_STRATEGIES; i++) {
3409 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3410 }
3411 mPreviousOutputs = mOutputs;
3412}
3413
Eric Laurente0720872014-03-11 09:30:41 -07003414uint32_t AudioPolicyManager::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003415 audio_devices_t prevDevice,
3416 uint32_t delayMs)
3417{
3418 // mute/unmute strategies using an incompatible device combination
3419 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3420 // if unmuting, unmute only after the specified delay
3421 if (outputDesc->isDuplicated()) {
3422 return 0;
3423 }
3424
3425 uint32_t muteWaitMs = 0;
3426 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003427 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003428
3429 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3430 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3431 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3432 bool doMute = false;
3433
3434 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3435 doMute = true;
3436 outputDesc->mStrategyMutedByDevice[i] = true;
3437 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3438 doMute = true;
3439 outputDesc->mStrategyMutedByDevice[i] = false;
3440 }
Eric Laurent99401132014-05-07 19:48:15 -07003441 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003442 for (size_t j = 0; j < mOutputs.size(); j++) {
3443 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
3444 // skip output if it does not share any device with current output
3445 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3446 == AUDIO_DEVICE_NONE) {
3447 continue;
3448 }
3449 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3450 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3451 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3452 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3453 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003454 if (mute) {
3455 // FIXME: should not need to double latency if volume could be applied
3456 // immediately by the audioflinger mixer. We must account for the delay
3457 // between now and the next time the audioflinger thread for this output
3458 // will process a buffer (which corresponds to one buffer size,
3459 // usually 1/2 or 1/4 of the latency).
3460 if (muteWaitMs < desc->latency() * 2) {
3461 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003462 }
3463 }
3464 }
3465 }
3466 }
3467 }
3468
Eric Laurent99401132014-05-07 19:48:15 -07003469 // temporary mute output if device selection changes to avoid volume bursts due to
3470 // different per device volumes
3471 if (outputDesc->isActive() && (device != prevDevice)) {
3472 if (muteWaitMs < outputDesc->latency() * 2) {
3473 muteWaitMs = outputDesc->latency() * 2;
3474 }
3475 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3476 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003477 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003478 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003479 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003480 muteWaitMs *2, device);
3481 }
3482 }
3483 }
3484
Eric Laurente552edb2014-03-10 17:42:56 -07003485 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3486 if (muteWaitMs > delayMs) {
3487 muteWaitMs -= delayMs;
3488 usleep(muteWaitMs * 1000);
3489 return muteWaitMs;
3490 }
3491 return 0;
3492}
3493
Eric Laurente0720872014-03-11 09:30:41 -07003494uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003495 audio_devices_t device,
3496 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003497 int delayMs,
3498 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003499{
3500 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
3501 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3502 AudioParameter param;
3503 uint32_t muteWaitMs;
3504
3505 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003506 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3507 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003508 return muteWaitMs;
3509 }
3510 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3511 // output profile
3512 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003513 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003514 return 0;
3515 }
3516
3517 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003518 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003519
3520 audio_devices_t prevDevice = outputDesc->mDevice;
3521
3522 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3523
3524 if (device != AUDIO_DEVICE_NONE) {
3525 outputDesc->mDevice = device;
3526 }
3527 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3528
3529 // Do not change the routing if:
3530 // - the requested device is AUDIO_DEVICE_NONE
3531 // - the requested device is the same as current device and force is not specified.
3532 // Doing this check here allows the caller to call setOutputDevice() without conditions
3533 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3534 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3535 return muteWaitMs;
3536 }
3537
3538 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003539
Eric Laurente552edb2014-03-10 17:42:56 -07003540 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003541 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003542 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003543 } else {
3544 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3545 if (!deviceList.isEmpty()) {
3546 struct audio_patch patch;
3547 outputDesc->toAudioPortConfig(&patch.sources[0]);
3548 patch.num_sources = 1;
3549 patch.num_sinks = 0;
3550 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3551 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003552 patch.num_sinks++;
3553 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003554 ssize_t index;
3555 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3556 index = mAudioPatches.indexOfKey(*patchHandle);
3557 } else {
3558 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3559 }
3560 sp< AudioPatch> patchDesc;
3561 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3562 if (index >= 0) {
3563 patchDesc = mAudioPatches.valueAt(index);
3564 afPatchHandle = patchDesc->mAfPatchHandle;
3565 }
3566
Eric Laurent1c333e22014-05-20 10:48:17 -07003567 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003568 &afPatchHandle,
3569 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003570 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3571 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003572 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003573 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003574 if (index < 0) {
3575 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3576 &patch, mUidCached);
3577 addAudioPatch(patchDesc->mHandle, patchDesc);
3578 } else {
3579 patchDesc->mPatch = patch;
3580 }
3581 patchDesc->mAfPatchHandle = afPatchHandle;
3582 patchDesc->mUid = mUidCached;
3583 if (patchHandle) {
3584 *patchHandle = patchDesc->mHandle;
3585 }
3586 outputDesc->mPatchHandle = patchDesc->mHandle;
3587 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003588 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003589 }
3590 }
3591 }
Eric Laurente552edb2014-03-10 17:42:56 -07003592
3593 // update stream volumes according to new device
3594 applyStreamVolumes(output, device, delayMs);
3595
3596 return muteWaitMs;
3597}
3598
Eric Laurent1c333e22014-05-20 10:48:17 -07003599status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003600 int delayMs,
3601 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003602{
3603 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003604 ssize_t index;
3605 if (patchHandle) {
3606 index = mAudioPatches.indexOfKey(*patchHandle);
3607 } else {
3608 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3609 }
3610 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003611 return INVALID_OPERATION;
3612 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003613 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3614 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003615 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3616 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003617 removeAudioPatch(patchDesc->mHandle);
3618 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003619 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003620 return status;
3621}
3622
3623status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3624 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003625 bool force,
3626 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003627{
3628 status_t status = NO_ERROR;
3629
3630 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
3631 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3632 inputDesc->mDevice = device;
3633
3634 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3635 if (!deviceList.isEmpty()) {
3636 struct audio_patch patch;
3637 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3638 patch.num_sinks = 1;
3639 //only one input device for now
3640 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003641 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003642 ssize_t index;
3643 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3644 index = mAudioPatches.indexOfKey(*patchHandle);
3645 } else {
3646 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3647 }
3648 sp< AudioPatch> patchDesc;
3649 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3650 if (index >= 0) {
3651 patchDesc = mAudioPatches.valueAt(index);
3652 afPatchHandle = patchDesc->mAfPatchHandle;
3653 }
3654
Eric Laurent1c333e22014-05-20 10:48:17 -07003655 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003656 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003657 0);
3658 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003659 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003660 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003661 if (index < 0) {
3662 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3663 &patch, mUidCached);
3664 addAudioPatch(patchDesc->mHandle, patchDesc);
3665 } else {
3666 patchDesc->mPatch = patch;
3667 }
3668 patchDesc->mAfPatchHandle = afPatchHandle;
3669 patchDesc->mUid = mUidCached;
3670 if (patchHandle) {
3671 *patchHandle = patchDesc->mHandle;
3672 }
3673 inputDesc->mPatchHandle = patchDesc->mHandle;
3674 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003675 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003676 }
3677 }
3678 }
3679 return status;
3680}
3681
Eric Laurent6a94d692014-05-20 11:18:06 -07003682status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3683 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003684{
3685 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003686 ssize_t index;
3687 if (patchHandle) {
3688 index = mAudioPatches.indexOfKey(*patchHandle);
3689 } else {
3690 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3691 }
3692 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003693 return INVALID_OPERATION;
3694 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003695 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3696 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003697 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3698 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003699 removeAudioPatch(patchDesc->mHandle);
3700 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003701 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003702 return status;
3703}
3704
3705sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003706 uint32_t samplingRate,
3707 audio_format_t format,
3708 audio_channel_mask_t channelMask)
3709{
3710 // Choose an input profile based on the requested capture parameters: select the first available
3711 // profile supporting all requested parameters.
3712
3713 for (size_t i = 0; i < mHwModules.size(); i++)
3714 {
3715 if (mHwModules[i]->mHandle == 0) {
3716 continue;
3717 }
3718 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3719 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003720 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003721 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003722 if (profile->isCompatibleProfile(device, samplingRate, format,
3723 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3724 return profile;
3725 }
3726 }
3727 }
3728 return NULL;
3729}
3730
Eric Laurente0720872014-03-11 09:30:41 -07003731audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003732{
3733 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003734 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3735 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003736 switch (inputSource) {
3737 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003738 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003739 device = AUDIO_DEVICE_IN_VOICE_CALL;
3740 break;
3741 }
3742 // FALL THROUGH
3743
3744 case AUDIO_SOURCE_DEFAULT:
3745 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003746 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3747 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3748 break;
3749 }
3750 // FALL THROUGH
3751
Eric Laurente552edb2014-03-10 17:42:56 -07003752 case AUDIO_SOURCE_VOICE_RECOGNITION:
3753 case AUDIO_SOURCE_HOTWORD:
3754 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003755 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003756 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003757 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003758 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003759 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003760 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3761 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003762 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003763 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3764 }
3765 break;
3766 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003767 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003768 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003769 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003770 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3771 }
3772 break;
3773 case AUDIO_SOURCE_VOICE_DOWNLINK:
3774 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003775 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003776 device = AUDIO_DEVICE_IN_VOICE_CALL;
3777 }
3778 break;
3779 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003780 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003781 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3782 }
3783 break;
3784 default:
3785 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3786 break;
3787 }
3788 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3789 return device;
3790}
3791
Eric Laurente0720872014-03-11 09:30:41 -07003792bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003793{
3794 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3795 device &= ~AUDIO_DEVICE_BIT_IN;
3796 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3797 return true;
3798 }
3799 return false;
3800}
3801
Eric Laurente0720872014-03-11 09:30:41 -07003802audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003803{
3804 for (size_t i = 0; i < mInputs.size(); i++) {
3805 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
3806 if ((input_descriptor->mRefCount > 0)
3807 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3808 return mInputs.keyAt(i);
3809 }
3810 }
3811 return 0;
3812}
3813
3814
Eric Laurente0720872014-03-11 09:30:41 -07003815audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003816{
3817 if (device == AUDIO_DEVICE_NONE) {
3818 // this happens when forcing a route update and no track is active on an output.
3819 // In this case the returned category is not important.
3820 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003821 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003822 // Multiple device selection is either:
3823 // - speaker + one other device: give priority to speaker in this case.
3824 // - one A2DP device + another device: happens with duplicated output. In this case
3825 // retain the device on the A2DP output as the other must not correspond to an active
3826 // selection if not the speaker.
3827 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3828 device = AUDIO_DEVICE_OUT_SPEAKER;
3829 } else {
3830 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3831 }
3832 }
3833
Eric Laurent3b73df72014-03-11 09:06:29 -07003834 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003835 "getDeviceForVolume() invalid device combination: %08x",
3836 device);
3837
3838 return device;
3839}
3840
Eric Laurente0720872014-03-11 09:30:41 -07003841AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003842{
3843 switch(getDeviceForVolume(device)) {
3844 case AUDIO_DEVICE_OUT_EARPIECE:
3845 return DEVICE_CATEGORY_EARPIECE;
3846 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3847 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3848 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3849 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3850 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3851 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3852 return DEVICE_CATEGORY_HEADSET;
3853 case AUDIO_DEVICE_OUT_SPEAKER:
3854 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3855 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3856 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3857 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3858 case AUDIO_DEVICE_OUT_USB_DEVICE:
3859 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3860 default:
3861 return DEVICE_CATEGORY_SPEAKER;
3862 }
3863}
3864
Eric Laurente0720872014-03-11 09:30:41 -07003865float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003866 int indexInUi)
3867{
3868 device_category deviceCategory = getDeviceCategory(device);
3869 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3870
3871 // the volume index in the UI is relative to the min and max volume indices for this stream type
3872 int nbSteps = 1 + curve[VOLMAX].mIndex -
3873 curve[VOLMIN].mIndex;
3874 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3875 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3876
3877 // find what part of the curve this index volume belongs to, or if it's out of bounds
3878 int segment = 0;
3879 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3880 return 0.0f;
3881 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3882 segment = 0;
3883 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3884 segment = 1;
3885 } else if (volIdx <= curve[VOLMAX].mIndex) {
3886 segment = 2;
3887 } else { // out of bounds
3888 return 1.0f;
3889 }
3890
3891 // linear interpolation in the attenuation table in dB
3892 float decibels = curve[segment].mDBAttenuation +
3893 ((float)(volIdx - curve[segment].mIndex)) *
3894 ( (curve[segment+1].mDBAttenuation -
3895 curve[segment].mDBAttenuation) /
3896 ((float)(curve[segment+1].mIndex -
3897 curve[segment].mIndex)) );
3898
3899 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3900
3901 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3902 curve[segment].mIndex, volIdx,
3903 curve[segment+1].mIndex,
3904 curve[segment].mDBAttenuation,
3905 decibels,
3906 curve[segment+1].mDBAttenuation,
3907 amplification);
3908
3909 return amplification;
3910}
3911
Eric Laurente0720872014-03-11 09:30:41 -07003912const AudioPolicyManager::VolumeCurvePoint
3913 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003914 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3915};
3916
Eric Laurente0720872014-03-11 09:30:41 -07003917const AudioPolicyManager::VolumeCurvePoint
3918 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003919 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3920};
3921
Eric Laurente0720872014-03-11 09:30:41 -07003922const AudioPolicyManager::VolumeCurvePoint
3923 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003924 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3925};
3926
Eric Laurente0720872014-03-11 09:30:41 -07003927const AudioPolicyManager::VolumeCurvePoint
3928 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003929 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3930};
3931
Eric Laurente0720872014-03-11 09:30:41 -07003932const AudioPolicyManager::VolumeCurvePoint
3933 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003934 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3935};
3936
3937// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3938// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3939// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3940// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3941
Eric Laurente0720872014-03-11 09:30:41 -07003942const AudioPolicyManager::VolumeCurvePoint
3943 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003944 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3945};
3946
Eric Laurente0720872014-03-11 09:30:41 -07003947const AudioPolicyManager::VolumeCurvePoint
3948 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003949 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3950};
3951
Eric Laurente0720872014-03-11 09:30:41 -07003952const AudioPolicyManager::VolumeCurvePoint
3953 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003954 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3955};
3956
Eric Laurente0720872014-03-11 09:30:41 -07003957const AudioPolicyManager::VolumeCurvePoint
3958 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003959 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3960};
3961
Eric Laurente0720872014-03-11 09:30:41 -07003962const AudioPolicyManager::VolumeCurvePoint
3963 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003964 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3965};
3966
Eric Laurente0720872014-03-11 09:30:41 -07003967const AudioPolicyManager::VolumeCurvePoint
3968 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
3969 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003970 { // AUDIO_STREAM_VOICE_CALL
3971 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3972 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3973 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3974 },
3975 { // AUDIO_STREAM_SYSTEM
3976 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3977 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3978 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3979 },
3980 { // AUDIO_STREAM_RING
3981 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3982 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3983 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3984 },
3985 { // AUDIO_STREAM_MUSIC
3986 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3987 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3988 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3989 },
3990 { // AUDIO_STREAM_ALARM
3991 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3992 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3993 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3994 },
3995 { // AUDIO_STREAM_NOTIFICATION
3996 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3997 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3998 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3999 },
4000 { // AUDIO_STREAM_BLUETOOTH_SCO
4001 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4002 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4003 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4004 },
4005 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4006 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4007 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4008 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4009 },
4010 { // AUDIO_STREAM_DTMF
4011 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4012 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4013 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4014 },
4015 { // AUDIO_STREAM_TTS
4016 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4017 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4018 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4019 },
4020};
4021
Eric Laurente0720872014-03-11 09:30:41 -07004022void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004023{
4024 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4025 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4026 mStreams[i].mVolumeCurve[j] =
4027 sVolumeProfiles[i][j];
4028 }
4029 }
4030
4031 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4032 if (mSpeakerDrcEnabled) {
4033 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4034 sDefaultSystemVolumeCurveDrc;
4035 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4036 sSpeakerSonificationVolumeCurveDrc;
4037 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4038 sSpeakerSonificationVolumeCurveDrc;
4039 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4040 sSpeakerSonificationVolumeCurveDrc;
4041 }
4042}
4043
Eric Laurente0720872014-03-11 09:30:41 -07004044float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004045 int index,
4046 audio_io_handle_t output,
4047 audio_devices_t device)
4048{
4049 float volume = 1.0;
4050 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
4051 StreamDescriptor &streamDesc = mStreams[stream];
4052
4053 if (device == AUDIO_DEVICE_NONE) {
4054 device = outputDesc->device();
4055 }
4056
4057 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004058 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004059 index != mStreams[stream].mIndexMin &&
4060 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
4061 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
4062 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
4063 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
4064 return 1.0;
4065 }
4066
4067 volume = volIndexToAmpl(device, streamDesc, index);
4068
4069 // if a headset is connected, apply the following rules to ring tones and notifications
4070 // to avoid sound level bursts in user's ears:
4071 // - always attenuate ring tones and notifications volume by 6dB
4072 // - if music is playing, always limit the volume to current music volume,
4073 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004074 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004075 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4076 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4077 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4078 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4079 ((stream_strategy == STRATEGY_SONIFICATION)
4080 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004081 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004082 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004083 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004084 streamDesc.mCanBeMuted) {
4085 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4086 // when the phone is ringing we must consider that music could have been paused just before
4087 // by the music application and behave as if music was active if the last music track was
4088 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004089 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004090 mLimitRingtoneVolume) {
4091 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004092 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4093 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004094 output,
4095 musicDevice);
4096 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4097 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4098 if (volume > minVol) {
4099 volume = minVol;
4100 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4101 }
4102 }
4103 }
4104
4105 return volume;
4106}
4107
Eric Laurente0720872014-03-11 09:30:41 -07004108status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004109 int index,
4110 audio_io_handle_t output,
4111 audio_devices_t device,
4112 int delayMs,
4113 bool force)
4114{
4115
4116 // do not change actual stream volume if the stream is muted
4117 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4118 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4119 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4120 return NO_ERROR;
4121 }
4122
4123 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004124 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4125 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4126 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4127 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004128 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004129 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004130 return INVALID_OPERATION;
4131 }
4132
4133 float volume = computeVolume(stream, index, output, device);
4134 // We actually change the volume if:
4135 // - the float value returned by computeVolume() changed
4136 // - the force flag is set
4137 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4138 force) {
4139 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4140 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4141 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4142 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004143 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4144 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004145 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004146 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004147 }
4148
Eric Laurent3b73df72014-03-11 09:06:29 -07004149 if (stream == AUDIO_STREAM_VOICE_CALL ||
4150 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004151 float voiceVolume;
4152 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004153 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004154 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4155 } else {
4156 voiceVolume = 1.0;
4157 }
4158
4159 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4160 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4161 mLastVoiceVolume = voiceVolume;
4162 }
4163 }
4164
4165 return NO_ERROR;
4166}
4167
Eric Laurente0720872014-03-11 09:30:41 -07004168void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004169 audio_devices_t device,
4170 int delayMs,
4171 bool force)
4172{
4173 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4174
Eric Laurent3b73df72014-03-11 09:06:29 -07004175 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4176 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004177 mStreams[stream].getVolumeIndex(device),
4178 output,
4179 device,
4180 delayMs,
4181 force);
4182 }
4183}
4184
Eric Laurente0720872014-03-11 09:30:41 -07004185void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004186 bool on,
4187 audio_io_handle_t output,
4188 int delayMs,
4189 audio_devices_t device)
4190{
4191 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004192 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4193 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4194 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004195 }
4196 }
4197}
4198
Eric Laurente0720872014-03-11 09:30:41 -07004199void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004200 bool on,
4201 audio_io_handle_t output,
4202 int delayMs,
4203 audio_devices_t device)
4204{
4205 StreamDescriptor &streamDesc = mStreams[stream];
4206 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
4207 if (device == AUDIO_DEVICE_NONE) {
4208 device = outputDesc->device();
4209 }
4210
4211 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4212 stream, on, output, outputDesc->mMuteCount[stream], device);
4213
4214 if (on) {
4215 if (outputDesc->mMuteCount[stream] == 0) {
4216 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004217 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4218 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004219 checkAndSetVolume(stream, 0, output, device, delayMs);
4220 }
4221 }
4222 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4223 outputDesc->mMuteCount[stream]++;
4224 } else {
4225 if (outputDesc->mMuteCount[stream] == 0) {
4226 ALOGV("setStreamMute() unmuting non muted stream!");
4227 return;
4228 }
4229 if (--outputDesc->mMuteCount[stream] == 0) {
4230 checkAndSetVolume(stream,
4231 streamDesc.getVolumeIndex(device),
4232 output,
4233 device,
4234 delayMs);
4235 }
4236 }
4237}
4238
Eric Laurente0720872014-03-11 09:30:41 -07004239void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004240 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004241{
4242 // if the stream pertains to sonification strategy and we are in call we must
4243 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4244 // in the device used for phone strategy and play the tone if the selected device does not
4245 // interfere with the device used for phone strategy
4246 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4247 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004248 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004249 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4250 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
4251 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
4252 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4253 stream, starting, outputDesc->mDevice, stateChange);
4254 if (outputDesc->mRefCount[stream]) {
4255 int muteCount = 1;
4256 if (stateChange) {
4257 muteCount = outputDesc->mRefCount[stream];
4258 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004259 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004260 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4261 for (int i = 0; i < muteCount; i++) {
4262 setStreamMute(stream, starting, mPrimaryOutput);
4263 }
4264 } else {
4265 ALOGV("handleIncallSonification() high visibility");
4266 if (outputDesc->device() &
4267 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4268 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4269 for (int i = 0; i < muteCount; i++) {
4270 setStreamMute(stream, starting, mPrimaryOutput);
4271 }
4272 }
4273 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004274 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4275 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004276 } else {
4277 mpClientInterface->stopTone();
4278 }
4279 }
4280 }
4281 }
4282}
4283
Eric Laurente0720872014-03-11 09:30:41 -07004284bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004285{
4286 return isStateInCall(mPhoneState);
4287}
4288
Eric Laurente0720872014-03-11 09:30:41 -07004289bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004290 return ((state == AUDIO_MODE_IN_CALL) ||
4291 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004292}
4293
Eric Laurente0720872014-03-11 09:30:41 -07004294uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004295{
4296 return MAX_EFFECTS_CPU_LOAD;
4297}
4298
Eric Laurente0720872014-03-11 09:30:41 -07004299uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004300{
4301 return MAX_EFFECTS_MEMORY;
4302}
4303
Eric Laurent6a94d692014-05-20 11:18:06 -07004304
Eric Laurente552edb2014-03-10 17:42:56 -07004305// --- AudioOutputDescriptor class implementation
4306
Eric Laurente0720872014-03-11 09:30:41 -07004307AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004308 const sp<IOProfile>& profile)
4309 : mId(0), mIoHandle(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
Eric Laurente552edb2014-03-10 17:42:56 -07004310 mChannelMask(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004311 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004312 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4313{
4314 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004315 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004316 mRefCount[i] = 0;
4317 mCurVolume[i] = -1.0;
4318 mMuteCount[i] = 0;
4319 mStopTime[i] = 0;
4320 }
4321 for (int i = 0; i < NUM_STRATEGIES; i++) {
4322 mStrategyMutedByDevice[i] = false;
4323 }
4324 if (profile != NULL) {
4325 mSamplingRate = profile->mSamplingRates[0];
4326 mFormat = profile->mFormats[0];
4327 mChannelMask = profile->mChannelMasks[0];
4328 mFlags = profile->mFlags;
4329 }
4330}
4331
Eric Laurente0720872014-03-11 09:30:41 -07004332audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004333{
4334 if (isDuplicated()) {
4335 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4336 } else {
4337 return mDevice;
4338 }
4339}
4340
Eric Laurente0720872014-03-11 09:30:41 -07004341uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004342{
4343 if (isDuplicated()) {
4344 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4345 } else {
4346 return mLatency;
4347 }
4348}
4349
Eric Laurente0720872014-03-11 09:30:41 -07004350bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurente552edb2014-03-10 17:42:56 -07004351 const AudioOutputDescriptor *outputDesc)
4352{
4353 if (isDuplicated()) {
4354 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4355 } else if (outputDesc->isDuplicated()){
4356 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4357 } else {
4358 return (mProfile->mModule == outputDesc->mProfile->mModule);
4359 }
4360}
4361
Eric Laurente0720872014-03-11 09:30:41 -07004362void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004363 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004364{
4365 // forward usage count change to attached outputs
4366 if (isDuplicated()) {
4367 mOutput1->changeRefCount(stream, delta);
4368 mOutput2->changeRefCount(stream, delta);
4369 }
4370 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004371 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4372 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004373 mRefCount[stream] = 0;
4374 return;
4375 }
4376 mRefCount[stream] += delta;
4377 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4378}
4379
Eric Laurente0720872014-03-11 09:30:41 -07004380audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004381{
4382 if (isDuplicated()) {
4383 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4384 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004385 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004386 }
4387}
4388
Eric Laurente0720872014-03-11 09:30:41 -07004389bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004390{
4391 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4392}
4393
Eric Laurente0720872014-03-11 09:30:41 -07004394bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004395 uint32_t inPastMs,
4396 nsecs_t sysTime) const
4397{
4398 if ((sysTime == 0) && (inPastMs != 0)) {
4399 sysTime = systemTime();
4400 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004401 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4402 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004403 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004404 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004405 return true;
4406 }
4407 }
4408 return false;
4409}
4410
Eric Laurente0720872014-03-11 09:30:41 -07004411bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004412 uint32_t inPastMs,
4413 nsecs_t sysTime) const
4414{
4415 if (mRefCount[stream] != 0) {
4416 return true;
4417 }
4418 if (inPastMs == 0) {
4419 return false;
4420 }
4421 if (sysTime == 0) {
4422 sysTime = systemTime();
4423 }
4424 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4425 return true;
4426 }
4427 return false;
4428}
4429
Eric Laurent1c333e22014-05-20 10:48:17 -07004430void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004431 struct audio_port_config *dstConfig,
4432 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004433{
Eric Laurent6a94d692014-05-20 11:18:06 -07004434 dstConfig->id = mId;
4435 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4436 dstConfig->type = AUDIO_PORT_TYPE_MIX;
4437 dstConfig->sample_rate = mSamplingRate;
4438 dstConfig->channel_mask = mChannelMask;
4439 dstConfig->format = mFormat;
4440 dstConfig->gain.index = -1;
4441 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
Eric Laurent1c333e22014-05-20 10:48:17 -07004442 AUDIO_PORT_CONFIG_FORMAT;
Eric Laurent6a94d692014-05-20 11:18:06 -07004443 // use supplied variable configuration parameters if any
4444 if (srcConfig != NULL) {
4445 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
4446 dstConfig->sample_rate = srcConfig->sample_rate;
4447 }
4448 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
4449 dstConfig->channel_mask = srcConfig->channel_mask;
4450 }
4451 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
4452 dstConfig->format = srcConfig->format;
4453 }
4454 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
4455 dstConfig->gain = srcConfig->gain;
4456 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
4457 }
4458 }
4459 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4460 dstConfig->ext.mix.handle = mIoHandle;
4461 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004462}
4463
4464void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4465 struct audio_port *port) const
4466{
4467 mProfile->toAudioPort(port);
4468 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004469 toAudioPortConfig(&port->active_config);
4470 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004471 port->ext.mix.handle = mIoHandle;
4472 port->ext.mix.latency_class =
4473 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4474}
Eric Laurente552edb2014-03-10 17:42:56 -07004475
Eric Laurente0720872014-03-11 09:30:41 -07004476status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004477{
4478 const size_t SIZE = 256;
4479 char buffer[SIZE];
4480 String8 result;
4481
4482 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4483 result.append(buffer);
4484 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4485 result.append(buffer);
4486 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4487 result.append(buffer);
4488 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4489 result.append(buffer);
4490 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4491 result.append(buffer);
4492 snprintf(buffer, SIZE, " Devices %08x\n", device());
4493 result.append(buffer);
4494 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4495 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004496 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4497 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4498 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004499 result.append(buffer);
4500 }
4501 write(fd, result.string(), result.size());
4502
4503 return NO_ERROR;
4504}
4505
4506// --- AudioInputDescriptor class implementation
4507
Eric Laurent1c333e22014-05-20 10:48:17 -07004508AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
4509 : mId(0), mIoHandle(0), mSamplingRate(0),
4510 mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
4511 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004512 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004513{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004514 if (profile != NULL) {
4515 mSamplingRate = profile->mSamplingRates[0];
4516 mFormat = profile->mFormats[0];
4517 mChannelMask = profile->mChannelMasks[0];
4518 }
Eric Laurente552edb2014-03-10 17:42:56 -07004519}
4520
Eric Laurent1c333e22014-05-20 10:48:17 -07004521void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004522 struct audio_port_config *dstConfig,
4523 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004524{
Eric Laurent6a94d692014-05-20 11:18:06 -07004525 dstConfig->id = mId;
4526 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4527 dstConfig->type = AUDIO_PORT_TYPE_MIX;
4528 dstConfig->sample_rate = mSamplingRate;
4529 dstConfig->channel_mask = mChannelMask;
4530 dstConfig->format = mFormat;
4531 dstConfig->gain.index = -1;
4532 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4533 AUDIO_PORT_CONFIG_FORMAT;
4534 // use supplied variable configuration parameters if any
4535 if (srcConfig != NULL) {
4536 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
4537 dstConfig->sample_rate = srcConfig->sample_rate;
4538 }
4539 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
4540 dstConfig->channel_mask = srcConfig->channel_mask;
4541 }
4542 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
4543 dstConfig->format = srcConfig->format;
4544 }
4545 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
4546 dstConfig->gain = srcConfig->gain;
4547 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
4548 }
4549 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004550}
4551
4552void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4553 struct audio_port *port) const
4554{
4555 mProfile->toAudioPort(port);
4556 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004557 toAudioPortConfig(&port->active_config);
4558 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004559 port->ext.mix.handle = mIoHandle;
4560 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4561}
4562
Eric Laurente0720872014-03-11 09:30:41 -07004563status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004564{
4565 const size_t SIZE = 256;
4566 char buffer[SIZE];
4567 String8 result;
4568
4569 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4570 result.append(buffer);
4571 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4572 result.append(buffer);
4573 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4574 result.append(buffer);
4575 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4576 result.append(buffer);
4577 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4578 result.append(buffer);
4579 write(fd, result.string(), result.size());
4580
4581 return NO_ERROR;
4582}
4583
4584// --- StreamDescriptor class implementation
4585
Eric Laurente0720872014-03-11 09:30:41 -07004586AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004587 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4588{
4589 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4590}
4591
Eric Laurente0720872014-03-11 09:30:41 -07004592int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004593{
Eric Laurente0720872014-03-11 09:30:41 -07004594 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004595 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4596 if (mIndexCur.indexOfKey(device) < 0) {
4597 device = AUDIO_DEVICE_OUT_DEFAULT;
4598 }
4599 return mIndexCur.valueFor(device);
4600}
4601
Eric Laurente0720872014-03-11 09:30:41 -07004602void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004603{
4604 const size_t SIZE = 256;
4605 char buffer[SIZE];
4606 String8 result;
4607
4608 snprintf(buffer, SIZE, "%s %02d %02d ",
4609 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4610 result.append(buffer);
4611 for (size_t i = 0; i < mIndexCur.size(); i++) {
4612 snprintf(buffer, SIZE, "%04x : %02d, ",
4613 mIndexCur.keyAt(i),
4614 mIndexCur.valueAt(i));
4615 result.append(buffer);
4616 }
4617 result.append("\n");
4618
4619 write(fd, result.string(), result.size());
4620}
4621
4622// --- EffectDescriptor class implementation
4623
Eric Laurente0720872014-03-11 09:30:41 -07004624status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004625{
4626 const size_t SIZE = 256;
4627 char buffer[SIZE];
4628 String8 result;
4629
4630 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4631 result.append(buffer);
4632 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4633 result.append(buffer);
4634 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4635 result.append(buffer);
4636 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4637 result.append(buffer);
4638 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4639 result.append(buffer);
4640 write(fd, result.string(), result.size());
4641
4642 return NO_ERROR;
4643}
4644
Eric Laurent1c333e22014-05-20 10:48:17 -07004645// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004646
Eric Laurente0720872014-03-11 09:30:41 -07004647AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07004648 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
4649{
4650}
4651
Eric Laurente0720872014-03-11 09:30:41 -07004652AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004653{
4654 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004655 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004656 }
4657 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004658 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004659 }
4660 free((void *)mName);
4661}
4662
Eric Laurente0720872014-03-11 09:30:41 -07004663void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004664{
4665 const size_t SIZE = 256;
4666 char buffer[SIZE];
4667 String8 result;
4668
4669 snprintf(buffer, SIZE, " - name: %s\n", mName);
4670 result.append(buffer);
4671 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4672 result.append(buffer);
4673 write(fd, result.string(), result.size());
4674 if (mOutputProfiles.size()) {
4675 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4676 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004677 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004678 write(fd, buffer, strlen(buffer));
4679 mOutputProfiles[i]->dump(fd);
4680 }
4681 }
4682 if (mInputProfiles.size()) {
4683 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4684 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004685 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004686 write(fd, buffer, strlen(buffer));
4687 mInputProfiles[i]->dump(fd);
4688 }
4689 }
4690}
4691
Eric Laurent1c333e22014-05-20 10:48:17 -07004692// --- AudioPort class implementation
4693
4694void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
4695{
4696 port->role = mRole;
4697 port->type = mType;
4698 unsigned int i;
4699 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
4700 port->sample_rates[i] = mSamplingRates[i];
4701 }
4702 port->num_sample_rates = i;
4703 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
4704 port->channel_masks[i] = mChannelMasks[i];
4705 }
4706 port->num_channel_masks = i;
4707 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
4708 port->formats[i] = mFormats[i];
4709 }
4710 port->num_formats = i;
4711 port->num_gains = 0;
4712}
4713
4714
4715void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
4716{
4717 char *str = strtok(name, "|");
4718
4719 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4720 // rates should be read from the output stream after it is opened for the first time
4721 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4722 mSamplingRates.add(0);
4723 return;
4724 }
4725
4726 while (str != NULL) {
4727 uint32_t rate = atoi(str);
4728 if (rate != 0) {
4729 ALOGV("loadSamplingRates() adding rate %d", rate);
4730 mSamplingRates.add(rate);
4731 }
4732 str = strtok(NULL, "|");
4733 }
4734 return;
4735}
4736
4737void AudioPolicyManager::AudioPort::loadFormats(char *name)
4738{
4739 char *str = strtok(name, "|");
4740
4741 // by convention, "0' in the first entry in mFormats indicates the supported formats
4742 // should be read from the output stream after it is opened for the first time
4743 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4744 mFormats.add(AUDIO_FORMAT_DEFAULT);
4745 return;
4746 }
4747
4748 while (str != NULL) {
4749 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4750 ARRAY_SIZE(sFormatNameToEnumTable),
4751 str);
4752 if (format != AUDIO_FORMAT_DEFAULT) {
4753 mFormats.add(format);
4754 }
4755 str = strtok(NULL, "|");
4756 }
4757 return;
4758}
4759
4760void AudioPolicyManager::AudioPort::loadInChannels(char *name)
4761{
4762 const char *str = strtok(name, "|");
4763
4764 ALOGV("loadInChannels() %s", name);
4765
4766 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4767 mChannelMasks.add(0);
4768 return;
4769 }
4770
4771 while (str != NULL) {
4772 audio_channel_mask_t channelMask =
4773 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4774 ARRAY_SIZE(sInChannelsNameToEnumTable),
4775 str);
4776 if (channelMask != 0) {
4777 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4778 mChannelMasks.add(channelMask);
4779 }
4780 str = strtok(NULL, "|");
4781 }
4782 return;
4783}
4784
4785void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
4786{
4787 const char *str = strtok(name, "|");
4788
4789 ALOGV("loadOutChannels() %s", name);
4790
4791 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4792 // masks should be read from the output stream after it is opened for the first time
4793 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4794 mChannelMasks.add(0);
4795 return;
4796 }
4797
4798 while (str != NULL) {
4799 audio_channel_mask_t channelMask =
4800 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4801 ARRAY_SIZE(sOutChannelsNameToEnumTable),
4802 str);
4803 if (channelMask != 0) {
4804 mChannelMasks.add(channelMask);
4805 }
4806 str = strtok(NULL, "|");
4807 }
4808 return;
4809}
4810
4811// --- IOProfile class implementation
4812
4813AudioPolicyManager::IOProfile::IOProfile(audio_port_role_t role, HwModule *module)
4814 : AudioPort(AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07004815{
4816}
4817
Eric Laurente0720872014-03-11 09:30:41 -07004818AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07004819{
4820}
4821
4822// checks if the IO profile is compatible with specified parameters.
4823// Sampling rate, format and channel mask must be specified in order to
4824// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07004825bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07004826 uint32_t samplingRate,
4827 audio_format_t format,
4828 audio_channel_mask_t channelMask,
4829 audio_output_flags_t flags) const
4830{
4831 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
4832 return false;
4833 }
4834
Eric Laurent3a4311c2014-03-17 12:00:47 -07004835 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07004836 return false;
4837 }
4838 if ((mFlags & flags) != flags) {
4839 return false;
4840 }
4841 size_t i;
4842 for (i = 0; i < mSamplingRates.size(); i++)
4843 {
4844 if (mSamplingRates[i] == samplingRate) {
4845 break;
4846 }
4847 }
4848 if (i == mSamplingRates.size()) {
4849 return false;
4850 }
4851 for (i = 0; i < mFormats.size(); i++)
4852 {
4853 if (mFormats[i] == format) {
4854 break;
4855 }
4856 }
4857 if (i == mFormats.size()) {
4858 return false;
4859 }
4860 for (i = 0; i < mChannelMasks.size(); i++)
4861 {
4862 if (mChannelMasks[i] == channelMask) {
4863 break;
4864 }
4865 }
4866 if (i == mChannelMasks.size()) {
4867 return false;
4868 }
4869 return true;
4870}
4871
Eric Laurente0720872014-03-11 09:30:41 -07004872void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004873{
4874 const size_t SIZE = 256;
4875 char buffer[SIZE];
4876 String8 result;
4877
4878 snprintf(buffer, SIZE, " - sampling rates: ");
4879 result.append(buffer);
4880 for (size_t i = 0; i < mSamplingRates.size(); i++) {
4881 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
4882 result.append(buffer);
4883 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
4884 }
4885
4886 snprintf(buffer, SIZE, " - channel masks: ");
4887 result.append(buffer);
4888 for (size_t i = 0; i < mChannelMasks.size(); i++) {
4889 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
4890 result.append(buffer);
4891 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
4892 }
4893
4894 snprintf(buffer, SIZE, " - formats: ");
4895 result.append(buffer);
4896 for (size_t i = 0; i < mFormats.size(); i++) {
4897 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
4898 result.append(buffer);
4899 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
4900 }
4901
Eric Laurent3a4311c2014-03-17 12:00:47 -07004902 snprintf(buffer, SIZE, " - devices:\n");
Eric Laurente552edb2014-03-10 17:42:56 -07004903 result.append(buffer);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004904 write(fd, result.string(), result.size());
4905 DeviceDescriptor::dumpHeader(fd, 6);
4906 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
4907 mSupportedDevices[i]->dump(fd, 6);
4908 }
4909
Eric Laurente552edb2014-03-10 17:42:56 -07004910 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
4911 result.append(buffer);
4912
4913 write(fd, result.string(), result.size());
4914}
4915
Eric Laurentd4692962014-05-05 18:13:44 -07004916void AudioPolicyManager::IOProfile::log()
4917{
4918 const size_t SIZE = 256;
4919 char buffer[SIZE];
4920 String8 result;
4921
4922 ALOGV(" - sampling rates: ");
4923 for (size_t i = 0; i < mSamplingRates.size(); i++) {
4924 ALOGV(" %d", mSamplingRates[i]);
4925 }
4926
4927 ALOGV(" - channel masks: ");
4928 for (size_t i = 0; i < mChannelMasks.size(); i++) {
4929 ALOGV(" 0x%04x", mChannelMasks[i]);
4930 }
4931
4932 ALOGV(" - formats: ");
4933 for (size_t i = 0; i < mFormats.size(); i++) {
4934 ALOGV(" 0x%08x", mFormats[i]);
4935 }
4936
4937 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
4938 ALOGV(" - flags: 0x%04x\n", mFlags);
4939}
4940
4941
Eric Laurent3a4311c2014-03-17 12:00:47 -07004942// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004943
Eric Laurent3a4311c2014-03-17 12:00:47 -07004944bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07004945{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004946 // Devices are considered equal if they:
4947 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
4948 // - have the same address or one device does not specify the address
4949 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07004950 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004951 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07004952 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07004953 mChannelMask == other->mChannelMask);
4954}
4955
4956void AudioPolicyManager::DeviceVector::refreshTypes()
4957{
Eric Laurent1c333e22014-05-20 10:48:17 -07004958 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004959 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004960 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004961 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004962 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004963}
4964
4965ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
4966{
4967 for(size_t i = 0; i < size(); i++) {
4968 if (item->equals(itemAt(i))) {
4969 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07004970 }
4971 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004972 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07004973}
4974
Eric Laurent3a4311c2014-03-17 12:00:47 -07004975ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07004976{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004977 ssize_t ret = indexOf(item);
4978
4979 if (ret < 0) {
4980 ret = SortedVector::add(item);
4981 if (ret >= 0) {
4982 refreshTypes();
4983 }
4984 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004986 ret = -1;
4987 }
4988 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07004989}
4990
Eric Laurent3a4311c2014-03-17 12:00:47 -07004991ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
4992{
4993 size_t i;
4994 ssize_t ret = indexOf(item);
4995
4996 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004997 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004998 } else {
4999 ret = SortedVector::removeAt(ret);
5000 if (ret >= 0) {
5001 refreshTypes();
5002 }
5003 }
5004 return ret;
5005}
5006
5007void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5008{
5009 DeviceVector deviceList;
5010
5011 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5012 types &= ~role_bit;
5013
5014 while (types) {
5015 uint32_t i = 31 - __builtin_clz(types);
5016 uint32_t type = 1 << i;
5017 types &= ~type;
5018 add(new DeviceDescriptor(type | role_bit));
5019 }
5020}
5021
Eric Laurent1c333e22014-05-20 10:48:17 -07005022sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5023 audio_devices_t type, String8 address) const
5024{
5025 sp<DeviceDescriptor> device;
5026 for (size_t i = 0; i < size(); i++) {
5027 if (itemAt(i)->mDeviceType == type) {
5028 device = itemAt(i);
5029 if (itemAt(i)->mAddress = address) {
5030 break;
5031 }
5032 }
5033 }
5034 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5035 type, address.string(), device.get());
5036 return device;
5037}
5038
Eric Laurent6a94d692014-05-20 11:18:06 -07005039sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5040 audio_port_handle_t id) const
5041{
5042 sp<DeviceDescriptor> device;
5043 for (size_t i = 0; i < size(); i++) {
5044 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%d)->mId %d", id, i, itemAt(i)->mId);
5045 if (itemAt(i)->mId == id) {
5046 device = itemAt(i);
5047 break;
5048 }
5049 }
5050 return device;
5051}
5052
Eric Laurent1c333e22014-05-20 10:48:17 -07005053AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5054 audio_devices_t type) const
5055{
5056 DeviceVector devices;
5057 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5058 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5059 devices.add(itemAt(i));
5060 type &= ~itemAt(i)->mDeviceType;
5061 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5062 itemAt(i)->mDeviceType, itemAt(i).get());
5063 }
5064 }
5065 return devices;
5066}
5067
Eric Laurent6a94d692014-05-20 11:18:06 -07005068void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5069 struct audio_port_config *dstConfig,
5070 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005071{
Eric Laurent6a94d692014-05-20 11:18:06 -07005072 dstConfig->id = mId;
5073 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005074 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
5076 dstConfig->channel_mask = mChannelMask;
5077 dstConfig->gain.index = -1;
5078 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK;
5079 // use supplied variable configuration parameters if any
5080 if (srcConfig != NULL) {
5081 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5082 dstConfig->channel_mask = srcConfig->channel_mask;
5083 }
5084 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5085 dstConfig->gain = srcConfig->gain;
5086 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5087 }
5088 }
5089 dstConfig->ext.device.type = mDeviceType;
5090 dstConfig->ext.device.hw_module = mModule->mHandle;
5091 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005092}
5093
5094void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5095{
5096 AudioPort::toAudioPort(port);
5097 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005098 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005099 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005100 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005101 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5102}
5103
Eric Laurent3a4311c2014-03-17 12:00:47 -07005104void AudioPolicyManager::DeviceDescriptor::dumpHeader(int fd, int spaces)
5105{
5106 const size_t SIZE = 256;
5107 char buffer[SIZE];
5108
5109 snprintf(buffer, SIZE, "%*s%-48s %-2s %-8s %-32s \n",
5110 spaces, "", "Type", "ID", "Cnl Mask", "Address");
5111 write(fd, buffer, strlen(buffer));
5112}
5113
5114status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces) const
5115{
5116 const size_t SIZE = 256;
5117 char buffer[SIZE];
5118
5119 snprintf(buffer, SIZE, "%*s%-48s %2d %08x %-32s \n",
5120 spaces, "",
5121 enumToString(sDeviceNameToEnumTable,
5122 ARRAY_SIZE(sDeviceNameToEnumTable),
Eric Laurent1c333e22014-05-20 10:48:17 -07005123 mDeviceType),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005124 mId, mChannelMask, mAddress.string());
5125 write(fd, buffer, strlen(buffer));
5126
5127 return NO_ERROR;
5128}
5129
5130
5131// --- audio_policy.conf file parsing
5132
Eric Laurente0720872014-03-11 09:30:41 -07005133audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005134{
5135 uint32_t flag = 0;
5136
5137 // it is OK to cast name to non const here as we are not going to use it after
5138 // strtok() modifies it
5139 char *flagName = strtok(name, "|");
5140 while (flagName != NULL) {
5141 if (strlen(flagName) != 0) {
5142 flag |= stringToEnum(sFlagNameToEnumTable,
5143 ARRAY_SIZE(sFlagNameToEnumTable),
5144 flagName);
5145 }
5146 flagName = strtok(NULL, "|");
5147 }
5148 //force direct flag if offload flag is set: offloading implies a direct output stream
5149 // and all common behaviors are driven by checking only the direct flag
5150 // this should normally be set appropriately in the policy configuration file
5151 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5152 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5153 }
5154
5155 return (audio_output_flags_t)flag;
5156}
5157
Eric Laurente0720872014-03-11 09:30:41 -07005158audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005159{
5160 uint32_t device = 0;
5161
5162 char *devName = strtok(name, "|");
5163 while (devName != NULL) {
5164 if (strlen(devName) != 0) {
5165 device |= stringToEnum(sDeviceNameToEnumTable,
5166 ARRAY_SIZE(sDeviceNameToEnumTable),
5167 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005168 }
Eric Laurente552edb2014-03-10 17:42:56 -07005169 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005170 }
Eric Laurente552edb2014-03-10 17:42:56 -07005171 return device;
5172}
5173
Eric Laurente0720872014-03-11 09:30:41 -07005174status_t AudioPolicyManager::loadInput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07005175{
5176 cnode *node = root->first_child;
5177
Eric Laurent1c333e22014-05-20 10:48:17 -07005178 sp<IOProfile> profile = new IOProfile(AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005179
5180 while (node) {
5181 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005182 profile->loadSamplingRates((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005183 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005184 profile->loadFormats((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005185 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005186 profile->loadInChannels((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005187 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005188 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07005189 }
5190 node = node->next;
5191 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005192 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07005193 "loadInput() invalid supported devices");
5194 ALOGW_IF(profile->mChannelMasks.size() == 0,
5195 "loadInput() invalid supported channel masks");
5196 ALOGW_IF(profile->mSamplingRates.size() == 0,
5197 "loadInput() invalid supported sampling rates");
5198 ALOGW_IF(profile->mFormats.size() == 0,
5199 "loadInput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005200 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07005201 (profile->mChannelMasks.size() != 0) &&
5202 (profile->mSamplingRates.size() != 0) &&
5203 (profile->mFormats.size() != 0)) {
5204
Eric Laurent3a4311c2014-03-17 12:00:47 -07005205 ALOGV("loadInput() adding input Supported Devices %04x",
5206 profile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005207
5208 module->mInputProfiles.add(profile);
5209 return NO_ERROR;
5210 } else {
Eric Laurente552edb2014-03-10 17:42:56 -07005211 return BAD_VALUE;
5212 }
5213}
5214
Eric Laurente0720872014-03-11 09:30:41 -07005215status_t AudioPolicyManager::loadOutput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07005216{
5217 cnode *node = root->first_child;
5218
Eric Laurent1c333e22014-05-20 10:48:17 -07005219 sp<IOProfile> profile = new IOProfile(AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005220
5221 while (node) {
5222 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005223 profile->loadSamplingRates((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005224 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005225 profile->loadFormats((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005226 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005227 profile->loadOutChannels((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005228 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005229 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07005230 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5231 profile->mFlags = parseFlagNames((char *)node->value);
5232 }
5233 node = node->next;
5234 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005235 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07005236 "loadOutput() invalid supported devices");
5237 ALOGW_IF(profile->mChannelMasks.size() == 0,
5238 "loadOutput() invalid supported channel masks");
5239 ALOGW_IF(profile->mSamplingRates.size() == 0,
5240 "loadOutput() invalid supported sampling rates");
5241 ALOGW_IF(profile->mFormats.size() == 0,
5242 "loadOutput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005243 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07005244 (profile->mChannelMasks.size() != 0) &&
5245 (profile->mSamplingRates.size() != 0) &&
5246 (profile->mFormats.size() != 0)) {
5247
Eric Laurent3a4311c2014-03-17 12:00:47 -07005248 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5249 profile->mSupportedDevices.types(), profile->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07005250
5251 module->mOutputProfiles.add(profile);
5252 return NO_ERROR;
5253 } else {
Eric Laurente552edb2014-03-10 17:42:56 -07005254 return BAD_VALUE;
5255 }
5256}
5257
Eric Laurente0720872014-03-11 09:30:41 -07005258void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005259{
5260 cnode *node = config_find(root, OUTPUTS_TAG);
5261 status_t status = NAME_NOT_FOUND;
5262
5263 HwModule *module = new HwModule(root->name);
5264
5265 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005266 node = node->first_child;
5267 while (node) {
5268 ALOGV("loadHwModule() loading output %s", node->name);
5269 status_t tmpStatus = loadOutput(node, module);
5270 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5271 status = tmpStatus;
5272 }
5273 node = node->next;
5274 }
5275 }
5276 node = config_find(root, INPUTS_TAG);
5277 if (node != NULL) {
5278 node = node->first_child;
5279 while (node) {
5280 ALOGV("loadHwModule() loading input %s", node->name);
5281 status_t tmpStatus = loadInput(node, module);
5282 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5283 status = tmpStatus;
5284 }
5285 node = node->next;
5286 }
5287 }
5288 if (status == NO_ERROR) {
5289 mHwModules.add(module);
5290 } else {
5291 delete module;
5292 }
5293}
5294
Eric Laurente0720872014-03-11 09:30:41 -07005295void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005296{
5297 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5298 if (node == NULL) {
5299 return;
5300 }
5301
5302 node = node->first_child;
5303 while (node) {
5304 ALOGV("loadHwModules() loading module %s", node->name);
5305 loadHwModule(node);
5306 node = node->next;
5307 }
5308}
5309
Eric Laurente0720872014-03-11 09:30:41 -07005310void AudioPolicyManager::loadGlobalConfig(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005311{
5312 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
5313 if (node == NULL) {
5314 return;
5315 }
5316 node = node->first_child;
5317 while (node) {
5318 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005319 mAvailableOutputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
5320 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5321 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005322 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005323 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005324 ARRAY_SIZE(sDeviceNameToEnumTable),
5325 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005326 if (device != AUDIO_DEVICE_NONE) {
5327 mDefaultOutputDevice = new DeviceDescriptor(device);
5328 } else {
5329 ALOGW("loadGlobalConfig() default device not specified");
5330 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005331 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005332 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005333 mAvailableInputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
5334 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005335 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5336 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5337 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
5338 }
5339 node = node->next;
5340 }
5341}
5342
Eric Laurente0720872014-03-11 09:30:41 -07005343status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005344{
5345 cnode *root;
5346 char *data;
5347
5348 data = (char *)load_file(path, NULL);
5349 if (data == NULL) {
5350 return -ENODEV;
5351 }
5352 root = config_node("", "");
5353 config_load(root, data);
5354
5355 loadGlobalConfig(root);
5356 loadHwModules(root);
5357
5358 config_free(root);
5359 free(root);
5360 free(data);
5361
5362 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5363
5364 return NO_ERROR;
5365}
5366
Eric Laurente0720872014-03-11 09:30:41 -07005367void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07005368{
5369 HwModule *module;
Eric Laurent1c333e22014-05-20 10:48:17 -07005370 sp<IOProfile> profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005371 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUILTIN_MIC);
5372 mAvailableOutputDevices.add(mDefaultOutputDevice);
5373 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005374
5375 module = new HwModule("primary");
5376
Eric Laurent1c333e22014-05-20 10:48:17 -07005377 profile = new IOProfile(AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005378 profile->mSamplingRates.add(44100);
5379 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5380 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005381 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005382 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
5383 module->mOutputProfiles.add(profile);
5384
Eric Laurent1c333e22014-05-20 10:48:17 -07005385 profile = new IOProfile(AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005386 profile->mSamplingRates.add(8000);
5387 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5388 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005389 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005390 module->mInputProfiles.add(profile);
5391
5392 mHwModules.add(module);
5393}
5394
5395}; // namespace android