blob: 7f3bdef98d5a0e91a7fae928d11f4186f29c0af0 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
33
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
39#include <hardware/audio.h>
40#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070041#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070043#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070044
Eric Laurent3b73df72014-03-11 09:06:29 -070045namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070046
47// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070048// Definitions for audio_policy.conf file parsing
49// ----------------------------------------------------------------------------
50
51struct StringToEnum {
52 const char *name;
53 uint32_t value;
54};
55
56#define STRING_TO_ENUM(string) { #string, string }
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
59const StringToEnum sDeviceNameToEnumTable[] = {
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070073 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070074 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
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
Eric Laurent1afeecb2014-05-14 08:52:28 -0700140const StringToEnum sGainModeNameToEnumTable[] = {
141 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
142 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
143 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
144};
145
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146
147uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
148 size_t size,
149 const char *name)
150{
151 for (size_t i = 0; i < size; i++) {
152 if (strcmp(table[i].name, name) == 0) {
153 ALOGV("stringToEnum() found %s", table[i].name);
154 return table[i].value;
155 }
156 }
157 return 0;
158}
159
160const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
161 size_t size,
162 uint32_t value)
163{
164 for (size_t i = 0; i < size; i++) {
165 if (table[i].value == value) {
166 return table[i].name;
167 }
168 }
169 return "";
170}
171
172bool AudioPolicyManager::stringToBool(const char *value)
173{
174 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
175}
176
177
178// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700179// AudioPolicyInterface implementation
180// ----------------------------------------------------------------------------
181
182
Eric Laurente0720872014-03-11 09:30:41 -0700183status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700184 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700185 const char *device_address)
186{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700187 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700188
189 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
190
191 // connect/disconnect only 1 device at a time
192 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
193
Eric Laurente552edb2014-03-10 17:42:56 -0700194 // handle output devices
195 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700196 SortedVector <audio_io_handle_t> outputs;
197
Eric Laurent1afeecb2014-05-14 08:52:28 -0700198 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
199 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700200 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // save a copy of the opened output descriptors before any output is opened or closed
203 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
204 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 switch (state)
206 {
207 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700208 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700209 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700210 ALOGW("setDeviceConnectionState() device already connected: %x", device);
211 return INVALID_OPERATION;
212 }
213 ALOGV("setDeviceConnectionState() connecting device %x", device);
214
Eric Laurent3a4311c2014-03-17 12:00:47 -0700215 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700216 return INVALID_OPERATION;
217 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700218 // outputs should never be empty here
219 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
220 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700221 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700222 outputs.size());
223 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700224 index = mAvailableOutputDevices.add(devDesc);
225 if (index >= 0) {
226 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700227 HwModule *module = getModuleForDevice(device);
228 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
229 "could not find HW module for device %08x", device);
230 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 } else {
232 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700233 }
234
235 break;
236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700239 ALOGW("setDeviceConnectionState() device not connected: %x", device);
240 return INVALID_OPERATION;
241 }
242
243 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
244 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700245 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700246
Eric Laurent3a4311c2014-03-17 12:00:47 -0700247 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700248 // not currently handling multiple simultaneous submixes: ignoring remote submix
249 // case and address
250 } break;
251
252 default:
253 ALOGE("setDeviceConnectionState() invalid state: %x", state);
254 return BAD_VALUE;
255 }
256
Eric Laurent3a4311c2014-03-17 12:00:47 -0700257 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
258 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700259 checkA2dpSuspend();
260 checkOutputForAllStrategies();
261 // outputs must be closed after checkOutputForAllStrategies() is executed
262 if (!outputs.isEmpty()) {
263 for (size_t i = 0; i < outputs.size(); i++) {
264 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
265 // close unused outputs after device disconnection or direct outputs that have been
266 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700267 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700268 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
269 (desc->mDirectOpenCount == 0))) {
270 closeOutput(outputs[i]);
271 }
272 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700273 // check again after closing A2DP output to reset mA2dpSuspended if needed
274 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700275 }
276
277 updateDevicesAndOutputs();
278 for (size_t i = 0; i < mOutputs.size(); i++) {
279 // do not force device change on duplicated output because if device is 0, it will
280 // also force a device 0 for the two outputs it is duplicated to which may override
281 // a valid device selection on those outputs.
282 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700283 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700284 !mOutputs.valueAt(i)->isDuplicated(),
285 0);
286 }
287
Eric Laurent72aa32f2014-05-30 18:51:48 -0700288 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700289 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700290 } // end if is output device
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 // handle input devices
293 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700294 SortedVector <audio_io_handle_t> inputs;
295
Eric Laurent1afeecb2014-05-14 08:52:28 -0700296 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
297 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700299 switch (state)
300 {
301 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700302 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700304 ALOGW("setDeviceConnectionState() device already connected: %d", device);
305 return INVALID_OPERATION;
306 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700307 HwModule *module = getModuleForDevice(device);
308 if (module == NULL) {
309 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
310 device);
311 return INVALID_OPERATION;
312 }
Eric Laurentd4692962014-05-05 18:13:44 -0700313 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
314 return INVALID_OPERATION;
315 }
316
Eric Laurent3a4311c2014-03-17 12:00:47 -0700317 index = mAvailableInputDevices.add(devDesc);
318 if (index >= 0) {
319 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700320 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700321 } else {
322 return NO_MEMORY;
323 }
Eric Laurentd4692962014-05-05 18:13:44 -0700324 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700325
326 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700327 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700329 ALOGW("setDeviceConnectionState() device not connected: %d", device);
330 return INVALID_OPERATION;
331 }
Eric Laurentd4692962014-05-05 18:13:44 -0700332 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700334 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700335
336 default:
337 ALOGE("setDeviceConnectionState() invalid state: %x", state);
338 return BAD_VALUE;
339 }
340
Eric Laurentd4692962014-05-05 18:13:44 -0700341 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700342
Eric Laurentb52c1522014-05-20 11:27:36 -0700343 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700344 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700345 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700346
347 ALOGW("setDeviceConnectionState() invalid device: %x", device);
348 return BAD_VALUE;
349}
350
Eric Laurente0720872014-03-11 09:30:41 -0700351audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700352 const char *device_address)
353{
Eric Laurent3b73df72014-03-11 09:06:29 -0700354 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700356 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
357 devDesc->mAddress = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 ssize_t index;
359 DeviceVector *deviceVector;
360
Eric Laurente552edb2014-03-10 17:42:56 -0700361 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700362 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700363 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 deviceVector = &mAvailableInputDevices;
365 } else {
366 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
367 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700368 }
369
Eric Laurent3a4311c2014-03-17 12:00:47 -0700370 index = deviceVector->indexOf(devDesc);
371 if (index >= 0) {
372 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
373 } else {
374 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
375 }
Eric Laurente552edb2014-03-10 17:42:56 -0700376}
377
Eric Laurente0720872014-03-11 09:30:41 -0700378void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700379{
380 ALOGV("setPhoneState() state %d", state);
381 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700382 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700383 ALOGW("setPhoneState() invalid state %d", state);
384 return;
385 }
386
387 if (state == mPhoneState ) {
388 ALOGW("setPhoneState() setting same state %d", state);
389 return;
390 }
391
392 // if leaving call state, handle special case of active streams
393 // pertaining to sonification strategy see handleIncallSonification()
394 if (isInCall()) {
395 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700396 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
397 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700398 }
399 }
400
401 // store previous phone state for management of sonification strategy below
402 int oldState = mPhoneState;
403 mPhoneState = state;
404 bool force = false;
405
406 // are we entering or starting a call
407 if (!isStateInCall(oldState) && isStateInCall(state)) {
408 ALOGV(" Entering call in setPhoneState()");
409 // force routing command to audio hardware when starting a call
410 // even if no device change is needed
411 force = true;
412 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
413 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
414 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
415 }
416 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
417 ALOGV(" Exiting call in setPhoneState()");
418 // force routing command to audio hardware when exiting a call
419 // even if no device change is needed
420 force = true;
421 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
422 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
423 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
424 }
425 } else if (isStateInCall(state) && (state != oldState)) {
426 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
427 // force routing command to audio hardware when switching between telephony and VoIP
428 // even if no device change is needed
429 force = true;
430 }
431
432 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700433 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700434 checkA2dpSuspend();
435 checkOutputForAllStrategies();
436 updateDevicesAndOutputs();
437
438 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
439
440 // force routing command to audio hardware when ending call
441 // even if no device change is needed
442 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
443 newDevice = hwOutputDesc->device();
444 }
445
446 int delayMs = 0;
447 if (isStateInCall(state)) {
448 nsecs_t sysTime = systemTime();
449 for (size_t i = 0; i < mOutputs.size(); i++) {
450 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
451 // mute media and sonification strategies and delay device switch by the largest
452 // latency of any output where either strategy is active.
453 // This avoid sending the ring tone or music tail into the earpiece or headset.
454 if ((desc->isStrategyActive(STRATEGY_MEDIA,
455 SONIFICATION_HEADSET_MUSIC_DELAY,
456 sysTime) ||
457 desc->isStrategyActive(STRATEGY_SONIFICATION,
458 SONIFICATION_HEADSET_MUSIC_DELAY,
459 sysTime)) &&
460 (delayMs < (int)desc->mLatency*2)) {
461 delayMs = desc->mLatency*2;
462 }
463 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
464 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
465 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
466 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
467 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
468 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
469 }
470 }
471
472 // change routing is necessary
473 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
474
475 // if entering in call state, handle special case of active streams
476 // pertaining to sonification strategy see handleIncallSonification()
477 if (isStateInCall(state)) {
478 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700479 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
480 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700481 }
482 }
483
484 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700485 if (state == AUDIO_MODE_RINGTONE &&
486 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700487 mLimitRingtoneVolume = true;
488 } else {
489 mLimitRingtoneVolume = false;
490 }
491}
492
Eric Laurente0720872014-03-11 09:30:41 -0700493void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700494 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700495{
496 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
497
498 bool forceVolumeReeval = false;
499 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700500 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
501 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
502 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700503 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
504 return;
505 }
506 forceVolumeReeval = true;
507 mForceUse[usage] = config;
508 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700509 case AUDIO_POLICY_FORCE_FOR_MEDIA:
510 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
511 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
512 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
513 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
514 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700515 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
516 return;
517 }
518 mForceUse[usage] = config;
519 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700520 case AUDIO_POLICY_FORCE_FOR_RECORD:
521 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
522 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700523 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
524 return;
525 }
526 mForceUse[usage] = config;
527 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700528 case AUDIO_POLICY_FORCE_FOR_DOCK:
529 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
530 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
531 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
532 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
533 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700534 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
535 }
536 forceVolumeReeval = true;
537 mForceUse[usage] = config;
538 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700539 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
540 if (config != AUDIO_POLICY_FORCE_NONE &&
541 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700542 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
543 }
544 forceVolumeReeval = true;
545 mForceUse[usage] = config;
546 break;
547 default:
548 ALOGW("setForceUse() invalid usage %d", usage);
549 break;
550 }
551
552 // check for device and output changes triggered by new force usage
553 checkA2dpSuspend();
554 checkOutputForAllStrategies();
555 updateDevicesAndOutputs();
556 for (size_t i = 0; i < mOutputs.size(); i++) {
557 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700558 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700559 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
560 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
561 applyStreamVolumes(output, newDevice, 0, true);
562 }
563 }
564
565 audio_io_handle_t activeInput = getActiveInput();
566 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700567 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700568 }
569
570}
571
Eric Laurente0720872014-03-11 09:30:41 -0700572audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700573{
574 return mForceUse[usage];
575}
576
Eric Laurente0720872014-03-11 09:30:41 -0700577void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700578{
579 ALOGV("setSystemProperty() property %s, value %s", property, value);
580}
581
582// Find a direct output profile compatible with the parameters passed, even if the input flags do
583// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700584sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700585 audio_devices_t device,
586 uint32_t samplingRate,
587 audio_format_t format,
588 audio_channel_mask_t channelMask,
589 audio_output_flags_t flags)
590{
591 for (size_t i = 0; i < mHwModules.size(); i++) {
592 if (mHwModules[i]->mHandle == 0) {
593 continue;
594 }
595 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700596 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700597 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700598 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
599 if (profile->isCompatibleProfile(device, samplingRate, format,
600 channelMask,
601 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700602 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700603 }
604 } else {
605 if (profile->isCompatibleProfile(device, samplingRate, format,
606 channelMask,
607 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700608 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700609 }
610 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700611 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
612 return profile;
613 }
Eric Laurente552edb2014-03-10 17:42:56 -0700614 }
615 }
616 return 0;
617}
618
Eric Laurente0720872014-03-11 09:30:41 -0700619audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700620 uint32_t samplingRate,
621 audio_format_t format,
622 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700623 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700624 const audio_offload_info_t *offloadInfo)
625{
626 audio_io_handle_t output = 0;
627 uint32_t latency = 0;
Eric Laurent3b73df72014-03-11 09:06:29 -0700628 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700629 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
630 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
631 device, stream, samplingRate, format, channelMask, flags);
632
633#ifdef AUDIO_POLICY_TEST
634 if (mCurOutput != 0) {
635 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
636 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
637
638 if (mTestOutputs[mCurOutput] == 0) {
639 ALOGV("getOutput() opening test output");
640 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
641 outputDesc->mDevice = mTestDevice;
642 outputDesc->mSamplingRate = mTestSamplingRate;
643 outputDesc->mFormat = mTestFormat;
644 outputDesc->mChannelMask = mTestChannels;
645 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700646 outputDesc->mFlags =
647 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700648 outputDesc->mRefCount[stream] = 0;
649 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
650 &outputDesc->mSamplingRate,
651 &outputDesc->mFormat,
652 &outputDesc->mChannelMask,
653 &outputDesc->mLatency,
654 outputDesc->mFlags,
655 offloadInfo);
656 if (mTestOutputs[mCurOutput]) {
657 AudioParameter outputCmd = AudioParameter();
658 outputCmd.addInt(String8("set_id"),mCurOutput);
659 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
660 addOutput(mTestOutputs[mCurOutput], outputDesc);
661 }
662 }
663 return mTestOutputs[mCurOutput];
664 }
665#endif //AUDIO_POLICY_TEST
666
667 // open a direct output if required by specified parameters
668 //force direct flag if offload flag is set: offloading implies a direct output stream
669 // and all common behaviors are driven by checking only the direct flag
670 // this should normally be set appropriately in the policy configuration file
671 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700672 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700673 }
674
675 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
676 // creating an offloaded track and tearing it down immediately after start when audioflinger
677 // detects there is an active non offloadable effect.
678 // FIXME: We should check the audio session here but we do not have it in this context.
679 // This may prevent offloading in rare situations where effects are left active by apps
680 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700681 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700682 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
683 !isNonOffloadableEffectEnabled()) {
684 profile = getProfileForDirectOutput(device,
685 samplingRate,
686 format,
687 channelMask,
688 (audio_output_flags_t)flags);
689 }
690
Eric Laurent1c333e22014-05-20 10:48:17 -0700691 if (profile != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700692 AudioOutputDescriptor *outputDesc = NULL;
693
694 for (size_t i = 0; i < mOutputs.size(); i++) {
695 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
696 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
697 outputDesc = desc;
698 // reuse direct output if currently open and configured with same parameters
699 if ((samplingRate == outputDesc->mSamplingRate) &&
700 (format == outputDesc->mFormat) &&
701 (channelMask == outputDesc->mChannelMask)) {
702 outputDesc->mDirectOpenCount++;
703 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
704 return mOutputs.keyAt(i);
705 }
706 }
707 }
708 // close direct output if currently open and configured with different parameters
709 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700710 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700711 }
712 outputDesc = new AudioOutputDescriptor(profile);
713 outputDesc->mDevice = device;
714 outputDesc->mSamplingRate = samplingRate;
715 outputDesc->mFormat = format;
716 outputDesc->mChannelMask = channelMask;
717 outputDesc->mLatency = 0;
718 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
719 outputDesc->mRefCount[stream] = 0;
720 outputDesc->mStopTime[stream] = 0;
721 outputDesc->mDirectOpenCount = 1;
722 output = mpClientInterface->openOutput(profile->mModule->mHandle,
723 &outputDesc->mDevice,
724 &outputDesc->mSamplingRate,
725 &outputDesc->mFormat,
726 &outputDesc->mChannelMask,
727 &outputDesc->mLatency,
728 outputDesc->mFlags,
729 offloadInfo);
730
731 // only accept an output with the requested parameters
732 if (output == 0 ||
733 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
734 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
735 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
736 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
737 "format %d %d, channelMask %04x %04x", output, samplingRate,
738 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
739 outputDesc->mChannelMask);
740 if (output != 0) {
741 mpClientInterface->closeOutput(output);
742 }
743 delete outputDesc;
744 return 0;
745 }
746 audio_io_handle_t srcOutput = getOutputForEffect();
747 addOutput(output, outputDesc);
748 audio_io_handle_t dstOutput = getOutputForEffect();
749 if (dstOutput == output) {
750 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
751 }
752 mPreviousOutputs = mOutputs;
753 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700754 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700755 return output;
756 }
757
758 // ignoring channel mask due to downmix capability in mixer
759
760 // open a non direct output
761
762 // for non direct outputs, only PCM is supported
763 if (audio_is_linear_pcm(format)) {
764 // get which output is suitable for the specified stream. The actual
765 // routing change will happen when startOutput() will be called
766 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
767
768 output = selectOutput(outputs, flags);
769 }
770 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
771 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
772
773 ALOGV("getOutput() returns output %d", output);
774
775 return output;
776}
777
Eric Laurente0720872014-03-11 09:30:41 -0700778audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700779 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700780{
781 // select one output among several that provide a path to a particular device or set of
782 // devices (the list was previously build by getOutputsForDevice()).
783 // The priority is as follows:
784 // 1: the output with the highest number of requested policy flags
785 // 2: the primary output
786 // 3: the first output in the list
787
788 if (outputs.size() == 0) {
789 return 0;
790 }
791 if (outputs.size() == 1) {
792 return outputs[0];
793 }
794
795 int maxCommonFlags = 0;
796 audio_io_handle_t outputFlags = 0;
797 audio_io_handle_t outputPrimary = 0;
798
799 for (size_t i = 0; i < outputs.size(); i++) {
800 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
801 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700802 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700803 if (commonFlags > maxCommonFlags) {
804 outputFlags = outputs[i];
805 maxCommonFlags = commonFlags;
806 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
807 }
808 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
809 outputPrimary = outputs[i];
810 }
811 }
812 }
813
814 if (outputFlags != 0) {
815 return outputFlags;
816 }
817 if (outputPrimary != 0) {
818 return outputPrimary;
819 }
820
821 return outputs[0];
822}
823
Eric Laurente0720872014-03-11 09:30:41 -0700824status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700825 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700826 int session)
827{
828 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
829 ssize_t index = mOutputs.indexOfKey(output);
830 if (index < 0) {
831 ALOGW("startOutput() unknown output %d", output);
832 return BAD_VALUE;
833 }
834
835 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
836
837 // increment usage count for this stream on the requested output:
838 // NOTE that the usage count is the same for duplicated output and hardware output which is
839 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
840 outputDesc->changeRefCount(stream, 1);
841
842 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700843 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700844 routing_strategy strategy = getStrategy(stream);
845 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
846 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
847 uint32_t waitMs = 0;
848 bool force = false;
849 for (size_t i = 0; i < mOutputs.size(); i++) {
850 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
851 if (desc != outputDesc) {
852 // force a device change if any other output is managed by the same hw
853 // module and has a current device selection that differs from selected device.
854 // In this case, the audio HAL must receive the new device selection so that it can
855 // change the device currently selected by the other active output.
856 if (outputDesc->sharesHwModuleWith(desc) &&
857 desc->device() != newDevice) {
858 force = true;
859 }
860 // wait for audio on other active outputs to be presented when starting
861 // a notification so that audio focus effect can propagate.
862 uint32_t latency = desc->latency();
863 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
864 waitMs = latency;
865 }
866 }
867 }
868 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
869
870 // handle special case for sonification while in call
871 if (isInCall()) {
872 handleIncallSonification(stream, true, false);
873 }
874
875 // apply volume rules for current stream and device if necessary
876 checkAndSetVolume(stream,
877 mStreams[stream].getVolumeIndex(newDevice),
878 output,
879 newDevice);
880
881 // update the outputs if starting an output with a stream that can affect notification
882 // routing
883 handleNotificationRoutingForStream(stream);
884 if (waitMs > muteWaitMs) {
885 usleep((waitMs - muteWaitMs) * 2 * 1000);
886 }
887 }
888 return NO_ERROR;
889}
890
891
Eric Laurente0720872014-03-11 09:30:41 -0700892status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700893 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700894 int session)
895{
896 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
897 ssize_t index = mOutputs.indexOfKey(output);
898 if (index < 0) {
899 ALOGW("stopOutput() unknown output %d", output);
900 return BAD_VALUE;
901 }
902
903 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
904
905 // handle special case for sonification while in call
906 if (isInCall()) {
907 handleIncallSonification(stream, false, false);
908 }
909
910 if (outputDesc->mRefCount[stream] > 0) {
911 // decrement usage count of this stream on the output
912 outputDesc->changeRefCount(stream, -1);
913 // store time at which the stream was stopped - see isStreamActive()
914 if (outputDesc->mRefCount[stream] == 0) {
915 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700916 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700917 // delay the device switch by twice the latency because stopOutput() is executed when
918 // the track stop() command is received and at that time the audio track buffer can
919 // still contain data that needs to be drained. The latency only covers the audio HAL
920 // and kernel buffers. Also the latency does not always include additional delay in the
921 // audio path (audio DSP, CODEC ...)
922 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
923
924 // force restoring the device selection on other active outputs if it differs from the
925 // one being selected for this output
926 for (size_t i = 0; i < mOutputs.size(); i++) {
927 audio_io_handle_t curOutput = mOutputs.keyAt(i);
928 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
929 if (curOutput != output &&
930 desc->isActive() &&
931 outputDesc->sharesHwModuleWith(desc) &&
932 (newDevice != desc->device())) {
933 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700934 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700935 true,
936 outputDesc->mLatency*2);
937 }
938 }
939 // update the outputs if stopping one with a stream that can affect notification routing
940 handleNotificationRoutingForStream(stream);
941 }
942 return NO_ERROR;
943 } else {
944 ALOGW("stopOutput() refcount is already 0 for output %d", output);
945 return INVALID_OPERATION;
946 }
947}
948
Eric Laurente0720872014-03-11 09:30:41 -0700949void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700950{
951 ALOGV("releaseOutput() %d", output);
952 ssize_t index = mOutputs.indexOfKey(output);
953 if (index < 0) {
954 ALOGW("releaseOutput() releasing unknown output %d", output);
955 return;
956 }
957
958#ifdef AUDIO_POLICY_TEST
959 int testIndex = testOutputIndex(output);
960 if (testIndex != 0) {
961 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
962 if (outputDesc->isActive()) {
963 mpClientInterface->closeOutput(output);
964 delete mOutputs.valueAt(index);
965 mOutputs.removeItem(output);
966 mTestOutputs[testIndex] = 0;
967 }
968 return;
969 }
970#endif //AUDIO_POLICY_TEST
971
972 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -0700973 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700974 if (desc->mDirectOpenCount <= 0) {
975 ALOGW("releaseOutput() invalid open count %d for output %d",
976 desc->mDirectOpenCount, output);
977 return;
978 }
979 if (--desc->mDirectOpenCount == 0) {
980 closeOutput(output);
981 // If effects where present on the output, audioflinger moved them to the primary
982 // output by default: move them back to the appropriate output.
983 audio_io_handle_t dstOutput = getOutputForEffect();
984 if (dstOutput != mPrimaryOutput) {
985 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
986 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700987 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700988 }
989 }
990}
991
992
Eric Laurente0720872014-03-11 09:30:41 -0700993audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -0700994 uint32_t samplingRate,
995 audio_format_t format,
996 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700997 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -0700998{
999 audio_io_handle_t input = 0;
1000 audio_devices_t device = getDeviceForInputSource(inputSource);
1001
1002 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1003 inputSource, samplingRate, format, channelMask, acoustics);
1004
1005 if (device == AUDIO_DEVICE_NONE) {
1006 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1007 return 0;
1008 }
1009
1010 // adapt channel selection to input source
1011 switch(inputSource) {
1012 case AUDIO_SOURCE_VOICE_UPLINK:
1013 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1014 break;
1015 case AUDIO_SOURCE_VOICE_DOWNLINK:
1016 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1017 break;
1018 case AUDIO_SOURCE_VOICE_CALL:
1019 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1020 break;
1021 default:
1022 break;
1023 }
1024
Eric Laurent1c333e22014-05-20 10:48:17 -07001025 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001026 samplingRate,
1027 format,
1028 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001029 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001030 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1031 "channelMask %04x",
1032 device, samplingRate, format, channelMask);
1033 return 0;
1034 }
1035
1036 if (profile->mModule->mHandle == 0) {
1037 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1038 return 0;
1039 }
1040
1041 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
1042
1043 inputDesc->mInputSource = inputSource;
1044 inputDesc->mDevice = device;
1045 inputDesc->mSamplingRate = samplingRate;
1046 inputDesc->mFormat = format;
1047 inputDesc->mChannelMask = channelMask;
1048 inputDesc->mRefCount = 0;
1049 input = mpClientInterface->openInput(profile->mModule->mHandle,
1050 &inputDesc->mDevice,
1051 &inputDesc->mSamplingRate,
1052 &inputDesc->mFormat,
1053 &inputDesc->mChannelMask);
1054
1055 // only accept input with the exact requested set of parameters
1056 if (input == 0 ||
1057 (samplingRate != inputDesc->mSamplingRate) ||
1058 (format != inputDesc->mFormat) ||
1059 (channelMask != inputDesc->mChannelMask)) {
1060 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1061 samplingRate, format, channelMask);
1062 if (input != 0) {
1063 mpClientInterface->closeInput(input);
1064 }
1065 delete inputDesc;
1066 return 0;
1067 }
Eric Laurentd4692962014-05-05 18:13:44 -07001068 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001069 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001070 return input;
1071}
1072
Eric Laurente0720872014-03-11 09:30:41 -07001073status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001074{
1075 ALOGV("startInput() input %d", input);
1076 ssize_t index = mInputs.indexOfKey(input);
1077 if (index < 0) {
1078 ALOGW("startInput() unknown input %d", input);
1079 return BAD_VALUE;
1080 }
1081 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1082
1083#ifdef AUDIO_POLICY_TEST
1084 if (mTestInput == 0)
1085#endif //AUDIO_POLICY_TEST
1086 {
1087 // refuse 2 active AudioRecord clients at the same time except if the active input
1088 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1089 audio_io_handle_t activeInput = getActiveInput();
1090 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1091 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1092 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1093 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1094 stopInput(activeInput);
1095 releaseInput(activeInput);
1096 } else {
1097 ALOGW("startInput() input %d failed: other input already started", input);
1098 return INVALID_OPERATION;
1099 }
1100 }
1101 }
1102
Eric Laurent1c333e22014-05-20 10:48:17 -07001103 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001104
1105 // automatically enable the remote submix output when input is started
1106 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1107 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001108 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001109 }
1110
Eric Laurente552edb2014-03-10 17:42:56 -07001111 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1112
Eric Laurente552edb2014-03-10 17:42:56 -07001113 inputDesc->mRefCount = 1;
1114 return NO_ERROR;
1115}
1116
Eric Laurente0720872014-03-11 09:30:41 -07001117status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001118{
1119 ALOGV("stopInput() input %d", input);
1120 ssize_t index = mInputs.indexOfKey(input);
1121 if (index < 0) {
1122 ALOGW("stopInput() unknown input %d", input);
1123 return BAD_VALUE;
1124 }
1125 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1126
1127 if (inputDesc->mRefCount == 0) {
1128 ALOGW("stopInput() input %d already stopped", input);
1129 return INVALID_OPERATION;
1130 } else {
1131 // automatically disable the remote submix output when input is stopped
1132 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1133 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001134 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001135 }
1136
Eric Laurent1c333e22014-05-20 10:48:17 -07001137 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001138 inputDesc->mRefCount = 0;
1139 return NO_ERROR;
1140 }
1141}
1142
Eric Laurente0720872014-03-11 09:30:41 -07001143void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001144{
1145 ALOGV("releaseInput() %d", input);
1146 ssize_t index = mInputs.indexOfKey(input);
1147 if (index < 0) {
1148 ALOGW("releaseInput() releasing unknown input %d", input);
1149 return;
1150 }
1151 mpClientInterface->closeInput(input);
1152 delete mInputs.valueAt(index);
1153 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001154 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001155 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001156 ALOGV("releaseInput() exit");
1157}
1158
Eric Laurentd4692962014-05-05 18:13:44 -07001159void AudioPolicyManager::closeAllInputs() {
1160 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1161 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1162 }
1163 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001164 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001165}
1166
Eric Laurente0720872014-03-11 09:30:41 -07001167void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001168 int indexMin,
1169 int indexMax)
1170{
1171 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1172 if (indexMin < 0 || indexMin >= indexMax) {
1173 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1174 return;
1175 }
1176 mStreams[stream].mIndexMin = indexMin;
1177 mStreams[stream].mIndexMax = indexMax;
1178}
1179
Eric Laurente0720872014-03-11 09:30:41 -07001180status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001181 int index,
1182 audio_devices_t device)
1183{
1184
1185 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1186 return BAD_VALUE;
1187 }
1188 if (!audio_is_output_device(device)) {
1189 return BAD_VALUE;
1190 }
1191
1192 // Force max volume if stream cannot be muted
1193 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1194
1195 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1196 stream, device, index);
1197
1198 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1199 // clear all device specific values
1200 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1201 mStreams[stream].mIndexCur.clear();
1202 }
1203 mStreams[stream].mIndexCur.add(device, index);
1204
1205 // compute and apply stream volume on all outputs according to connected device
1206 status_t status = NO_ERROR;
1207 for (size_t i = 0; i < mOutputs.size(); i++) {
1208 audio_devices_t curDevice =
1209 getDeviceForVolume(mOutputs.valueAt(i)->device());
1210 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1211 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1212 if (volStatus != NO_ERROR) {
1213 status = volStatus;
1214 }
1215 }
1216 }
1217 return status;
1218}
1219
Eric Laurente0720872014-03-11 09:30:41 -07001220status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001221 int *index,
1222 audio_devices_t device)
1223{
1224 if (index == NULL) {
1225 return BAD_VALUE;
1226 }
1227 if (!audio_is_output_device(device)) {
1228 return BAD_VALUE;
1229 }
1230 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1231 // the strategy the stream belongs to.
1232 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1233 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1234 }
1235 device = getDeviceForVolume(device);
1236
1237 *index = mStreams[stream].getVolumeIndex(device);
1238 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1239 return NO_ERROR;
1240}
1241
Eric Laurente0720872014-03-11 09:30:41 -07001242audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001243 const SortedVector<audio_io_handle_t>& outputs)
1244{
1245 // select one output among several suitable for global effects.
1246 // The priority is as follows:
1247 // 1: An offloaded output. If the effect ends up not being offloadable,
1248 // AudioFlinger will invalidate the track and the offloaded output
1249 // will be closed causing the effect to be moved to a PCM output.
1250 // 2: A deep buffer output
1251 // 3: the first output in the list
1252
1253 if (outputs.size() == 0) {
1254 return 0;
1255 }
1256
1257 audio_io_handle_t outputOffloaded = 0;
1258 audio_io_handle_t outputDeepBuffer = 0;
1259
1260 for (size_t i = 0; i < outputs.size(); i++) {
1261 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001262 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001263 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1264 outputOffloaded = outputs[i];
1265 }
1266 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1267 outputDeepBuffer = outputs[i];
1268 }
1269 }
1270
1271 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1272 outputOffloaded, outputDeepBuffer);
1273 if (outputOffloaded != 0) {
1274 return outputOffloaded;
1275 }
1276 if (outputDeepBuffer != 0) {
1277 return outputDeepBuffer;
1278 }
1279
1280 return outputs[0];
1281}
1282
Eric Laurente0720872014-03-11 09:30:41 -07001283audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001284{
1285 // apply simple rule where global effects are attached to the same output as MUSIC streams
1286
Eric Laurent3b73df72014-03-11 09:06:29 -07001287 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001288 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1289 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1290
1291 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1292 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1293 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1294
1295 return output;
1296}
1297
Eric Laurente0720872014-03-11 09:30:41 -07001298status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001299 audio_io_handle_t io,
1300 uint32_t strategy,
1301 int session,
1302 int id)
1303{
1304 ssize_t index = mOutputs.indexOfKey(io);
1305 if (index < 0) {
1306 index = mInputs.indexOfKey(io);
1307 if (index < 0) {
1308 ALOGW("registerEffect() unknown io %d", io);
1309 return INVALID_OPERATION;
1310 }
1311 }
1312
1313 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1314 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1315 desc->name, desc->memoryUsage);
1316 return INVALID_OPERATION;
1317 }
1318 mTotalEffectsMemory += desc->memoryUsage;
1319 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1320 desc->name, io, strategy, session, id);
1321 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1322
1323 EffectDescriptor *pDesc = new EffectDescriptor();
1324 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1325 pDesc->mIo = io;
1326 pDesc->mStrategy = (routing_strategy)strategy;
1327 pDesc->mSession = session;
1328 pDesc->mEnabled = false;
1329
1330 mEffects.add(id, pDesc);
1331
1332 return NO_ERROR;
1333}
1334
Eric Laurente0720872014-03-11 09:30:41 -07001335status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001336{
1337 ssize_t index = mEffects.indexOfKey(id);
1338 if (index < 0) {
1339 ALOGW("unregisterEffect() unknown effect ID %d", id);
1340 return INVALID_OPERATION;
1341 }
1342
1343 EffectDescriptor *pDesc = mEffects.valueAt(index);
1344
1345 setEffectEnabled(pDesc, false);
1346
1347 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1348 ALOGW("unregisterEffect() memory %d too big for total %d",
1349 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1350 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1351 }
1352 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1353 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1354 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1355
1356 mEffects.removeItem(id);
1357 delete pDesc;
1358
1359 return NO_ERROR;
1360}
1361
Eric Laurente0720872014-03-11 09:30:41 -07001362status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001363{
1364 ssize_t index = mEffects.indexOfKey(id);
1365 if (index < 0) {
1366 ALOGW("unregisterEffect() unknown effect ID %d", id);
1367 return INVALID_OPERATION;
1368 }
1369
1370 return setEffectEnabled(mEffects.valueAt(index), enabled);
1371}
1372
Eric Laurente0720872014-03-11 09:30:41 -07001373status_t AudioPolicyManager::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001374{
1375 if (enabled == pDesc->mEnabled) {
1376 ALOGV("setEffectEnabled(%s) effect already %s",
1377 enabled?"true":"false", enabled?"enabled":"disabled");
1378 return INVALID_OPERATION;
1379 }
1380
1381 if (enabled) {
1382 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1383 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1384 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1385 return INVALID_OPERATION;
1386 }
1387 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1388 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1389 } else {
1390 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1391 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1392 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1393 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1394 }
1395 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1396 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1397 }
1398 pDesc->mEnabled = enabled;
1399 return NO_ERROR;
1400}
1401
Eric Laurente0720872014-03-11 09:30:41 -07001402bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001403{
1404 for (size_t i = 0; i < mEffects.size(); i++) {
1405 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1406 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1407 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1408 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1409 pDesc->mDesc.name, pDesc->mSession);
1410 return true;
1411 }
1412 }
1413 return false;
1414}
1415
Eric Laurente0720872014-03-11 09:30:41 -07001416bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001417{
1418 nsecs_t sysTime = systemTime();
1419 for (size_t i = 0; i < mOutputs.size(); i++) {
1420 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001421 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001422 return true;
1423 }
1424 }
1425 return false;
1426}
1427
Eric Laurente0720872014-03-11 09:30:41 -07001428bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001429 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001430{
1431 nsecs_t sysTime = systemTime();
1432 for (size_t i = 0; i < mOutputs.size(); i++) {
1433 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1434 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001435 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001436 return true;
1437 }
1438 }
1439 return false;
1440}
1441
Eric Laurente0720872014-03-11 09:30:41 -07001442bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001443{
1444 for (size_t i = 0; i < mInputs.size(); i++) {
1445 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1446 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001447 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001448 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1449 && (inputDescriptor->mRefCount > 0)) {
1450 return true;
1451 }
1452 }
1453 return false;
1454}
1455
1456
Eric Laurente0720872014-03-11 09:30:41 -07001457status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001458{
1459 const size_t SIZE = 256;
1460 char buffer[SIZE];
1461 String8 result;
1462
1463 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1464 result.append(buffer);
1465
1466 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1467 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001468 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1469 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001470 snprintf(buffer, SIZE, " Force use for communications %d\n",
1471 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
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 media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
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 record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
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 dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001478 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001479 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001480 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001481
Eric Laurent3a4311c2014-03-17 12:00:47 -07001482 snprintf(buffer, SIZE, " Available output devices:\n");
1483 result.append(buffer);
1484 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001485 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001486 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001487 }
1488 snprintf(buffer, SIZE, "\n Available input devices:\n");
1489 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001490 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001491 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001492 }
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
Eric Laurent1afeecb2014-05-14 08:52:28 -07001721AudioPolicyManager::HwModule *AudioPolicyManager::getModuleFromName(const char *name) const
1722{
1723 for (size_t i = 0; i < mHwModules.size(); i++)
1724 {
1725 if (strcmp(mHwModules[i]->mName, name) == 0) {
1726 return mHwModules[i];
1727 }
1728 }
1729 return NULL;
1730}
1731
1732
Eric Laurent6a94d692014-05-20 11:18:06 -07001733status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1734 audio_patch_handle_t *handle,
1735 uid_t uid)
1736{
1737 ALOGV("createAudioPatch()");
1738
1739 if (handle == NULL || patch == NULL) {
1740 return BAD_VALUE;
1741 }
1742 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1743
1744 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1745 return INVALID_OPERATION;
1746 }
1747 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1748 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1749 return INVALID_OPERATION;
1750 }
1751
1752 sp<AudioPatch> patchDesc;
1753 ssize_t index = mAudioPatches.indexOfKey(*handle);
1754
1755 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1756 patch->sinks[0].type);
1757 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1758 patch->sources[0].role,
1759 patch->sources[0].type);
1760
1761 if (index >= 0) {
1762 patchDesc = mAudioPatches.valueAt(index);
1763 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1764 mUidCached, patchDesc->mUid, uid);
1765 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1766 return INVALID_OPERATION;
1767 }
1768 } else {
1769 *handle = 0;
1770 }
1771
1772 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1773 // TODO add support for mix to mix connection
1774 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1775 ALOGV("createAudioPatch() source mix sink not device");
1776 return BAD_VALUE;
1777 }
1778 // output mix to output device connection
1779 AudioOutputDescriptor *outputDesc = getOutputFromId(patch->sources[0].id);
1780 if (outputDesc == NULL) {
1781 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1782 return BAD_VALUE;
1783 }
1784 if (patchDesc != 0) {
1785 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1786 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1787 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1788 return BAD_VALUE;
1789 }
1790 }
1791 sp<DeviceDescriptor> devDesc =
1792 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1793 if (devDesc == 0) {
1794 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1795 return BAD_VALUE;
1796 }
1797
1798 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1799 patch->sources[0].sample_rate,
1800 patch->sources[0].format,
1801 patch->sources[0].channel_mask,
1802 AUDIO_OUTPUT_FLAG_NONE)) {
1803 return INVALID_OPERATION;
1804 }
1805 // TODO: reconfigure output format and channels here
1806 ALOGV("createAudioPatch() setting device %08x on output %d",
1807 devDesc->mType, outputDesc->mIoHandle);
1808 setOutputDevice(outputDesc->mIoHandle,
1809 devDesc->mType,
1810 true,
1811 0,
1812 handle);
1813 index = mAudioPatches.indexOfKey(*handle);
1814 if (index >= 0) {
1815 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1816 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1817 }
1818 patchDesc = mAudioPatches.valueAt(index);
1819 patchDesc->mUid = uid;
1820 ALOGV("createAudioPatch() success");
1821 } else {
1822 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1823 return INVALID_OPERATION;
1824 }
1825 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1826 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1827 // input device to input mix connection
1828 AudioInputDescriptor *inputDesc = getInputFromId(patch->sinks[0].id);
1829 if (inputDesc == NULL) {
1830 return BAD_VALUE;
1831 }
1832 if (patchDesc != 0) {
1833 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1834 return BAD_VALUE;
1835 }
1836 }
1837 sp<DeviceDescriptor> devDesc =
1838 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1839 if (devDesc == 0) {
1840 return BAD_VALUE;
1841 }
1842
1843 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1844 patch->sinks[0].sample_rate,
1845 patch->sinks[0].format,
1846 patch->sinks[0].channel_mask,
1847 AUDIO_OUTPUT_FLAG_NONE)) {
1848 return INVALID_OPERATION;
1849 }
1850 // TODO: reconfigure output format and channels here
1851 ALOGV("createAudioPatch() setting device %08x on output %d",
1852 devDesc->mType, inputDesc->mIoHandle);
1853 setInputDevice(inputDesc->mIoHandle,
1854 devDesc->mType,
1855 true,
1856 handle);
1857 index = mAudioPatches.indexOfKey(*handle);
1858 if (index >= 0) {
1859 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1860 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1861 }
1862 patchDesc = mAudioPatches.valueAt(index);
1863 patchDesc->mUid = uid;
1864 ALOGV("createAudioPatch() success");
1865 } else {
1866 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1867 return INVALID_OPERATION;
1868 }
1869 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1870 // device to device connection
1871 if (patchDesc != 0) {
1872 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1873 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1874 return BAD_VALUE;
1875 }
1876 }
1877
1878 sp<DeviceDescriptor> srcDeviceDesc =
1879 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1880 sp<DeviceDescriptor> sinkDeviceDesc =
1881 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1882 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1883 return BAD_VALUE;
1884 }
1885 //update source and sink with our own data as the data passed in the patch may
1886 // be incomplete.
1887 struct audio_patch newPatch = *patch;
1888 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1889 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1890
1891 // TODO: add support for devices on different HW modules
1892 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1893 return INVALID_OPERATION;
1894 }
1895 // TODO: check from routing capabilities in config file and other conflicting patches
1896
1897 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1898 if (index >= 0) {
1899 afPatchHandle = patchDesc->mAfPatchHandle;
1900 }
1901
1902 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1903 &afPatchHandle,
1904 0);
1905 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1906 status, afPatchHandle);
1907 if (status == NO_ERROR) {
1908 if (index < 0) {
1909 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1910 &newPatch, uid);
1911 addAudioPatch(patchDesc->mHandle, patchDesc);
1912 } else {
1913 patchDesc->mPatch = newPatch;
1914 }
1915 patchDesc->mAfPatchHandle = afPatchHandle;
1916 *handle = patchDesc->mHandle;
1917 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001918 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001919 } else {
1920 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1921 status);
1922 return INVALID_OPERATION;
1923 }
1924 } else {
1925 return BAD_VALUE;
1926 }
1927 } else {
1928 return BAD_VALUE;
1929 }
1930 return NO_ERROR;
1931}
1932
1933status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1934 uid_t uid)
1935{
1936 ALOGV("releaseAudioPatch() patch %d", handle);
1937
1938 ssize_t index = mAudioPatches.indexOfKey(handle);
1939
1940 if (index < 0) {
1941 return BAD_VALUE;
1942 }
1943 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1944 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1945 mUidCached, patchDesc->mUid, uid);
1946 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1947 return INVALID_OPERATION;
1948 }
1949
1950 struct audio_patch *patch = &patchDesc->mPatch;
1951 patchDesc->mUid = mUidCached;
1952 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1953 AudioOutputDescriptor *outputDesc = getOutputFromId(patch->sources[0].id);
1954 if (outputDesc == NULL) {
1955 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
1956 return BAD_VALUE;
1957 }
1958
1959 setOutputDevice(outputDesc->mIoHandle,
1960 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
1961 true,
1962 0,
1963 NULL);
1964 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1965 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1966 AudioInputDescriptor *inputDesc = getInputFromId(patch->sinks[0].id);
1967 if (inputDesc == NULL) {
1968 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
1969 return BAD_VALUE;
1970 }
1971 setInputDevice(inputDesc->mIoHandle,
1972 getNewInputDevice(inputDesc->mIoHandle),
1973 true,
1974 NULL);
1975 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1976 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
1977 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1978 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
1979 status, patchDesc->mAfPatchHandle);
1980 removeAudioPatch(patchDesc->mHandle);
1981 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001982 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001983 } else {
1984 return BAD_VALUE;
1985 }
1986 } else {
1987 return BAD_VALUE;
1988 }
1989 return NO_ERROR;
1990}
1991
1992status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
1993 struct audio_patch *patches,
1994 unsigned int *generation)
1995{
1996 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
1997 generation == NULL) {
1998 return BAD_VALUE;
1999 }
2000 ALOGV("listAudioPatches() num_patches %d patches %p available patches %d",
2001 *num_patches, patches, mAudioPatches.size());
2002 if (patches == NULL) {
2003 *num_patches = 0;
2004 }
2005
2006 size_t patchesWritten = 0;
2007 size_t patchesMax = *num_patches;
2008 for (size_t i = 0;
2009 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2010 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2011 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
2012 ALOGV("listAudioPatches() patch %d num_sources %d num_sinks %d",
2013 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2014 }
2015 *num_patches = mAudioPatches.size();
2016
2017 *generation = curAudioPortGeneration();
2018 ALOGV("listAudioPatches() got %d patches needed %d", patchesWritten, *num_patches);
2019 return NO_ERROR;
2020}
2021
Eric Laurente1715a42014-05-20 11:30:42 -07002022status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002023{
Eric Laurente1715a42014-05-20 11:30:42 -07002024 ALOGV("setAudioPortConfig()");
2025
2026 if (config == NULL) {
2027 return BAD_VALUE;
2028 }
2029 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2030 // Only support gain configuration for now
2031 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN || config->gain.index < 0) {
2032 return BAD_VALUE;
2033 }
2034
2035 sp<AudioPort> portDesc;
2036 struct audio_port_config portConfig;
2037 if (config->type == AUDIO_PORT_TYPE_MIX) {
2038 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2039 AudioOutputDescriptor *outputDesc = getOutputFromId(config->id);
2040 if (outputDesc == NULL) {
2041 return BAD_VALUE;
2042 }
2043 portDesc = outputDesc->mProfile;
2044 outputDesc->toAudioPortConfig(&portConfig);
2045 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2046 AudioInputDescriptor *inputDesc = getInputFromId(config->id);
2047 if (inputDesc == NULL) {
2048 return BAD_VALUE;
2049 }
2050 portDesc = inputDesc->mProfile;
2051 inputDesc->toAudioPortConfig(&portConfig);
2052 } else {
2053 return BAD_VALUE;
2054 }
2055 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2056 sp<DeviceDescriptor> deviceDesc;
2057 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2058 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2059 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2060 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2061 } else {
2062 return BAD_VALUE;
2063 }
2064 if (deviceDesc == NULL) {
2065 return BAD_VALUE;
2066 }
2067 portDesc = deviceDesc;
2068 deviceDesc->toAudioPortConfig(&portConfig);
2069 } else {
2070 return BAD_VALUE;
2071 }
2072
2073 if ((size_t)config->gain.index >= portDesc->mGains.size()) {
2074 return INVALID_OPERATION;
2075 }
2076 const struct audio_gain *gain = &portDesc->mGains[config->gain.index]->mGain;
2077 if ((config->gain.mode & ~gain->mode) != 0) {
2078 return BAD_VALUE;
2079 }
2080 if ((config->gain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
2081 if ((config->gain.values[0] < gain->min_value) ||
2082 (config->gain.values[0] > gain->max_value)) {
2083 return BAD_VALUE;
2084 }
2085 } else {
2086 if ((config->gain.channel_mask & ~gain->channel_mask) != 0) {
2087 return BAD_VALUE;
2088 }
2089 size_t numValues = popcount(config->gain.channel_mask);
2090 for (size_t i = 0; i < numValues; i++) {
2091 if ((config->gain.values[i] < gain->min_value) ||
2092 (config->gain.values[i] > gain->max_value)) {
2093 return BAD_VALUE;
2094 }
2095 }
2096 }
2097 if ((config->gain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
2098 if ((config->gain.ramp_duration_ms < gain->min_ramp_ms) ||
2099 (config->gain.ramp_duration_ms > gain->max_ramp_ms)) {
2100 return BAD_VALUE;
2101 }
2102 }
2103
2104 portConfig.gain = config->gain;
2105
2106 status_t status = mpClientInterface->setAudioPortConfig(&portConfig, 0);
2107
2108 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002109}
2110
2111void AudioPolicyManager::clearAudioPatches(uid_t uid)
2112{
2113 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2114 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2115 if (patchDesc->mUid == uid) {
2116 // releaseAudioPatch() removes the patch from mAudioPatches
2117 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2118 i--;
2119 }
2120 }
2121 }
2122}
2123
2124status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2125 const sp<AudioPatch>& patch)
2126{
2127 ssize_t index = mAudioPatches.indexOfKey(handle);
2128
2129 if (index >= 0) {
2130 ALOGW("addAudioPatch() patch %d already in", handle);
2131 return ALREADY_EXISTS;
2132 }
2133 mAudioPatches.add(handle, patch);
2134 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2135 "sink handle %d",
2136 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2137 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2138 return NO_ERROR;
2139}
2140
2141status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2142{
2143 ssize_t index = mAudioPatches.indexOfKey(handle);
2144
2145 if (index < 0) {
2146 ALOGW("removeAudioPatch() patch %d not in", handle);
2147 return ALREADY_EXISTS;
2148 }
2149 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2150 mAudioPatches.valueAt(index)->mAfPatchHandle);
2151 mAudioPatches.removeItemsAt(index);
2152 return NO_ERROR;
2153}
2154
Eric Laurente552edb2014-03-10 17:42:56 -07002155// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002156// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002157// ----------------------------------------------------------------------------
2158
Eric Laurent3a4311c2014-03-17 12:00:47 -07002159uint32_t AudioPolicyManager::nextUniqueId()
2160{
2161 return android_atomic_inc(&mNextUniqueId);
2162}
2163
Eric Laurent6a94d692014-05-20 11:18:06 -07002164uint32_t AudioPolicyManager::nextAudioPortGeneration()
2165{
2166 return android_atomic_inc(&mAudioPortGeneration);
2167}
2168
Eric Laurente0720872014-03-11 09:30:41 -07002169AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002170 :
2171#ifdef AUDIO_POLICY_TEST
2172 Thread(false),
2173#endif //AUDIO_POLICY_TEST
2174 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002175 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002176 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2177 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002178 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002179 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2180 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002181{
Eric Laurent6a94d692014-05-20 11:18:06 -07002182 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002183 mpClientInterface = clientInterface;
2184
Eric Laurent3b73df72014-03-11 09:06:29 -07002185 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2186 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002187 }
2188
Eric Laurent1afeecb2014-05-14 08:52:28 -07002189 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002190 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2191 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2192 ALOGE("could not load audio policy configuration file, setting defaults");
2193 defaultAudioPolicyConfig();
2194 }
2195 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002196 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002197
2198 // must be done after reading the policy
2199 initializeVolumeCurves();
2200
2201 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002202 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2203 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002204 for (size_t i = 0; i < mHwModules.size(); i++) {
2205 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2206 if (mHwModules[i]->mHandle == 0) {
2207 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2208 continue;
2209 }
2210 // open all output streams needed to access attached devices
2211 // except for direct output streams that are only opened when they are actually
2212 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002213 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002214 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2215 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002216 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002217
Eric Laurent3a4311c2014-03-17 12:00:47 -07002218 if (outProfile->mSupportedDevices.isEmpty()) {
2219 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2220 continue;
2221 }
2222
2223 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2224 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002225 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
2226 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002227
Eric Laurent1c333e22014-05-20 10:48:17 -07002228 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002229 audio_io_handle_t output = mpClientInterface->openOutput(
2230 outProfile->mModule->mHandle,
2231 &outputDesc->mDevice,
2232 &outputDesc->mSamplingRate,
2233 &outputDesc->mFormat,
2234 &outputDesc->mChannelMask,
2235 &outputDesc->mLatency,
2236 outputDesc->mFlags);
2237 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002238 ALOGW("Cannot open output stream for device %08x on hw module %s",
2239 outputDesc->mDevice,
2240 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002241 delete outputDesc;
2242 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002243 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002244 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002245 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002246 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002247 // give a valid ID to an attached device once confirmed it is reachable
2248 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2249 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002250 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002251 }
2252 }
Eric Laurente552edb2014-03-10 17:42:56 -07002253 if (mPrimaryOutput == 0 &&
2254 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2255 mPrimaryOutput = output;
2256 }
2257 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002258 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002259 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002260 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002261 true);
2262 }
2263 }
2264 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002265 // open input streams needed to access attached devices to validate
2266 // mAvailableInputDevices list
2267 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2268 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002269 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002270
Eric Laurent3a4311c2014-03-17 12:00:47 -07002271 if (inProfile->mSupportedDevices.isEmpty()) {
2272 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2273 continue;
2274 }
2275
2276 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2277 if (profileTypes & inputDeviceTypes) {
2278 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(inProfile);
2279
2280 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002281 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002282 audio_io_handle_t input = mpClientInterface->openInput(
2283 inProfile->mModule->mHandle,
2284 &inputDesc->mDevice,
2285 &inputDesc->mSamplingRate,
2286 &inputDesc->mFormat,
2287 &inputDesc->mChannelMask);
2288
2289 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002290 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002291 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002292 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002293 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002294 // give a valid ID to an attached device once confirmed it is reachable
2295 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2296 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002297 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002298 }
2299 }
2300 mpClientInterface->closeInput(input);
2301 } else {
2302 ALOGW("Cannot open input stream for device %08x on hw module %s",
2303 inputDesc->mDevice,
2304 mHwModules[i]->mName);
2305 }
2306 delete inputDesc;
2307 }
2308 }
2309 }
2310 // make sure all attached devices have been allocated a unique ID
2311 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2312 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002313 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002314 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2315 continue;
2316 }
2317 i++;
2318 }
2319 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2320 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002321 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002322 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2323 continue;
2324 }
2325 i++;
2326 }
2327 // make sure default device is reachable
2328 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002329 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002330 }
Eric Laurente552edb2014-03-10 17:42:56 -07002331
2332 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2333
2334 updateDevicesAndOutputs();
2335
2336#ifdef AUDIO_POLICY_TEST
2337 if (mPrimaryOutput != 0) {
2338 AudioParameter outputCmd = AudioParameter();
2339 outputCmd.addInt(String8("set_id"), 0);
2340 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2341
2342 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2343 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002344 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2345 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002346 mTestLatencyMs = 0;
2347 mCurOutput = 0;
2348 mDirectOutput = false;
2349 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2350 mTestOutputs[i] = 0;
2351 }
2352
2353 const size_t SIZE = 256;
2354 char buffer[SIZE];
2355 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2356 run(buffer, ANDROID_PRIORITY_AUDIO);
2357 }
2358#endif //AUDIO_POLICY_TEST
2359}
2360
Eric Laurente0720872014-03-11 09:30:41 -07002361AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002362{
2363#ifdef AUDIO_POLICY_TEST
2364 exit();
2365#endif //AUDIO_POLICY_TEST
2366 for (size_t i = 0; i < mOutputs.size(); i++) {
2367 mpClientInterface->closeOutput(mOutputs.keyAt(i));
2368 delete mOutputs.valueAt(i);
2369 }
2370 for (size_t i = 0; i < mInputs.size(); i++) {
2371 mpClientInterface->closeInput(mInputs.keyAt(i));
2372 delete mInputs.valueAt(i);
2373 }
2374 for (size_t i = 0; i < mHwModules.size(); i++) {
2375 delete mHwModules[i];
2376 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002377 mAvailableOutputDevices.clear();
2378 mAvailableInputDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002379}
2380
Eric Laurente0720872014-03-11 09:30:41 -07002381status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002382{
2383 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2384}
2385
2386#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002387bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002388{
2389 ALOGV("entering threadLoop()");
2390 while (!exitPending())
2391 {
2392 String8 command;
2393 int valueInt;
2394 String8 value;
2395
2396 Mutex::Autolock _l(mLock);
2397 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2398
2399 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2400 AudioParameter param = AudioParameter(command);
2401
2402 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2403 valueInt != 0) {
2404 ALOGV("Test command %s received", command.string());
2405 String8 target;
2406 if (param.get(String8("target"), target) != NO_ERROR) {
2407 target = "Manager";
2408 }
2409 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2410 param.remove(String8("test_cmd_policy_output"));
2411 mCurOutput = valueInt;
2412 }
2413 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2414 param.remove(String8("test_cmd_policy_direct"));
2415 if (value == "false") {
2416 mDirectOutput = false;
2417 } else if (value == "true") {
2418 mDirectOutput = true;
2419 }
2420 }
2421 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2422 param.remove(String8("test_cmd_policy_input"));
2423 mTestInput = valueInt;
2424 }
2425
2426 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2427 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002428 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002429 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002430 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002431 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002432 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002433 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002434 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002435 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002436 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002437 if (target == "Manager") {
2438 mTestFormat = format;
2439 } else if (mTestOutputs[mCurOutput] != 0) {
2440 AudioParameter outputParam = AudioParameter();
2441 outputParam.addInt(String8("format"), format);
2442 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2443 }
2444 }
2445 }
2446 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2447 param.remove(String8("test_cmd_policy_channels"));
2448 int channels = 0;
2449
2450 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002451 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002452 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002453 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002454 }
2455 if (channels != 0) {
2456 if (target == "Manager") {
2457 mTestChannels = channels;
2458 } else if (mTestOutputs[mCurOutput] != 0) {
2459 AudioParameter outputParam = AudioParameter();
2460 outputParam.addInt(String8("channels"), channels);
2461 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2462 }
2463 }
2464 }
2465 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2466 param.remove(String8("test_cmd_policy_sampleRate"));
2467 if (valueInt >= 0 && valueInt <= 96000) {
2468 int samplingRate = valueInt;
2469 if (target == "Manager") {
2470 mTestSamplingRate = samplingRate;
2471 } else if (mTestOutputs[mCurOutput] != 0) {
2472 AudioParameter outputParam = AudioParameter();
2473 outputParam.addInt(String8("sampling_rate"), samplingRate);
2474 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2475 }
2476 }
2477 }
2478
2479 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2480 param.remove(String8("test_cmd_policy_reopen"));
2481
2482 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2483 mpClientInterface->closeOutput(mPrimaryOutput);
2484
2485 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2486
2487 delete mOutputs.valueFor(mPrimaryOutput);
2488 mOutputs.removeItem(mPrimaryOutput);
2489
2490 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
2491 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2492 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2493 &outputDesc->mDevice,
2494 &outputDesc->mSamplingRate,
2495 &outputDesc->mFormat,
2496 &outputDesc->mChannelMask,
2497 &outputDesc->mLatency,
2498 outputDesc->mFlags);
2499 if (mPrimaryOutput == 0) {
2500 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2501 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2502 } else {
2503 AudioParameter outputCmd = AudioParameter();
2504 outputCmd.addInt(String8("set_id"), 0);
2505 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2506 addOutput(mPrimaryOutput, outputDesc);
2507 }
2508 }
2509
2510
2511 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2512 }
2513 }
2514 return false;
2515}
2516
Eric Laurente0720872014-03-11 09:30:41 -07002517void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002518{
2519 {
2520 AutoMutex _l(mLock);
2521 requestExit();
2522 mWaitWorkCV.signal();
2523 }
2524 requestExitAndWait();
2525}
2526
Eric Laurente0720872014-03-11 09:30:41 -07002527int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002528{
2529 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2530 if (output == mTestOutputs[i]) return i;
2531 }
2532 return 0;
2533}
2534#endif //AUDIO_POLICY_TEST
2535
2536// ---
2537
Eric Laurent1c333e22014-05-20 10:48:17 -07002538void AudioPolicyManager::addOutput(audio_io_handle_t output, AudioOutputDescriptor *outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002539{
Eric Laurent1c333e22014-05-20 10:48:17 -07002540 outputDesc->mIoHandle = output;
2541 outputDesc->mId = nextUniqueId();
2542 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002543 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002544}
2545
Eric Laurent1c333e22014-05-20 10:48:17 -07002546void AudioPolicyManager::addInput(audio_io_handle_t input, AudioInputDescriptor *inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002547{
Eric Laurent1c333e22014-05-20 10:48:17 -07002548 inputDesc->mIoHandle = input;
2549 inputDesc->mId = nextUniqueId();
2550 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002551 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002552}
Eric Laurente552edb2014-03-10 17:42:56 -07002553
Eric Laurent3a4311c2014-03-17 12:00:47 -07002554String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2555{
2556 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2557 return String8("a2dp_sink_address=")+address;
2558 }
2559 return address;
2560}
2561
Eric Laurente0720872014-03-11 09:30:41 -07002562status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002563 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002564 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002565 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002566{
2567 AudioOutputDescriptor *desc;
2568
Eric Laurent3b73df72014-03-11 09:06:29 -07002569 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002570 // first list already open outputs that can be routed to this device
2571 for (size_t i = 0; i < mOutputs.size(); i++) {
2572 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002573 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002574 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2575 outputs.add(mOutputs.keyAt(i));
2576 }
2577 }
2578 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002579 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002580 for (size_t i = 0; i < mHwModules.size(); i++)
2581 {
2582 if (mHwModules[i]->mHandle == 0) {
2583 continue;
2584 }
2585 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2586 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002587 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002588 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002589 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2590 }
2591 }
2592 }
2593
2594 if (profiles.isEmpty() && outputs.isEmpty()) {
2595 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2596 return BAD_VALUE;
2597 }
2598
2599 // open outputs for matching profiles if needed. Direct outputs are also opened to
2600 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2601 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002602 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002603
2604 // nothing to do if one output is already opened for this profile
2605 size_t j;
2606 for (j = 0; j < mOutputs.size(); j++) {
2607 desc = mOutputs.valueAt(j);
2608 if (!desc->isDuplicated() && desc->mProfile == profile) {
2609 break;
2610 }
2611 }
2612 if (j != mOutputs.size()) {
2613 continue;
2614 }
2615
Eric Laurent3a4311c2014-03-17 12:00:47 -07002616 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002617 desc = new AudioOutputDescriptor(profile);
2618 desc->mDevice = device;
2619 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2620 offloadInfo.sample_rate = desc->mSamplingRate;
2621 offloadInfo.format = desc->mFormat;
2622 offloadInfo.channel_mask = desc->mChannelMask;
2623
2624 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2625 &desc->mDevice,
2626 &desc->mSamplingRate,
2627 &desc->mFormat,
2628 &desc->mChannelMask,
2629 &desc->mLatency,
2630 desc->mFlags,
2631 &offloadInfo);
2632 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002633 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002634 if (!address.isEmpty()) {
2635 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002636 }
2637
Eric Laurentd4692962014-05-05 18:13:44 -07002638 // Here is where we step through and resolve any "dynamic" fields
2639 String8 reply;
2640 char *value;
2641 if (profile->mSamplingRates[0] == 0) {
2642 reply = mpClientInterface->getParameters(output,
2643 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2644 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2645 reply.string());
2646 value = strpbrk((char *)reply.string(), "=");
2647 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002648 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002649 }
Eric Laurentd4692962014-05-05 18:13:44 -07002650 }
2651 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2652 reply = mpClientInterface->getParameters(output,
2653 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2654 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2655 reply.string());
2656 value = strpbrk((char *)reply.string(), "=");
2657 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002658 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002659 }
Eric Laurentd4692962014-05-05 18:13:44 -07002660 }
2661 if (profile->mChannelMasks[0] == 0) {
2662 reply = mpClientInterface->getParameters(output,
2663 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2664 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2665 reply.string());
2666 value = strpbrk((char *)reply.string(), "=");
2667 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002668 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002669 }
Eric Laurentd4692962014-05-05 18:13:44 -07002670 }
2671 if (((profile->mSamplingRates[0] == 0) &&
2672 (profile->mSamplingRates.size() < 2)) ||
2673 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2674 (profile->mFormats.size() < 2)) ||
2675 ((profile->mChannelMasks[0] == 0) &&
2676 (profile->mChannelMasks.size() < 2))) {
2677 ALOGW("checkOutputsForDevice() direct output missing param");
2678 mpClientInterface->closeOutput(output);
2679 output = 0;
2680 } else if (profile->mSamplingRates[0] == 0) {
2681 mpClientInterface->closeOutput(output);
2682 desc->mSamplingRate = profile->mSamplingRates[1];
2683 offloadInfo.sample_rate = desc->mSamplingRate;
2684 output = mpClientInterface->openOutput(
2685 profile->mModule->mHandle,
2686 &desc->mDevice,
2687 &desc->mSamplingRate,
2688 &desc->mFormat,
2689 &desc->mChannelMask,
2690 &desc->mLatency,
2691 desc->mFlags,
2692 &offloadInfo);
2693 }
2694
2695 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002696 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002697 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2698 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002699
Eric Laurentd4692962014-05-05 18:13:44 -07002700 // set initial stream volume for device
2701 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002702
Eric Laurentd4692962014-05-05 18:13:44 -07002703 //TODO: configure audio effect output stage here
2704
2705 // open a duplicating output thread for the new output and the primary output
2706 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2707 mPrimaryOutput);
2708 if (duplicatedOutput != 0) {
2709 // add duplicated output descriptor
2710 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
2711 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2712 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2713 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2714 dupOutputDesc->mFormat = desc->mFormat;
2715 dupOutputDesc->mChannelMask = desc->mChannelMask;
2716 dupOutputDesc->mLatency = desc->mLatency;
2717 addOutput(duplicatedOutput, dupOutputDesc);
2718 applyStreamVolumes(duplicatedOutput, device, 0, true);
2719 } else {
2720 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2721 mPrimaryOutput, output);
2722 mpClientInterface->closeOutput(output);
2723 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002724 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002725 output = 0;
2726 }
Eric Laurente552edb2014-03-10 17:42:56 -07002727 }
2728 }
2729 }
2730 if (output == 0) {
2731 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2732 delete desc;
2733 profiles.removeAt(profile_index);
2734 profile_index--;
2735 } else {
2736 outputs.add(output);
2737 ALOGV("checkOutputsForDevice(): adding output %d", output);
2738 }
2739 }
2740
2741 if (profiles.isEmpty()) {
2742 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2743 return BAD_VALUE;
2744 }
Eric Laurentd4692962014-05-05 18:13:44 -07002745 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002746 // check if one opened output is not needed any more after disconnecting one device
2747 for (size_t i = 0; i < mOutputs.size(); i++) {
2748 desc = mOutputs.valueAt(i);
2749 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002750 !(desc->mProfile->mSupportedDevices.types() &
2751 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002752 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2753 outputs.add(mOutputs.keyAt(i));
2754 }
2755 }
Eric Laurentd4692962014-05-05 18:13:44 -07002756 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002757 for (size_t i = 0; i < mHwModules.size(); i++)
2758 {
2759 if (mHwModules[i]->mHandle == 0) {
2760 continue;
2761 }
2762 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2763 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002764 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002765 if (profile->mSupportedDevices.types() & device) {
2766 ALOGV("checkOutputsForDevice(): "
2767 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002768 if (profile->mSamplingRates[0] == 0) {
2769 profile->mSamplingRates.clear();
2770 profile->mSamplingRates.add(0);
2771 }
2772 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2773 profile->mFormats.clear();
2774 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2775 }
2776 if (profile->mChannelMasks[0] == 0) {
2777 profile->mChannelMasks.clear();
2778 profile->mChannelMasks.add(0);
2779 }
2780 }
2781 }
2782 }
2783 }
2784 return NO_ERROR;
2785}
2786
Eric Laurentd4692962014-05-05 18:13:44 -07002787status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2788 audio_policy_dev_state_t state,
2789 SortedVector<audio_io_handle_t>& inputs,
2790 const String8 address)
2791{
2792 AudioInputDescriptor *desc;
2793 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2794 // first list already open inputs that can be routed to this device
2795 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2796 desc = mInputs.valueAt(input_index);
2797 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2798 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2799 inputs.add(mInputs.keyAt(input_index));
2800 }
2801 }
2802
2803 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002804 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002805 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2806 {
2807 if (mHwModules[module_idx]->mHandle == 0) {
2808 continue;
2809 }
2810 for (size_t profile_index = 0;
2811 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2812 profile_index++)
2813 {
2814 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2815 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2816 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2817 profile_index, module_idx);
2818 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2819 }
2820 }
2821 }
2822
2823 if (profiles.isEmpty() && inputs.isEmpty()) {
2824 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2825 return BAD_VALUE;
2826 }
2827
2828 // open inputs for matching profiles if needed. Direct inputs are also opened to
2829 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2830 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2831
Eric Laurent1c333e22014-05-20 10:48:17 -07002832 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002833 // nothing to do if one input is already opened for this profile
2834 size_t input_index;
2835 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2836 desc = mInputs.valueAt(input_index);
2837 if (desc->mProfile == profile) {
2838 break;
2839 }
2840 }
2841 if (input_index != mInputs.size()) {
2842 continue;
2843 }
2844
2845 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2846 desc = new AudioInputDescriptor(profile);
2847 desc->mDevice = device;
2848
2849 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2850 &desc->mDevice,
2851 &desc->mSamplingRate,
2852 &desc->mFormat,
2853 &desc->mChannelMask);
2854
2855 if (input != 0) {
2856 if (!address.isEmpty()) {
2857 mpClientInterface->setParameters(input, addressToParameter(device, address));
2858 }
2859
2860 // Here is where we step through and resolve any "dynamic" fields
2861 String8 reply;
2862 char *value;
2863 if (profile->mSamplingRates[0] == 0) {
2864 reply = mpClientInterface->getParameters(input,
2865 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2866 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2867 reply.string());
2868 value = strpbrk((char *)reply.string(), "=");
2869 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002870 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002871 }
2872 }
2873 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2874 reply = mpClientInterface->getParameters(input,
2875 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2876 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2877 value = strpbrk((char *)reply.string(), "=");
2878 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002879 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002880 }
2881 }
2882 if (profile->mChannelMasks[0] == 0) {
2883 reply = mpClientInterface->getParameters(input,
2884 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2885 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2886 reply.string());
2887 value = strpbrk((char *)reply.string(), "=");
2888 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002889 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002890 }
2891 }
2892 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2893 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2894 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2895 ALOGW("checkInputsForDevice() direct input missing param");
2896 mpClientInterface->closeInput(input);
2897 input = 0;
2898 }
2899
2900 if (input != 0) {
2901 addInput(input, desc);
2902 }
2903 } // endif input != 0
2904
2905 if (input == 0) {
2906 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2907 delete desc;
2908 profiles.removeAt(profile_index);
2909 profile_index--;
2910 } else {
2911 inputs.add(input);
2912 ALOGV("checkInputsForDevice(): adding input %d", input);
2913 }
2914 } // end scan profiles
2915
2916 if (profiles.isEmpty()) {
2917 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2918 return BAD_VALUE;
2919 }
2920 } else {
2921 // Disconnect
2922 // check if one opened input is not needed any more after disconnecting one device
2923 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2924 desc = mInputs.valueAt(input_index);
2925 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2926 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2927 mInputs.keyAt(input_index));
2928 inputs.add(mInputs.keyAt(input_index));
2929 }
2930 }
2931 // Clear any profiles associated with the disconnected device.
2932 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2933 if (mHwModules[module_index]->mHandle == 0) {
2934 continue;
2935 }
2936 for (size_t profile_index = 0;
2937 profile_index < mHwModules[module_index]->mInputProfiles.size();
2938 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002939 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002940 if (profile->mSupportedDevices.types() & device) {
2941 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2942 profile_index, module_index);
2943 if (profile->mSamplingRates[0] == 0) {
2944 profile->mSamplingRates.clear();
2945 profile->mSamplingRates.add(0);
2946 }
2947 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2948 profile->mFormats.clear();
2949 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2950 }
2951 if (profile->mChannelMasks[0] == 0) {
2952 profile->mChannelMasks.clear();
2953 profile->mChannelMasks.add(0);
2954 }
2955 }
2956 }
2957 }
2958 } // end disconnect
2959
2960 return NO_ERROR;
2961}
2962
2963
Eric Laurente0720872014-03-11 09:30:41 -07002964void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002965{
2966 ALOGV("closeOutput(%d)", output);
2967
2968 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2969 if (outputDesc == NULL) {
2970 ALOGW("closeOutput() unknown output %d", output);
2971 return;
2972 }
2973
2974 // look for duplicated outputs connected to the output being removed.
2975 for (size_t i = 0; i < mOutputs.size(); i++) {
2976 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2977 if (dupOutputDesc->isDuplicated() &&
2978 (dupOutputDesc->mOutput1 == outputDesc ||
2979 dupOutputDesc->mOutput2 == outputDesc)) {
2980 AudioOutputDescriptor *outputDesc2;
2981 if (dupOutputDesc->mOutput1 == outputDesc) {
2982 outputDesc2 = dupOutputDesc->mOutput2;
2983 } else {
2984 outputDesc2 = dupOutputDesc->mOutput1;
2985 }
2986 // As all active tracks on duplicated output will be deleted,
2987 // and as they were also referenced on the other output, the reference
2988 // count for their stream type must be adjusted accordingly on
2989 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07002990 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07002991 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07002992 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07002993 }
2994 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2995 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2996
2997 mpClientInterface->closeOutput(duplicatedOutput);
2998 delete mOutputs.valueFor(duplicatedOutput);
2999 mOutputs.removeItem(duplicatedOutput);
3000 }
3001 }
3002
3003 AudioParameter param;
3004 param.add(String8("closing"), String8("true"));
3005 mpClientInterface->setParameters(output, param.toString());
3006
3007 mpClientInterface->closeOutput(output);
3008 delete outputDesc;
3009 mOutputs.removeItem(output);
3010 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003011 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003012}
3013
Eric Laurente0720872014-03-11 09:30:41 -07003014SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003015 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
3016{
3017 SortedVector<audio_io_handle_t> outputs;
3018
3019 ALOGVV("getOutputsForDevice() device %04x", device);
3020 for (size_t i = 0; i < openOutputs.size(); i++) {
3021 ALOGVV("output %d isDuplicated=%d device=%04x",
3022 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3023 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3024 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3025 outputs.add(openOutputs.keyAt(i));
3026 }
3027 }
3028 return outputs;
3029}
3030
Eric Laurente0720872014-03-11 09:30:41 -07003031bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003032 SortedVector<audio_io_handle_t>& outputs2)
3033{
3034 if (outputs1.size() != outputs2.size()) {
3035 return false;
3036 }
3037 for (size_t i = 0; i < outputs1.size(); i++) {
3038 if (outputs1[i] != outputs2[i]) {
3039 return false;
3040 }
3041 }
3042 return true;
3043}
3044
Eric Laurente0720872014-03-11 09:30:41 -07003045void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003046{
3047 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3048 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3049 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3050 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3051
3052 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3053 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3054 strategy, srcOutputs[0], dstOutputs[0]);
3055 // mute strategy while moving tracks from one output to another
3056 for (size_t i = 0; i < srcOutputs.size(); i++) {
3057 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
3058 if (desc->isStrategyActive(strategy)) {
3059 setStrategyMute(strategy, true, srcOutputs[i]);
3060 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3061 }
3062 }
3063
3064 // Move effects associated to this strategy from previous output to new output
3065 if (strategy == STRATEGY_MEDIA) {
3066 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3067 SortedVector<audio_io_handle_t> moved;
3068 for (size_t i = 0; i < mEffects.size(); i++) {
3069 EffectDescriptor *desc = mEffects.valueAt(i);
3070 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3071 desc->mIo != fxOutput) {
3072 if (moved.indexOf(desc->mIo) < 0) {
3073 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3074 mEffects.keyAt(i), fxOutput);
3075 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
3076 fxOutput);
3077 moved.add(desc->mIo);
3078 }
3079 desc->mIo = fxOutput;
3080 }
3081 }
3082 }
3083 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003084 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3085 if (getStrategy((audio_stream_type_t)i) == strategy) {
3086 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003087 }
3088 }
3089 }
3090}
3091
Eric Laurente0720872014-03-11 09:30:41 -07003092void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003093{
3094 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3095 checkOutputForStrategy(STRATEGY_PHONE);
3096 checkOutputForStrategy(STRATEGY_SONIFICATION);
3097 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3098 checkOutputForStrategy(STRATEGY_MEDIA);
3099 checkOutputForStrategy(STRATEGY_DTMF);
3100}
3101
Eric Laurente0720872014-03-11 09:30:41 -07003102audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003103{
Eric Laurente552edb2014-03-10 17:42:56 -07003104 for (size_t i = 0; i < mOutputs.size(); i++) {
3105 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
3106 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3107 return mOutputs.keyAt(i);
3108 }
3109 }
3110
3111 return 0;
3112}
3113
Eric Laurente0720872014-03-11 09:30:41 -07003114void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003115{
Eric Laurente552edb2014-03-10 17:42:56 -07003116 audio_io_handle_t a2dpOutput = getA2dpOutput();
3117 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003118 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003119 return;
3120 }
3121
Eric Laurent3a4311c2014-03-17 12:00:47 -07003122 bool isScoConnected =
3123 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003124 // suspend A2DP output if:
3125 // (NOT already suspended) &&
3126 // ((SCO device is connected &&
3127 // (forced usage for communication || for record is SCO))) ||
3128 // (phone state is ringing || in call)
3129 //
3130 // restore A2DP output if:
3131 // (Already suspended) &&
3132 // ((SCO device is NOT connected ||
3133 // (forced usage NOT for communication && NOT for record is SCO))) &&
3134 // (phone state is NOT ringing && NOT in call)
3135 //
3136 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003137 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003138 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3139 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3140 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3141 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003142
3143 mpClientInterface->restoreOutput(a2dpOutput);
3144 mA2dpSuspended = false;
3145 }
3146 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003147 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003148 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3149 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3150 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3151 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003152
3153 mpClientInterface->suspendOutput(a2dpOutput);
3154 mA2dpSuspended = true;
3155 }
3156 }
3157}
3158
Eric Laurent1c333e22014-05-20 10:48:17 -07003159audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003160{
3161 audio_devices_t device = AUDIO_DEVICE_NONE;
3162
3163 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003164
3165 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3166 if (index >= 0) {
3167 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3168 if (patchDesc->mUid != mUidCached) {
3169 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3170 outputDesc->device(), outputDesc->mPatchHandle);
3171 return outputDesc->device();
3172 }
3173 }
3174
Eric Laurente552edb2014-03-10 17:42:56 -07003175 // check the following by order of priority to request a routing change if necessary:
3176 // 1: the strategy enforced audible is active on the output:
3177 // use device for strategy enforced audible
3178 // 2: we are in call or the strategy phone is active on the output:
3179 // use device for strategy phone
3180 // 3: the strategy sonification is active on the output:
3181 // use device for strategy sonification
3182 // 4: the strategy "respectful" sonification is active on the output:
3183 // use device for strategy "respectful" sonification
3184 // 5: the strategy media is active on the output:
3185 // use device for strategy media
3186 // 6: the strategy DTMF is active on the output:
3187 // use device for strategy DTMF
3188 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3189 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3190 } else if (isInCall() ||
3191 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3192 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3193 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3194 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3195 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3196 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3197 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3198 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3199 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3200 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3201 }
3202
Eric Laurent1c333e22014-05-20 10:48:17 -07003203 ALOGV("getNewOutputDevice() selected device %x", device);
3204 return device;
3205}
3206
3207audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3208{
3209 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003210
3211 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3212 if (index >= 0) {
3213 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3214 if (patchDesc->mUid != mUidCached) {
3215 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3216 inputDesc->mDevice, inputDesc->mPatchHandle);
3217 return inputDesc->mDevice;
3218 }
3219 }
3220
Eric Laurent1c333e22014-05-20 10:48:17 -07003221 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3222
3223 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003224 return device;
3225}
3226
Eric Laurente0720872014-03-11 09:30:41 -07003227uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003228 return (uint32_t)getStrategy(stream);
3229}
3230
Eric Laurente0720872014-03-11 09:30:41 -07003231audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003232 // By checking the range of stream before calling getStrategy, we avoid
3233 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3234 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003235 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003236 return AUDIO_DEVICE_NONE;
3237 }
3238 audio_devices_t devices;
3239 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3240 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3241 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3242 for (size_t i = 0; i < outputs.size(); i++) {
3243 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
3244 if (outputDesc->isStrategyActive(strategy)) {
3245 devices = outputDesc->device();
3246 break;
3247 }
Eric Laurente552edb2014-03-10 17:42:56 -07003248 }
3249 return devices;
3250}
3251
Eric Laurente0720872014-03-11 09:30:41 -07003252AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003253 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003254 // stream to strategy mapping
3255 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003256 case AUDIO_STREAM_VOICE_CALL:
3257 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003258 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003259 case AUDIO_STREAM_RING:
3260 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003261 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003262 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003263 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003264 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003265 return STRATEGY_DTMF;
3266 default:
3267 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003268 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003269 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3270 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003271 case AUDIO_STREAM_TTS:
3272 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003273 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003274 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003275 return STRATEGY_ENFORCED_AUDIBLE;
3276 }
3277}
3278
Eric Laurente0720872014-03-11 09:30:41 -07003279void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003280 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003281 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003282 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3283 updateDevicesAndOutputs();
3284 break;
3285 default:
3286 break;
3287 }
3288}
3289
Eric Laurente0720872014-03-11 09:30:41 -07003290audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003291 bool fromCache)
3292{
3293 uint32_t device = AUDIO_DEVICE_NONE;
3294
3295 if (fromCache) {
3296 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3297 strategy, mDeviceForStrategy[strategy]);
3298 return mDeviceForStrategy[strategy];
3299 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003300 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003301 switch (strategy) {
3302
3303 case STRATEGY_SONIFICATION_RESPECTFUL:
3304 if (isInCall()) {
3305 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003306 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003307 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3308 // while media is playing on a remote device, use the the sonification behavior.
3309 // Note that we test this usecase before testing if media is playing because
3310 // the isStreamActive() method only informs about the activity of a stream, not
3311 // if it's for local playback. Note also that we use the same delay between both tests
3312 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003313 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003314 // while media is playing (or has recently played), use the same device
3315 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3316 } else {
3317 // when media is not playing anymore, fall back on the sonification behavior
3318 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3319 }
3320
3321 break;
3322
3323 case STRATEGY_DTMF:
3324 if (!isInCall()) {
3325 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3326 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3327 break;
3328 }
3329 // when in call, DTMF and PHONE strategies follow the same rules
3330 // FALL THROUGH
3331
3332 case STRATEGY_PHONE:
3333 // for phone strategy, we first consider the forced use and then the available devices by order
3334 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003335 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3336 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003337 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003338 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003339 if (device) break;
3340 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003341 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003342 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003343 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003344 if (device) break;
3345 // if SCO device is requested but no SCO device is available, fall back to default case
3346 // FALL THROUGH
3347
3348 default: // FORCE_NONE
3349 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003350 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003351 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003352 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003353 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003354 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003355 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003356 if (device) break;
3357 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003358 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003359 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003360 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003361 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003362 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003363 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003364 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003365 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003366 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003367 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003368 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003369 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003370 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003371 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003372 if (device) break;
3373 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003374 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003375 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003376 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003377 if (device == AUDIO_DEVICE_NONE) {
3378 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3379 }
3380 break;
3381
Eric Laurent3b73df72014-03-11 09:06:29 -07003382 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003383 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3384 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003385 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003386 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003387 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003388 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003389 if (device) break;
3390 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003391 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003392 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003393 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003394 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003395 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003396 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003397 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003398 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003399 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003400 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003401 if (device) break;
3402 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003403 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003404 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003405 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003406 if (device == AUDIO_DEVICE_NONE) {
3407 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3408 }
3409 break;
3410 }
3411 break;
3412
3413 case STRATEGY_SONIFICATION:
3414
3415 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3416 // handleIncallSonification().
3417 if (isInCall()) {
3418 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3419 break;
3420 }
3421 // FALL THROUGH
3422
3423 case STRATEGY_ENFORCED_AUDIBLE:
3424 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3425 // except:
3426 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3427 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3428
3429 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003430 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003431 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003432 if (device == AUDIO_DEVICE_NONE) {
3433 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3434 }
3435 }
3436 // The second device used for sonification is the same as the device used by media strategy
3437 // FALL THROUGH
3438
3439 case STRATEGY_MEDIA: {
3440 uint32_t device2 = AUDIO_DEVICE_NONE;
3441 if (strategy != STRATEGY_SONIFICATION) {
3442 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003443 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003444 }
3445 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003446 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003447 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003448 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003449 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003450 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003451 }
3452 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003453 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003454 }
3455 }
3456 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003457 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003458 }
3459 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003460 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003461 }
3462 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003463 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003464 }
3465 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003466 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003467 }
3468 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003469 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003470 }
3471 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3472 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003473 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003474 }
3475 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003476 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003477 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003478 }
3479 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003480 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003481 }
3482
3483 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3484 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3485 device |= device2;
3486 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003487 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003488 if (device == AUDIO_DEVICE_NONE) {
3489 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3490 }
3491 } break;
3492
3493 default:
3494 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3495 break;
3496 }
3497
3498 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3499 return device;
3500}
3501
Eric Laurente0720872014-03-11 09:30:41 -07003502void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003503{
3504 for (int i = 0; i < NUM_STRATEGIES; i++) {
3505 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3506 }
3507 mPreviousOutputs = mOutputs;
3508}
3509
Eric Laurente0720872014-03-11 09:30:41 -07003510uint32_t AudioPolicyManager::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003511 audio_devices_t prevDevice,
3512 uint32_t delayMs)
3513{
3514 // mute/unmute strategies using an incompatible device combination
3515 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3516 // if unmuting, unmute only after the specified delay
3517 if (outputDesc->isDuplicated()) {
3518 return 0;
3519 }
3520
3521 uint32_t muteWaitMs = 0;
3522 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003523 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003524
3525 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3526 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3527 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3528 bool doMute = false;
3529
3530 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3531 doMute = true;
3532 outputDesc->mStrategyMutedByDevice[i] = true;
3533 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3534 doMute = true;
3535 outputDesc->mStrategyMutedByDevice[i] = false;
3536 }
Eric Laurent99401132014-05-07 19:48:15 -07003537 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003538 for (size_t j = 0; j < mOutputs.size(); j++) {
3539 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
3540 // skip output if it does not share any device with current output
3541 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3542 == AUDIO_DEVICE_NONE) {
3543 continue;
3544 }
3545 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3546 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3547 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3548 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3549 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003550 if (mute) {
3551 // FIXME: should not need to double latency if volume could be applied
3552 // immediately by the audioflinger mixer. We must account for the delay
3553 // between now and the next time the audioflinger thread for this output
3554 // will process a buffer (which corresponds to one buffer size,
3555 // usually 1/2 or 1/4 of the latency).
3556 if (muteWaitMs < desc->latency() * 2) {
3557 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003558 }
3559 }
3560 }
3561 }
3562 }
3563 }
3564
Eric Laurent99401132014-05-07 19:48:15 -07003565 // temporary mute output if device selection changes to avoid volume bursts due to
3566 // different per device volumes
3567 if (outputDesc->isActive() && (device != prevDevice)) {
3568 if (muteWaitMs < outputDesc->latency() * 2) {
3569 muteWaitMs = outputDesc->latency() * 2;
3570 }
3571 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3572 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003573 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003574 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003575 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003576 muteWaitMs *2, device);
3577 }
3578 }
3579 }
3580
Eric Laurente552edb2014-03-10 17:42:56 -07003581 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3582 if (muteWaitMs > delayMs) {
3583 muteWaitMs -= delayMs;
3584 usleep(muteWaitMs * 1000);
3585 return muteWaitMs;
3586 }
3587 return 0;
3588}
3589
Eric Laurente0720872014-03-11 09:30:41 -07003590uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003591 audio_devices_t device,
3592 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003593 int delayMs,
3594 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003595{
3596 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
3597 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3598 AudioParameter param;
3599 uint32_t muteWaitMs;
3600
3601 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003602 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3603 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003604 return muteWaitMs;
3605 }
3606 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3607 // output profile
3608 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003609 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003610 return 0;
3611 }
3612
3613 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003614 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003615
3616 audio_devices_t prevDevice = outputDesc->mDevice;
3617
3618 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3619
3620 if (device != AUDIO_DEVICE_NONE) {
3621 outputDesc->mDevice = device;
3622 }
3623 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3624
3625 // Do not change the routing if:
3626 // - the requested device is AUDIO_DEVICE_NONE
3627 // - the requested device is the same as current device and force is not specified.
3628 // Doing this check here allows the caller to call setOutputDevice() without conditions
3629 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3630 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3631 return muteWaitMs;
3632 }
3633
3634 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003635
Eric Laurente552edb2014-03-10 17:42:56 -07003636 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003637 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003638 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003639 } else {
3640 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3641 if (!deviceList.isEmpty()) {
3642 struct audio_patch patch;
3643 outputDesc->toAudioPortConfig(&patch.sources[0]);
3644 patch.num_sources = 1;
3645 patch.num_sinks = 0;
3646 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3647 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003648 patch.num_sinks++;
3649 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003650 ssize_t index;
3651 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3652 index = mAudioPatches.indexOfKey(*patchHandle);
3653 } else {
3654 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3655 }
3656 sp< AudioPatch> patchDesc;
3657 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3658 if (index >= 0) {
3659 patchDesc = mAudioPatches.valueAt(index);
3660 afPatchHandle = patchDesc->mAfPatchHandle;
3661 }
3662
Eric Laurent1c333e22014-05-20 10:48:17 -07003663 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003664 &afPatchHandle,
3665 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003666 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3667 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003668 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003669 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003670 if (index < 0) {
3671 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3672 &patch, mUidCached);
3673 addAudioPatch(patchDesc->mHandle, patchDesc);
3674 } else {
3675 patchDesc->mPatch = patch;
3676 }
3677 patchDesc->mAfPatchHandle = afPatchHandle;
3678 patchDesc->mUid = mUidCached;
3679 if (patchHandle) {
3680 *patchHandle = patchDesc->mHandle;
3681 }
3682 outputDesc->mPatchHandle = patchDesc->mHandle;
3683 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003684 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003685 }
3686 }
3687 }
Eric Laurente552edb2014-03-10 17:42:56 -07003688
3689 // update stream volumes according to new device
3690 applyStreamVolumes(output, device, delayMs);
3691
3692 return muteWaitMs;
3693}
3694
Eric Laurent1c333e22014-05-20 10:48:17 -07003695status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003696 int delayMs,
3697 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003698{
3699 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003700 ssize_t index;
3701 if (patchHandle) {
3702 index = mAudioPatches.indexOfKey(*patchHandle);
3703 } else {
3704 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3705 }
3706 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003707 return INVALID_OPERATION;
3708 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003709 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3710 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003711 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3712 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003713 removeAudioPatch(patchDesc->mHandle);
3714 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003715 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003716 return status;
3717}
3718
3719status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3720 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003721 bool force,
3722 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003723{
3724 status_t status = NO_ERROR;
3725
3726 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
3727 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3728 inputDesc->mDevice = device;
3729
3730 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3731 if (!deviceList.isEmpty()) {
3732 struct audio_patch patch;
3733 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3734 patch.num_sinks = 1;
3735 //only one input device for now
3736 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003737 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003738 ssize_t index;
3739 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3740 index = mAudioPatches.indexOfKey(*patchHandle);
3741 } else {
3742 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3743 }
3744 sp< AudioPatch> patchDesc;
3745 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3746 if (index >= 0) {
3747 patchDesc = mAudioPatches.valueAt(index);
3748 afPatchHandle = patchDesc->mAfPatchHandle;
3749 }
3750
Eric Laurent1c333e22014-05-20 10:48:17 -07003751 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003752 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003753 0);
3754 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003755 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003756 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003757 if (index < 0) {
3758 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3759 &patch, mUidCached);
3760 addAudioPatch(patchDesc->mHandle, patchDesc);
3761 } else {
3762 patchDesc->mPatch = patch;
3763 }
3764 patchDesc->mAfPatchHandle = afPatchHandle;
3765 patchDesc->mUid = mUidCached;
3766 if (patchHandle) {
3767 *patchHandle = patchDesc->mHandle;
3768 }
3769 inputDesc->mPatchHandle = patchDesc->mHandle;
3770 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003771 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003772 }
3773 }
3774 }
3775 return status;
3776}
3777
Eric Laurent6a94d692014-05-20 11:18:06 -07003778status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3779 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003780{
3781 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003782 ssize_t index;
3783 if (patchHandle) {
3784 index = mAudioPatches.indexOfKey(*patchHandle);
3785 } else {
3786 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3787 }
3788 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003789 return INVALID_OPERATION;
3790 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003791 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3792 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003793 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3794 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003795 removeAudioPatch(patchDesc->mHandle);
3796 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003797 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003798 return status;
3799}
3800
3801sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003802 uint32_t samplingRate,
3803 audio_format_t format,
3804 audio_channel_mask_t channelMask)
3805{
3806 // Choose an input profile based on the requested capture parameters: select the first available
3807 // profile supporting all requested parameters.
3808
3809 for (size_t i = 0; i < mHwModules.size(); i++)
3810 {
3811 if (mHwModules[i]->mHandle == 0) {
3812 continue;
3813 }
3814 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3815 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003816 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003817 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003818 if (profile->isCompatibleProfile(device, samplingRate, format,
3819 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3820 return profile;
3821 }
3822 }
3823 }
3824 return NULL;
3825}
3826
Eric Laurente0720872014-03-11 09:30:41 -07003827audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003828{
3829 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003830 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3831 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003832 switch (inputSource) {
3833 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003834 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003835 device = AUDIO_DEVICE_IN_VOICE_CALL;
3836 break;
3837 }
3838 // FALL THROUGH
3839
3840 case AUDIO_SOURCE_DEFAULT:
3841 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003842 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3843 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3844 break;
3845 }
3846 // FALL THROUGH
3847
Eric Laurente552edb2014-03-10 17:42:56 -07003848 case AUDIO_SOURCE_VOICE_RECOGNITION:
3849 case AUDIO_SOURCE_HOTWORD:
3850 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003851 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003852 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003853 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003854 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003855 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003856 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3857 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003858 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003859 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3860 }
3861 break;
3862 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003863 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003864 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003865 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003866 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3867 }
3868 break;
3869 case AUDIO_SOURCE_VOICE_DOWNLINK:
3870 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003871 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003872 device = AUDIO_DEVICE_IN_VOICE_CALL;
3873 }
3874 break;
3875 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003876 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003877 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3878 }
3879 break;
3880 default:
3881 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3882 break;
3883 }
3884 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3885 return device;
3886}
3887
Eric Laurente0720872014-03-11 09:30:41 -07003888bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003889{
3890 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3891 device &= ~AUDIO_DEVICE_BIT_IN;
3892 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3893 return true;
3894 }
3895 return false;
3896}
3897
Eric Laurente0720872014-03-11 09:30:41 -07003898audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003899{
3900 for (size_t i = 0; i < mInputs.size(); i++) {
3901 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
3902 if ((input_descriptor->mRefCount > 0)
3903 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3904 return mInputs.keyAt(i);
3905 }
3906 }
3907 return 0;
3908}
3909
3910
Eric Laurente0720872014-03-11 09:30:41 -07003911audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003912{
3913 if (device == AUDIO_DEVICE_NONE) {
3914 // this happens when forcing a route update and no track is active on an output.
3915 // In this case the returned category is not important.
3916 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003917 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003918 // Multiple device selection is either:
3919 // - speaker + one other device: give priority to speaker in this case.
3920 // - one A2DP device + another device: happens with duplicated output. In this case
3921 // retain the device on the A2DP output as the other must not correspond to an active
3922 // selection if not the speaker.
3923 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3924 device = AUDIO_DEVICE_OUT_SPEAKER;
3925 } else {
3926 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3927 }
3928 }
3929
Eric Laurent3b73df72014-03-11 09:06:29 -07003930 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003931 "getDeviceForVolume() invalid device combination: %08x",
3932 device);
3933
3934 return device;
3935}
3936
Eric Laurente0720872014-03-11 09:30:41 -07003937AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003938{
3939 switch(getDeviceForVolume(device)) {
3940 case AUDIO_DEVICE_OUT_EARPIECE:
3941 return DEVICE_CATEGORY_EARPIECE;
3942 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3943 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3944 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3945 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3946 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3947 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3948 return DEVICE_CATEGORY_HEADSET;
3949 case AUDIO_DEVICE_OUT_SPEAKER:
3950 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3951 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3952 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3953 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3954 case AUDIO_DEVICE_OUT_USB_DEVICE:
3955 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3956 default:
3957 return DEVICE_CATEGORY_SPEAKER;
3958 }
3959}
3960
Eric Laurente0720872014-03-11 09:30:41 -07003961float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003962 int indexInUi)
3963{
3964 device_category deviceCategory = getDeviceCategory(device);
3965 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3966
3967 // the volume index in the UI is relative to the min and max volume indices for this stream type
3968 int nbSteps = 1 + curve[VOLMAX].mIndex -
3969 curve[VOLMIN].mIndex;
3970 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3971 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3972
3973 // find what part of the curve this index volume belongs to, or if it's out of bounds
3974 int segment = 0;
3975 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3976 return 0.0f;
3977 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3978 segment = 0;
3979 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3980 segment = 1;
3981 } else if (volIdx <= curve[VOLMAX].mIndex) {
3982 segment = 2;
3983 } else { // out of bounds
3984 return 1.0f;
3985 }
3986
3987 // linear interpolation in the attenuation table in dB
3988 float decibels = curve[segment].mDBAttenuation +
3989 ((float)(volIdx - curve[segment].mIndex)) *
3990 ( (curve[segment+1].mDBAttenuation -
3991 curve[segment].mDBAttenuation) /
3992 ((float)(curve[segment+1].mIndex -
3993 curve[segment].mIndex)) );
3994
3995 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3996
3997 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3998 curve[segment].mIndex, volIdx,
3999 curve[segment+1].mIndex,
4000 curve[segment].mDBAttenuation,
4001 decibels,
4002 curve[segment+1].mDBAttenuation,
4003 amplification);
4004
4005 return amplification;
4006}
4007
Eric Laurente0720872014-03-11 09:30:41 -07004008const AudioPolicyManager::VolumeCurvePoint
4009 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004010 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4011};
4012
Eric Laurente0720872014-03-11 09:30:41 -07004013const AudioPolicyManager::VolumeCurvePoint
4014 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004015 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4016};
4017
Eric Laurente0720872014-03-11 09:30:41 -07004018const AudioPolicyManager::VolumeCurvePoint
4019 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004020 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4021};
4022
Eric Laurente0720872014-03-11 09:30:41 -07004023const AudioPolicyManager::VolumeCurvePoint
4024 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004025 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4026};
4027
Eric Laurente0720872014-03-11 09:30:41 -07004028const AudioPolicyManager::VolumeCurvePoint
4029 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004030 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4031};
4032
4033// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4034// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4035// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4036// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4037
Eric Laurente0720872014-03-11 09:30:41 -07004038const AudioPolicyManager::VolumeCurvePoint
4039 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004040 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4041};
4042
Eric Laurente0720872014-03-11 09:30:41 -07004043const AudioPolicyManager::VolumeCurvePoint
4044 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004045 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4046};
4047
Eric Laurente0720872014-03-11 09:30:41 -07004048const AudioPolicyManager::VolumeCurvePoint
4049 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004050 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4051};
4052
Eric Laurente0720872014-03-11 09:30:41 -07004053const AudioPolicyManager::VolumeCurvePoint
4054 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004055 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4056};
4057
Eric Laurente0720872014-03-11 09:30:41 -07004058const AudioPolicyManager::VolumeCurvePoint
4059 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004060 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4061};
4062
Eric Laurente0720872014-03-11 09:30:41 -07004063const AudioPolicyManager::VolumeCurvePoint
4064 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4065 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004066 { // AUDIO_STREAM_VOICE_CALL
4067 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4068 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4069 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4070 },
4071 { // AUDIO_STREAM_SYSTEM
4072 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4073 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4074 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4075 },
4076 { // AUDIO_STREAM_RING
4077 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4078 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4079 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4080 },
4081 { // AUDIO_STREAM_MUSIC
4082 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4083 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4084 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4085 },
4086 { // AUDIO_STREAM_ALARM
4087 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4088 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4089 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4090 },
4091 { // AUDIO_STREAM_NOTIFICATION
4092 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4093 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4094 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4095 },
4096 { // AUDIO_STREAM_BLUETOOTH_SCO
4097 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4098 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4099 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4100 },
4101 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4102 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4103 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4104 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4105 },
4106 { // AUDIO_STREAM_DTMF
4107 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4108 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4109 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4110 },
4111 { // AUDIO_STREAM_TTS
4112 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4113 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4114 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4115 },
4116};
4117
Eric Laurente0720872014-03-11 09:30:41 -07004118void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004119{
4120 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4121 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4122 mStreams[i].mVolumeCurve[j] =
4123 sVolumeProfiles[i][j];
4124 }
4125 }
4126
4127 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4128 if (mSpeakerDrcEnabled) {
4129 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4130 sDefaultSystemVolumeCurveDrc;
4131 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4132 sSpeakerSonificationVolumeCurveDrc;
4133 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4134 sSpeakerSonificationVolumeCurveDrc;
4135 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4136 sSpeakerSonificationVolumeCurveDrc;
4137 }
4138}
4139
Eric Laurente0720872014-03-11 09:30:41 -07004140float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004141 int index,
4142 audio_io_handle_t output,
4143 audio_devices_t device)
4144{
4145 float volume = 1.0;
4146 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
4147 StreamDescriptor &streamDesc = mStreams[stream];
4148
4149 if (device == AUDIO_DEVICE_NONE) {
4150 device = outputDesc->device();
4151 }
4152
4153 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004154 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004155 index != mStreams[stream].mIndexMin &&
4156 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
4157 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
4158 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
4159 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
4160 return 1.0;
4161 }
4162
4163 volume = volIndexToAmpl(device, streamDesc, index);
4164
4165 // if a headset is connected, apply the following rules to ring tones and notifications
4166 // to avoid sound level bursts in user's ears:
4167 // - always attenuate ring tones and notifications volume by 6dB
4168 // - if music is playing, always limit the volume to current music volume,
4169 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004170 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004171 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4172 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4173 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4174 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4175 ((stream_strategy == STRATEGY_SONIFICATION)
4176 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004177 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004178 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004179 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004180 streamDesc.mCanBeMuted) {
4181 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4182 // when the phone is ringing we must consider that music could have been paused just before
4183 // by the music application and behave as if music was active if the last music track was
4184 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004185 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004186 mLimitRingtoneVolume) {
4187 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004188 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4189 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004190 output,
4191 musicDevice);
4192 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4193 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4194 if (volume > minVol) {
4195 volume = minVol;
4196 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4197 }
4198 }
4199 }
4200
4201 return volume;
4202}
4203
Eric Laurente0720872014-03-11 09:30:41 -07004204status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004205 int index,
4206 audio_io_handle_t output,
4207 audio_devices_t device,
4208 int delayMs,
4209 bool force)
4210{
4211
4212 // do not change actual stream volume if the stream is muted
4213 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4214 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4215 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4216 return NO_ERROR;
4217 }
4218
4219 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004220 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4221 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4222 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4223 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004224 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004225 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004226 return INVALID_OPERATION;
4227 }
4228
4229 float volume = computeVolume(stream, index, output, device);
4230 // We actually change the volume if:
4231 // - the float value returned by computeVolume() changed
4232 // - the force flag is set
4233 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4234 force) {
4235 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4236 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4237 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4238 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004239 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4240 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004241 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004242 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004243 }
4244
Eric Laurent3b73df72014-03-11 09:06:29 -07004245 if (stream == AUDIO_STREAM_VOICE_CALL ||
4246 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004247 float voiceVolume;
4248 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004249 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004250 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4251 } else {
4252 voiceVolume = 1.0;
4253 }
4254
4255 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4256 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4257 mLastVoiceVolume = voiceVolume;
4258 }
4259 }
4260
4261 return NO_ERROR;
4262}
4263
Eric Laurente0720872014-03-11 09:30:41 -07004264void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004265 audio_devices_t device,
4266 int delayMs,
4267 bool force)
4268{
4269 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4270
Eric Laurent3b73df72014-03-11 09:06:29 -07004271 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4272 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004273 mStreams[stream].getVolumeIndex(device),
4274 output,
4275 device,
4276 delayMs,
4277 force);
4278 }
4279}
4280
Eric Laurente0720872014-03-11 09:30:41 -07004281void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004282 bool on,
4283 audio_io_handle_t output,
4284 int delayMs,
4285 audio_devices_t device)
4286{
4287 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004288 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4289 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4290 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004291 }
4292 }
4293}
4294
Eric Laurente0720872014-03-11 09:30:41 -07004295void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004296 bool on,
4297 audio_io_handle_t output,
4298 int delayMs,
4299 audio_devices_t device)
4300{
4301 StreamDescriptor &streamDesc = mStreams[stream];
4302 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
4303 if (device == AUDIO_DEVICE_NONE) {
4304 device = outputDesc->device();
4305 }
4306
4307 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4308 stream, on, output, outputDesc->mMuteCount[stream], device);
4309
4310 if (on) {
4311 if (outputDesc->mMuteCount[stream] == 0) {
4312 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004313 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4314 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004315 checkAndSetVolume(stream, 0, output, device, delayMs);
4316 }
4317 }
4318 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4319 outputDesc->mMuteCount[stream]++;
4320 } else {
4321 if (outputDesc->mMuteCount[stream] == 0) {
4322 ALOGV("setStreamMute() unmuting non muted stream!");
4323 return;
4324 }
4325 if (--outputDesc->mMuteCount[stream] == 0) {
4326 checkAndSetVolume(stream,
4327 streamDesc.getVolumeIndex(device),
4328 output,
4329 device,
4330 delayMs);
4331 }
4332 }
4333}
4334
Eric Laurente0720872014-03-11 09:30:41 -07004335void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004336 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004337{
4338 // if the stream pertains to sonification strategy and we are in call we must
4339 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4340 // in the device used for phone strategy and play the tone if the selected device does not
4341 // interfere with the device used for phone strategy
4342 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4343 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004344 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004345 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4346 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
4347 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
4348 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4349 stream, starting, outputDesc->mDevice, stateChange);
4350 if (outputDesc->mRefCount[stream]) {
4351 int muteCount = 1;
4352 if (stateChange) {
4353 muteCount = outputDesc->mRefCount[stream];
4354 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004355 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004356 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4357 for (int i = 0; i < muteCount; i++) {
4358 setStreamMute(stream, starting, mPrimaryOutput);
4359 }
4360 } else {
4361 ALOGV("handleIncallSonification() high visibility");
4362 if (outputDesc->device() &
4363 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4364 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4365 for (int i = 0; i < muteCount; i++) {
4366 setStreamMute(stream, starting, mPrimaryOutput);
4367 }
4368 }
4369 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004370 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4371 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004372 } else {
4373 mpClientInterface->stopTone();
4374 }
4375 }
4376 }
4377 }
4378}
4379
Eric Laurente0720872014-03-11 09:30:41 -07004380bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004381{
4382 return isStateInCall(mPhoneState);
4383}
4384
Eric Laurente0720872014-03-11 09:30:41 -07004385bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004386 return ((state == AUDIO_MODE_IN_CALL) ||
4387 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004388}
4389
Eric Laurente0720872014-03-11 09:30:41 -07004390uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004391{
4392 return MAX_EFFECTS_CPU_LOAD;
4393}
4394
Eric Laurente0720872014-03-11 09:30:41 -07004395uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004396{
4397 return MAX_EFFECTS_MEMORY;
4398}
4399
Eric Laurent6a94d692014-05-20 11:18:06 -07004400
Eric Laurente552edb2014-03-10 17:42:56 -07004401// --- AudioOutputDescriptor class implementation
4402
Eric Laurente0720872014-03-11 09:30:41 -07004403AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004404 const sp<IOProfile>& profile)
4405 : mId(0), mIoHandle(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
Eric Laurente552edb2014-03-10 17:42:56 -07004406 mChannelMask(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004407 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004408 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4409{
4410 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004411 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004412 mRefCount[i] = 0;
4413 mCurVolume[i] = -1.0;
4414 mMuteCount[i] = 0;
4415 mStopTime[i] = 0;
4416 }
4417 for (int i = 0; i < NUM_STRATEGIES; i++) {
4418 mStrategyMutedByDevice[i] = false;
4419 }
4420 if (profile != NULL) {
4421 mSamplingRate = profile->mSamplingRates[0];
4422 mFormat = profile->mFormats[0];
4423 mChannelMask = profile->mChannelMasks[0];
4424 mFlags = profile->mFlags;
4425 }
4426}
4427
Eric Laurente0720872014-03-11 09:30:41 -07004428audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004429{
4430 if (isDuplicated()) {
4431 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4432 } else {
4433 return mDevice;
4434 }
4435}
4436
Eric Laurente0720872014-03-11 09:30:41 -07004437uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004438{
4439 if (isDuplicated()) {
4440 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4441 } else {
4442 return mLatency;
4443 }
4444}
4445
Eric Laurente0720872014-03-11 09:30:41 -07004446bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurente552edb2014-03-10 17:42:56 -07004447 const AudioOutputDescriptor *outputDesc)
4448{
4449 if (isDuplicated()) {
4450 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4451 } else if (outputDesc->isDuplicated()){
4452 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4453 } else {
4454 return (mProfile->mModule == outputDesc->mProfile->mModule);
4455 }
4456}
4457
Eric Laurente0720872014-03-11 09:30:41 -07004458void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004459 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004460{
4461 // forward usage count change to attached outputs
4462 if (isDuplicated()) {
4463 mOutput1->changeRefCount(stream, delta);
4464 mOutput2->changeRefCount(stream, delta);
4465 }
4466 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004467 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4468 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004469 mRefCount[stream] = 0;
4470 return;
4471 }
4472 mRefCount[stream] += delta;
4473 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4474}
4475
Eric Laurente0720872014-03-11 09:30:41 -07004476audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004477{
4478 if (isDuplicated()) {
4479 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4480 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004481 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004482 }
4483}
4484
Eric Laurente0720872014-03-11 09:30:41 -07004485bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004486{
4487 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4488}
4489
Eric Laurente0720872014-03-11 09:30:41 -07004490bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004491 uint32_t inPastMs,
4492 nsecs_t sysTime) const
4493{
4494 if ((sysTime == 0) && (inPastMs != 0)) {
4495 sysTime = systemTime();
4496 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004497 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4498 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004499 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004500 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004501 return true;
4502 }
4503 }
4504 return false;
4505}
4506
Eric Laurente0720872014-03-11 09:30:41 -07004507bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004508 uint32_t inPastMs,
4509 nsecs_t sysTime) const
4510{
4511 if (mRefCount[stream] != 0) {
4512 return true;
4513 }
4514 if (inPastMs == 0) {
4515 return false;
4516 }
4517 if (sysTime == 0) {
4518 sysTime = systemTime();
4519 }
4520 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4521 return true;
4522 }
4523 return false;
4524}
4525
Eric Laurent1c333e22014-05-20 10:48:17 -07004526void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004527 struct audio_port_config *dstConfig,
4528 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004529{
Eric Laurent6a94d692014-05-20 11:18:06 -07004530 dstConfig->id = mId;
4531 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4532 dstConfig->type = AUDIO_PORT_TYPE_MIX;
4533 dstConfig->sample_rate = mSamplingRate;
4534 dstConfig->channel_mask = mChannelMask;
4535 dstConfig->format = mFormat;
4536 dstConfig->gain.index = -1;
4537 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
Eric Laurent1c333e22014-05-20 10:48:17 -07004538 AUDIO_PORT_CONFIG_FORMAT;
Eric Laurent6a94d692014-05-20 11:18:06 -07004539 // use supplied variable configuration parameters if any
4540 if (srcConfig != NULL) {
4541 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
4542 dstConfig->sample_rate = srcConfig->sample_rate;
4543 }
4544 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
4545 dstConfig->channel_mask = srcConfig->channel_mask;
4546 }
4547 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
4548 dstConfig->format = srcConfig->format;
4549 }
4550 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
4551 dstConfig->gain = srcConfig->gain;
4552 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
4553 }
4554 }
4555 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4556 dstConfig->ext.mix.handle = mIoHandle;
4557 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004558}
4559
4560void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4561 struct audio_port *port) const
4562{
4563 mProfile->toAudioPort(port);
4564 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004565 toAudioPortConfig(&port->active_config);
4566 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004567 port->ext.mix.handle = mIoHandle;
4568 port->ext.mix.latency_class =
4569 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4570}
Eric Laurente552edb2014-03-10 17:42:56 -07004571
Eric Laurente0720872014-03-11 09:30:41 -07004572status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004573{
4574 const size_t SIZE = 256;
4575 char buffer[SIZE];
4576 String8 result;
4577
4578 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4579 result.append(buffer);
4580 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4581 result.append(buffer);
4582 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4583 result.append(buffer);
4584 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4585 result.append(buffer);
4586 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4587 result.append(buffer);
4588 snprintf(buffer, SIZE, " Devices %08x\n", device());
4589 result.append(buffer);
4590 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4591 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004592 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4593 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4594 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004595 result.append(buffer);
4596 }
4597 write(fd, result.string(), result.size());
4598
4599 return NO_ERROR;
4600}
4601
4602// --- AudioInputDescriptor class implementation
4603
Eric Laurent1c333e22014-05-20 10:48:17 -07004604AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
4605 : mId(0), mIoHandle(0), mSamplingRate(0),
4606 mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
4607 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004608 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004609{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004610 if (profile != NULL) {
4611 mSamplingRate = profile->mSamplingRates[0];
4612 mFormat = profile->mFormats[0];
4613 mChannelMask = profile->mChannelMasks[0];
4614 }
Eric Laurente552edb2014-03-10 17:42:56 -07004615}
4616
Eric Laurent1c333e22014-05-20 10:48:17 -07004617void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004618 struct audio_port_config *dstConfig,
4619 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004620{
Eric Laurent6a94d692014-05-20 11:18:06 -07004621 dstConfig->id = mId;
4622 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4623 dstConfig->type = AUDIO_PORT_TYPE_MIX;
4624 dstConfig->sample_rate = mSamplingRate;
4625 dstConfig->channel_mask = mChannelMask;
4626 dstConfig->format = mFormat;
4627 dstConfig->gain.index = -1;
4628 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4629 AUDIO_PORT_CONFIG_FORMAT;
4630 // use supplied variable configuration parameters if any
4631 if (srcConfig != NULL) {
4632 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
4633 dstConfig->sample_rate = srcConfig->sample_rate;
4634 }
4635 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
4636 dstConfig->channel_mask = srcConfig->channel_mask;
4637 }
4638 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
4639 dstConfig->format = srcConfig->format;
4640 }
4641 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
4642 dstConfig->gain = srcConfig->gain;
4643 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
4644 }
4645 }
Eric Laurent62aaabb2014-06-02 10:40:54 -07004646 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4647 dstConfig->ext.mix.handle = mIoHandle;
4648 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004649}
4650
4651void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4652 struct audio_port *port) const
4653{
4654 mProfile->toAudioPort(port);
4655 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004656 toAudioPortConfig(&port->active_config);
4657 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004658 port->ext.mix.handle = mIoHandle;
4659 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4660}
4661
Eric Laurente0720872014-03-11 09:30:41 -07004662status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004663{
4664 const size_t SIZE = 256;
4665 char buffer[SIZE];
4666 String8 result;
4667
4668 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4669 result.append(buffer);
4670 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4671 result.append(buffer);
4672 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4673 result.append(buffer);
4674 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4675 result.append(buffer);
4676 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4677 result.append(buffer);
4678 write(fd, result.string(), result.size());
4679
4680 return NO_ERROR;
4681}
4682
4683// --- StreamDescriptor class implementation
4684
Eric Laurente0720872014-03-11 09:30:41 -07004685AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004686 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4687{
4688 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4689}
4690
Eric Laurente0720872014-03-11 09:30:41 -07004691int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004692{
Eric Laurente0720872014-03-11 09:30:41 -07004693 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004694 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4695 if (mIndexCur.indexOfKey(device) < 0) {
4696 device = AUDIO_DEVICE_OUT_DEFAULT;
4697 }
4698 return mIndexCur.valueFor(device);
4699}
4700
Eric Laurente0720872014-03-11 09:30:41 -07004701void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004702{
4703 const size_t SIZE = 256;
4704 char buffer[SIZE];
4705 String8 result;
4706
4707 snprintf(buffer, SIZE, "%s %02d %02d ",
4708 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4709 result.append(buffer);
4710 for (size_t i = 0; i < mIndexCur.size(); i++) {
4711 snprintf(buffer, SIZE, "%04x : %02d, ",
4712 mIndexCur.keyAt(i),
4713 mIndexCur.valueAt(i));
4714 result.append(buffer);
4715 }
4716 result.append("\n");
4717
4718 write(fd, result.string(), result.size());
4719}
4720
4721// --- EffectDescriptor class implementation
4722
Eric Laurente0720872014-03-11 09:30:41 -07004723status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004724{
4725 const size_t SIZE = 256;
4726 char buffer[SIZE];
4727 String8 result;
4728
4729 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4730 result.append(buffer);
4731 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4732 result.append(buffer);
4733 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4734 result.append(buffer);
4735 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4736 result.append(buffer);
4737 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4738 result.append(buffer);
4739 write(fd, result.string(), result.size());
4740
4741 return NO_ERROR;
4742}
4743
Eric Laurent1c333e22014-05-20 10:48:17 -07004744// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004745
Eric Laurente0720872014-03-11 09:30:41 -07004746AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07004747 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
4748{
4749}
4750
Eric Laurente0720872014-03-11 09:30:41 -07004751AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004752{
4753 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004754 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004755 }
4756 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004757 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004758 }
4759 free((void *)mName);
4760}
4761
Eric Laurent1afeecb2014-05-14 08:52:28 -07004762status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4763{
4764 cnode *node = root->first_child;
4765
4766 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4767
4768 while (node) {
4769 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4770 profile->loadSamplingRates((char *)node->value);
4771 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4772 profile->loadFormats((char *)node->value);
4773 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4774 profile->loadInChannels((char *)node->value);
4775 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4776 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4777 mDeclaredDevices);
4778 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4779 profile->loadGains(node);
4780 }
4781 node = node->next;
4782 }
4783 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4784 "loadInput() invalid supported devices");
4785 ALOGW_IF(profile->mChannelMasks.size() == 0,
4786 "loadInput() invalid supported channel masks");
4787 ALOGW_IF(profile->mSamplingRates.size() == 0,
4788 "loadInput() invalid supported sampling rates");
4789 ALOGW_IF(profile->mFormats.size() == 0,
4790 "loadInput() invalid supported formats");
4791 if (!profile->mSupportedDevices.isEmpty() &&
4792 (profile->mChannelMasks.size() != 0) &&
4793 (profile->mSamplingRates.size() != 0) &&
4794 (profile->mFormats.size() != 0)) {
4795
4796 ALOGV("loadInput() adding input Supported Devices %04x",
4797 profile->mSupportedDevices.types());
4798
4799 mInputProfiles.add(profile);
4800 return NO_ERROR;
4801 } else {
4802 return BAD_VALUE;
4803 }
4804}
4805
4806status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4807{
4808 cnode *node = root->first_child;
4809
4810 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4811
4812 while (node) {
4813 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4814 profile->loadSamplingRates((char *)node->value);
4815 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4816 profile->loadFormats((char *)node->value);
4817 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4818 profile->loadOutChannels((char *)node->value);
4819 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4820 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4821 mDeclaredDevices);
4822 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4823 profile->mFlags = parseFlagNames((char *)node->value);
4824 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4825 profile->loadGains(node);
4826 }
4827 node = node->next;
4828 }
4829 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4830 "loadOutput() invalid supported devices");
4831 ALOGW_IF(profile->mChannelMasks.size() == 0,
4832 "loadOutput() invalid supported channel masks");
4833 ALOGW_IF(profile->mSamplingRates.size() == 0,
4834 "loadOutput() invalid supported sampling rates");
4835 ALOGW_IF(profile->mFormats.size() == 0,
4836 "loadOutput() invalid supported formats");
4837 if (!profile->mSupportedDevices.isEmpty() &&
4838 (profile->mChannelMasks.size() != 0) &&
4839 (profile->mSamplingRates.size() != 0) &&
4840 (profile->mFormats.size() != 0)) {
4841
4842 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4843 profile->mSupportedDevices.types(), profile->mFlags);
4844
4845 mOutputProfiles.add(profile);
4846 return NO_ERROR;
4847 } else {
4848 return BAD_VALUE;
4849 }
4850}
4851
4852status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4853{
4854 cnode *node = root->first_child;
4855
4856 audio_devices_t type = AUDIO_DEVICE_NONE;
4857 while (node) {
4858 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4859 type = parseDeviceNames((char *)node->value);
4860 break;
4861 }
4862 node = node->next;
4863 }
4864 if (type == AUDIO_DEVICE_NONE ||
4865 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4866 ALOGW("loadDevice() bad type %08x", type);
4867 return BAD_VALUE;
4868 }
4869 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4870 deviceDesc->mModule = this;
4871
4872 node = root->first_child;
4873 while (node) {
4874 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4875 deviceDesc->mAddress = String8((char *)node->value);
4876 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4877 if (audio_is_input_device(type)) {
4878 deviceDesc->loadInChannels((char *)node->value);
4879 } else {
4880 deviceDesc->loadOutChannels((char *)node->value);
4881 }
4882 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4883 deviceDesc->loadGains(node);
4884 }
4885 node = node->next;
4886 }
4887
4888 ALOGV("loadDevice() adding device name %s type %08x address %s",
4889 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4890
4891 mDeclaredDevices.add(deviceDesc);
4892
4893 return NO_ERROR;
4894}
4895
Eric Laurente0720872014-03-11 09:30:41 -07004896void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004897{
4898 const size_t SIZE = 256;
4899 char buffer[SIZE];
4900 String8 result;
4901
4902 snprintf(buffer, SIZE, " - name: %s\n", mName);
4903 result.append(buffer);
4904 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4905 result.append(buffer);
4906 write(fd, result.string(), result.size());
4907 if (mOutputProfiles.size()) {
4908 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4909 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004910 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004911 write(fd, buffer, strlen(buffer));
4912 mOutputProfiles[i]->dump(fd);
4913 }
4914 }
4915 if (mInputProfiles.size()) {
4916 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4917 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004918 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004919 write(fd, buffer, strlen(buffer));
4920 mInputProfiles[i]->dump(fd);
4921 }
4922 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07004923 if (mDeclaredDevices.size()) {
4924 write(fd, " - devices:\n", strlen(" - devices:\n"));
4925 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
4926 mDeclaredDevices[i]->dump(fd, 4, i);
4927 }
4928 }
Eric Laurente552edb2014-03-10 17:42:56 -07004929}
4930
Eric Laurent1c333e22014-05-20 10:48:17 -07004931// --- AudioPort class implementation
4932
4933void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
4934{
4935 port->role = mRole;
4936 port->type = mType;
4937 unsigned int i;
4938 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
4939 port->sample_rates[i] = mSamplingRates[i];
4940 }
4941 port->num_sample_rates = i;
4942 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
4943 port->channel_masks[i] = mChannelMasks[i];
4944 }
4945 port->num_channel_masks = i;
4946 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
4947 port->formats[i] = mFormats[i];
4948 }
4949 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07004950
4951 ALOGV("AudioPort::toAudioPort() num gains %d", mGains.size());
4952
4953 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
4954 port->gains[i] = mGains[i]->mGain;
4955 }
4956 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07004957}
4958
4959
4960void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
4961{
4962 char *str = strtok(name, "|");
4963
4964 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4965 // rates should be read from the output stream after it is opened for the first time
4966 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4967 mSamplingRates.add(0);
4968 return;
4969 }
4970
4971 while (str != NULL) {
4972 uint32_t rate = atoi(str);
4973 if (rate != 0) {
4974 ALOGV("loadSamplingRates() adding rate %d", rate);
4975 mSamplingRates.add(rate);
4976 }
4977 str = strtok(NULL, "|");
4978 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004979}
4980
4981void AudioPolicyManager::AudioPort::loadFormats(char *name)
4982{
4983 char *str = strtok(name, "|");
4984
4985 // by convention, "0' in the first entry in mFormats indicates the supported formats
4986 // should be read from the output stream after it is opened for the first time
4987 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4988 mFormats.add(AUDIO_FORMAT_DEFAULT);
4989 return;
4990 }
4991
4992 while (str != NULL) {
4993 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4994 ARRAY_SIZE(sFormatNameToEnumTable),
4995 str);
4996 if (format != AUDIO_FORMAT_DEFAULT) {
4997 mFormats.add(format);
4998 }
4999 str = strtok(NULL, "|");
5000 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005001}
5002
5003void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5004{
5005 const char *str = strtok(name, "|");
5006
5007 ALOGV("loadInChannels() %s", name);
5008
5009 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5010 mChannelMasks.add(0);
5011 return;
5012 }
5013
5014 while (str != NULL) {
5015 audio_channel_mask_t channelMask =
5016 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5017 ARRAY_SIZE(sInChannelsNameToEnumTable),
5018 str);
5019 if (channelMask != 0) {
5020 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5021 mChannelMasks.add(channelMask);
5022 }
5023 str = strtok(NULL, "|");
5024 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005025}
5026
5027void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5028{
5029 const char *str = strtok(name, "|");
5030
5031 ALOGV("loadOutChannels() %s", name);
5032
5033 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5034 // masks should be read from the output stream after it is opened for the first time
5035 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5036 mChannelMasks.add(0);
5037 return;
5038 }
5039
5040 while (str != NULL) {
5041 audio_channel_mask_t channelMask =
5042 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5043 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5044 str);
5045 if (channelMask != 0) {
5046 mChannelMasks.add(channelMask);
5047 }
5048 str = strtok(NULL, "|");
5049 }
5050 return;
5051}
5052
Eric Laurent1afeecb2014-05-14 08:52:28 -07005053audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5054{
5055 const char *str = strtok(name, "|");
5056
5057 ALOGV("loadGainMode() %s", name);
5058 audio_gain_mode_t mode = 0;
5059 while (str != NULL) {
5060 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5061 ARRAY_SIZE(sGainModeNameToEnumTable),
5062 str);
5063 str = strtok(NULL, "|");
5064 }
5065 return mode;
5066}
5067
5068void AudioPolicyManager::AudioPort::loadGain(cnode *root)
5069{
5070 cnode *node = root->first_child;
5071
5072 sp<AudioGain> gain = new AudioGain();
5073
5074 while (node) {
5075 if (strcmp(node->name, GAIN_MODE) == 0) {
5076 gain->mGain.mode = loadGainMode((char *)node->value);
5077 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
5078 if ((mType == AUDIO_PORT_TYPE_DEVICE && mRole == AUDIO_PORT_ROLE_SOURCE) ||
5079 (mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK)) {
5080 gain->mGain.channel_mask =
5081 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5082 ARRAY_SIZE(sInChannelsNameToEnumTable),
5083 (char *)node->value);
5084 } else {
5085 gain->mGain.channel_mask =
5086 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5087 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5088 (char *)node->value);
5089 }
5090 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5091 gain->mGain.min_value = atoi((char *)node->value);
5092 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5093 gain->mGain.max_value = atoi((char *)node->value);
5094 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5095 gain->mGain.default_value = atoi((char *)node->value);
5096 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5097 gain->mGain.step_value = atoi((char *)node->value);
5098 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5099 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5100 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5101 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5102 }
5103 node = node->next;
5104 }
5105
5106 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5107 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5108
5109 if (gain->mGain.mode == 0) {
5110 return;
5111 }
5112 mGains.add(gain);
5113}
5114
5115void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5116{
5117 cnode *node = root->first_child;
5118 while (node) {
5119 ALOGV("loadGains() loading gain %s", node->name);
5120 loadGain(node);
5121 node = node->next;
5122 }
5123}
5124
5125void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5126{
5127 const size_t SIZE = 256;
5128 char buffer[SIZE];
5129 String8 result;
5130
5131 if (mName.size() != 0) {
5132 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5133 result.append(buffer);
5134 }
5135
5136 if (mSamplingRates.size() != 0) {
5137 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5138 result.append(buffer);
5139 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5140 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5141 result.append(buffer);
5142 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5143 }
5144 result.append("\n");
5145 }
5146
5147 if (mChannelMasks.size() != 0) {
5148 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5149 result.append(buffer);
5150 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5151 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5152 result.append(buffer);
5153 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5154 }
5155 result.append("\n");
5156 }
5157
5158 if (mFormats.size() != 0) {
5159 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5160 result.append(buffer);
5161 for (size_t i = 0; i < mFormats.size(); i++) {
5162 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5163 ARRAY_SIZE(sFormatNameToEnumTable),
5164 mFormats[i]));
5165 result.append(buffer);
5166 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5167 }
5168 result.append("\n");
5169 }
5170 write(fd, result.string(), result.size());
5171 if (mGains.size() != 0) {
5172 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5173 write(fd, buffer, strlen(buffer) + 1);
5174 result.append(buffer);
5175 for (size_t i = 0; i < mGains.size(); i++) {
5176 mGains[i]->dump(fd, spaces + 2, i);
5177 }
5178 }
5179}
5180
5181// --- AudioGain class implementation
5182
5183AudioPolicyManager::AudioGain::AudioGain()
5184{
5185 memset(&mGain, 0, sizeof(struct audio_gain));
5186}
5187
5188void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5189{
5190 const size_t SIZE = 256;
5191 char buffer[SIZE];
5192 String8 result;
5193
5194 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5195 result.append(buffer);
5196 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5197 result.append(buffer);
5198 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5199 result.append(buffer);
5200 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5201 result.append(buffer);
5202 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5203 result.append(buffer);
5204 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5205 result.append(buffer);
5206 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5207 result.append(buffer);
5208 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5209 result.append(buffer);
5210 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5211 result.append(buffer);
5212
5213 write(fd, result.string(), result.size());
5214}
5215
Eric Laurent1c333e22014-05-20 10:48:17 -07005216// --- IOProfile class implementation
5217
Eric Laurent1afeecb2014-05-14 08:52:28 -07005218AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
5219 HwModule *module)
5220 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005221{
5222}
5223
Eric Laurente0720872014-03-11 09:30:41 -07005224AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005225{
5226}
5227
5228// checks if the IO profile is compatible with specified parameters.
5229// Sampling rate, format and channel mask must be specified in order to
5230// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005231bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005232 uint32_t samplingRate,
5233 audio_format_t format,
5234 audio_channel_mask_t channelMask,
5235 audio_output_flags_t flags) const
5236{
5237 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5238 return false;
5239 }
5240
Eric Laurent3a4311c2014-03-17 12:00:47 -07005241 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005242 return false;
5243 }
5244 if ((mFlags & flags) != flags) {
5245 return false;
5246 }
5247 size_t i;
5248 for (i = 0; i < mSamplingRates.size(); i++)
5249 {
5250 if (mSamplingRates[i] == samplingRate) {
5251 break;
5252 }
5253 }
5254 if (i == mSamplingRates.size()) {
5255 return false;
5256 }
5257 for (i = 0; i < mFormats.size(); i++)
5258 {
5259 if (mFormats[i] == format) {
5260 break;
5261 }
5262 }
5263 if (i == mFormats.size()) {
5264 return false;
5265 }
5266 for (i = 0; i < mChannelMasks.size(); i++)
5267 {
5268 if (mChannelMasks[i] == channelMask) {
5269 break;
5270 }
5271 }
5272 if (i == mChannelMasks.size()) {
5273 return false;
5274 }
5275 return true;
5276}
5277
Eric Laurente0720872014-03-11 09:30:41 -07005278void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005279{
5280 const size_t SIZE = 256;
5281 char buffer[SIZE];
5282 String8 result;
5283
Eric Laurent1afeecb2014-05-14 08:52:28 -07005284 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005285
Eric Laurente552edb2014-03-10 17:42:56 -07005286 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5287 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005288 snprintf(buffer, SIZE, " - devices:\n");
5289 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005290 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005291 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5292 mSupportedDevices[i]->dump(fd, 6, i);
5293 }
Eric Laurente552edb2014-03-10 17:42:56 -07005294}
5295
Eric Laurentd4692962014-05-05 18:13:44 -07005296void AudioPolicyManager::IOProfile::log()
5297{
5298 const size_t SIZE = 256;
5299 char buffer[SIZE];
5300 String8 result;
5301
5302 ALOGV(" - sampling rates: ");
5303 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5304 ALOGV(" %d", mSamplingRates[i]);
5305 }
5306
5307 ALOGV(" - channel masks: ");
5308 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5309 ALOGV(" 0x%04x", mChannelMasks[i]);
5310 }
5311
5312 ALOGV(" - formats: ");
5313 for (size_t i = 0; i < mFormats.size(); i++) {
5314 ALOGV(" 0x%08x", mFormats[i]);
5315 }
5316
5317 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5318 ALOGV(" - flags: 0x%04x\n", mFlags);
5319}
5320
5321
Eric Laurent3a4311c2014-03-17 12:00:47 -07005322// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005323
Eric Laurent3a4311c2014-03-17 12:00:47 -07005324bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005325{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005326 // Devices are considered equal if they:
5327 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5328 // - have the same address or one device does not specify the address
5329 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005330 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005331 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005332 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005333 mChannelMask == other->mChannelMask);
5334}
5335
5336void AudioPolicyManager::DeviceVector::refreshTypes()
5337{
Eric Laurent1c333e22014-05-20 10:48:17 -07005338 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005339 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005340 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005341 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005342 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005343}
5344
5345ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5346{
5347 for(size_t i = 0; i < size(); i++) {
5348 if (item->equals(itemAt(i))) {
5349 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005350 }
5351 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005352 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005353}
5354
Eric Laurent3a4311c2014-03-17 12:00:47 -07005355ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005356{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005357 ssize_t ret = indexOf(item);
5358
5359 if (ret < 0) {
5360 ret = SortedVector::add(item);
5361 if (ret >= 0) {
5362 refreshTypes();
5363 }
5364 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005365 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005366 ret = -1;
5367 }
5368 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005369}
5370
Eric Laurent3a4311c2014-03-17 12:00:47 -07005371ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5372{
5373 size_t i;
5374 ssize_t ret = indexOf(item);
5375
5376 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005377 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005378 } else {
5379 ret = SortedVector::removeAt(ret);
5380 if (ret >= 0) {
5381 refreshTypes();
5382 }
5383 }
5384 return ret;
5385}
5386
5387void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5388{
5389 DeviceVector deviceList;
5390
5391 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5392 types &= ~role_bit;
5393
5394 while (types) {
5395 uint32_t i = 31 - __builtin_clz(types);
5396 uint32_t type = 1 << i;
5397 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005398 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005399 }
5400}
5401
Eric Laurent1afeecb2014-05-14 08:52:28 -07005402void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5403 const DeviceVector& declaredDevices)
5404{
5405 char *devName = strtok(name, "|");
5406 while (devName != NULL) {
5407 if (strlen(devName) != 0) {
5408 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5409 ARRAY_SIZE(sDeviceNameToEnumTable),
5410 devName);
5411 if (type != AUDIO_DEVICE_NONE) {
5412 add(new DeviceDescriptor(String8(""), type));
5413 } else {
5414 sp<DeviceDescriptor> deviceDesc =
5415 declaredDevices.getDeviceFromName(String8(devName));
5416 if (deviceDesc != 0) {
5417 add(deviceDesc);
5418 }
5419 }
5420 }
5421 devName = strtok(NULL, "|");
5422 }
5423}
5424
Eric Laurent1c333e22014-05-20 10:48:17 -07005425sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5426 audio_devices_t type, String8 address) const
5427{
5428 sp<DeviceDescriptor> device;
5429 for (size_t i = 0; i < size(); i++) {
5430 if (itemAt(i)->mDeviceType == type) {
5431 device = itemAt(i);
5432 if (itemAt(i)->mAddress = address) {
5433 break;
5434 }
5435 }
5436 }
5437 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5438 type, address.string(), device.get());
5439 return device;
5440}
5441
Eric Laurent6a94d692014-05-20 11:18:06 -07005442sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5443 audio_port_handle_t id) const
5444{
5445 sp<DeviceDescriptor> device;
5446 for (size_t i = 0; i < size(); i++) {
5447 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%d)->mId %d", id, i, itemAt(i)->mId);
5448 if (itemAt(i)->mId == id) {
5449 device = itemAt(i);
5450 break;
5451 }
5452 }
5453 return device;
5454}
5455
Eric Laurent1c333e22014-05-20 10:48:17 -07005456AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5457 audio_devices_t type) const
5458{
5459 DeviceVector devices;
5460 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5461 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5462 devices.add(itemAt(i));
5463 type &= ~itemAt(i)->mDeviceType;
5464 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5465 itemAt(i)->mDeviceType, itemAt(i).get());
5466 }
5467 }
5468 return devices;
5469}
5470
Eric Laurent1afeecb2014-05-14 08:52:28 -07005471sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5472 const String8& name) const
5473{
5474 sp<DeviceDescriptor> device;
5475 for (size_t i = 0; i < size(); i++) {
5476 if (itemAt(i)->mName == name) {
5477 device = itemAt(i);
5478 break;
5479 }
5480 }
5481 return device;
5482}
5483
Eric Laurent6a94d692014-05-20 11:18:06 -07005484void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5485 struct audio_port_config *dstConfig,
5486 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005487{
Eric Laurent6a94d692014-05-20 11:18:06 -07005488 dstConfig->id = mId;
5489 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005490 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005491 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
5492 dstConfig->channel_mask = mChannelMask;
5493 dstConfig->gain.index = -1;
5494 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK;
5495 // use supplied variable configuration parameters if any
5496 if (srcConfig != NULL) {
5497 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5498 dstConfig->channel_mask = srcConfig->channel_mask;
5499 }
5500 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5501 dstConfig->gain = srcConfig->gain;
5502 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5503 }
5504 }
5505 dstConfig->ext.device.type = mDeviceType;
5506 dstConfig->ext.device.hw_module = mModule->mHandle;
5507 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005508}
5509
5510void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5511{
Eric Laurente1715a42014-05-20 11:30:42 -07005512 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07005513 AudioPort::toAudioPort(port);
5514 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005515 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005516 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005517 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005518 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5519}
5520
Eric Laurent1afeecb2014-05-14 08:52:28 -07005521status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005522{
5523 const size_t SIZE = 256;
5524 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005525 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005526
Eric Laurent1afeecb2014-05-14 08:52:28 -07005527 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5528 result.append(buffer);
5529 if (mId != 0) {
5530 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5531 result.append(buffer);
5532 }
5533 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5534 enumToString(sDeviceNameToEnumTable,
5535 ARRAY_SIZE(sDeviceNameToEnumTable),
5536 mDeviceType));
5537 result.append(buffer);
5538 if (mAddress.size() != 0) {
5539 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5540 result.append(buffer);
5541 }
5542 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5543 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5544 result.append(buffer);
5545 }
5546 write(fd, result.string(), result.size());
5547 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005548
5549 return NO_ERROR;
5550}
5551
5552
5553// --- audio_policy.conf file parsing
5554
Eric Laurente0720872014-03-11 09:30:41 -07005555audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005556{
5557 uint32_t flag = 0;
5558
5559 // it is OK to cast name to non const here as we are not going to use it after
5560 // strtok() modifies it
5561 char *flagName = strtok(name, "|");
5562 while (flagName != NULL) {
5563 if (strlen(flagName) != 0) {
5564 flag |= stringToEnum(sFlagNameToEnumTable,
5565 ARRAY_SIZE(sFlagNameToEnumTable),
5566 flagName);
5567 }
5568 flagName = strtok(NULL, "|");
5569 }
5570 //force direct flag if offload flag is set: offloading implies a direct output stream
5571 // and all common behaviors are driven by checking only the direct flag
5572 // this should normally be set appropriately in the policy configuration file
5573 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5574 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5575 }
5576
5577 return (audio_output_flags_t)flag;
5578}
5579
Eric Laurente0720872014-03-11 09:30:41 -07005580audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005581{
5582 uint32_t device = 0;
5583
5584 char *devName = strtok(name, "|");
5585 while (devName != NULL) {
5586 if (strlen(devName) != 0) {
5587 device |= stringToEnum(sDeviceNameToEnumTable,
5588 ARRAY_SIZE(sDeviceNameToEnumTable),
5589 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005590 }
Eric Laurente552edb2014-03-10 17:42:56 -07005591 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005592 }
Eric Laurente552edb2014-03-10 17:42:56 -07005593 return device;
5594}
5595
Eric Laurente0720872014-03-11 09:30:41 -07005596void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005597{
Eric Laurente552edb2014-03-10 17:42:56 -07005598 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005599 cnode *node;
Eric Laurente552edb2014-03-10 17:42:56 -07005600 HwModule *module = new HwModule(root->name);
5601
Eric Laurent1afeecb2014-05-14 08:52:28 -07005602 node = config_find(root, DEVICES_TAG);
5603 if (node != NULL) {
5604 node = node->first_child;
5605 while (node) {
5606 ALOGV("loadHwModule() loading device %s", node->name);
5607 status_t tmpStatus = module->loadDevice(node);
5608 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5609 status = tmpStatus;
5610 }
5611 node = node->next;
5612 }
5613 }
5614 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005615 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005616 node = node->first_child;
5617 while (node) {
5618 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005619 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005620 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5621 status = tmpStatus;
5622 }
5623 node = node->next;
5624 }
5625 }
5626 node = config_find(root, INPUTS_TAG);
5627 if (node != NULL) {
5628 node = node->first_child;
5629 while (node) {
5630 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005631 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005632 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5633 status = tmpStatus;
5634 }
5635 node = node->next;
5636 }
5637 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005638 loadGlobalConfig(root, module);
5639
Eric Laurente552edb2014-03-10 17:42:56 -07005640 if (status == NO_ERROR) {
5641 mHwModules.add(module);
5642 } else {
5643 delete module;
5644 }
5645}
5646
Eric Laurente0720872014-03-11 09:30:41 -07005647void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005648{
5649 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5650 if (node == NULL) {
5651 return;
5652 }
5653
5654 node = node->first_child;
5655 while (node) {
5656 ALOGV("loadHwModules() loading module %s", node->name);
5657 loadHwModule(node);
5658 node = node->next;
5659 }
5660}
5661
Eric Laurent1afeecb2014-05-14 08:52:28 -07005662void AudioPolicyManager::loadGlobalConfig(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07005663{
5664 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
5665 if (node == NULL) {
5666 return;
5667 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005668 DeviceVector declaredDevices;
5669 if (module != NULL) {
5670 declaredDevices = module->mDeclaredDevices;
5671 }
5672
Eric Laurente552edb2014-03-10 17:42:56 -07005673 node = node->first_child;
5674 while (node) {
5675 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005676 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5677 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005678 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5679 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005680 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005681 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005682 ARRAY_SIZE(sDeviceNameToEnumTable),
5683 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005684 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005685 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005686 } else {
5687 ALOGW("loadGlobalConfig() default device not specified");
5688 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005689 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005690 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005691 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5692 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005693 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005694 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5695 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5696 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
5697 }
5698 node = node->next;
5699 }
5700}
5701
Eric Laurente0720872014-03-11 09:30:41 -07005702status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005703{
5704 cnode *root;
5705 char *data;
5706
5707 data = (char *)load_file(path, NULL);
5708 if (data == NULL) {
5709 return -ENODEV;
5710 }
5711 root = config_node("", "");
5712 config_load(root, data);
5713
Eric Laurente552edb2014-03-10 17:42:56 -07005714 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005715 // legacy audio_policy.conf files have one global_configuration section
5716 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07005717 config_free(root);
5718 free(root);
5719 free(data);
5720
5721 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5722
5723 return NO_ERROR;
5724}
5725
Eric Laurente0720872014-03-11 09:30:41 -07005726void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07005727{
5728 HwModule *module;
Eric Laurent1c333e22014-05-20 10:48:17 -07005729 sp<IOProfile> profile;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005730 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005731 mAvailableOutputDevices.add(mDefaultOutputDevice);
5732 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005733
5734 module = new HwModule("primary");
5735
Eric Laurent1afeecb2014-05-14 08:52:28 -07005736 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005737 profile->mSamplingRates.add(44100);
5738 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5739 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005740 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005741 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
5742 module->mOutputProfiles.add(profile);
5743
Eric Laurent1afeecb2014-05-14 08:52:28 -07005744 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005745 profile->mSamplingRates.add(8000);
5746 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5747 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005748 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005749 module->mInputProfiles.add(profile);
5750
5751 mHwModules.add(module);
5752}
5753
5754}; // namespace android