blob: b5b26d32dabf0e0086398180b5dca50ad5521b60 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
33
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
39#include <hardware/audio.h>
40#include <hardware/audio_effect.h>
41#include <hardware_legacy/audio_policy_conf.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070042#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070043#include "AudioPolicyManager.h"
Eric Laurente552edb2014-03-10 17:42:56 -070044
Eric Laurent3b73df72014-03-11 09:06:29 -070045namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070046
47// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070048// Definitions for audio_policy.conf file parsing
49// ----------------------------------------------------------------------------
50
51struct StringToEnum {
52 const char *name;
53 uint32_t value;
54};
55
56#define STRING_TO_ENUM(string) { #string, string }
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
59const StringToEnum sDeviceNameToEnumTable[] = {
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070073 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070074 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700103};
104
105const StringToEnum sFlagNameToEnumTable[] = {
106 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
107 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
112};
113
114const StringToEnum sFormatNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
116 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
121 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
122 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
123 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
124};
125
126const StringToEnum sOutChannelsNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
128 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
129 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
130 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
131};
132
133const StringToEnum sInChannelsNameToEnumTable[] = {
134 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
135 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
136 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
137};
138
139
140uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
141 size_t size,
142 const char *name)
143{
144 for (size_t i = 0; i < size; i++) {
145 if (strcmp(table[i].name, name) == 0) {
146 ALOGV("stringToEnum() found %s", table[i].name);
147 return table[i].value;
148 }
149 }
150 return 0;
151}
152
153const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
154 size_t size,
155 uint32_t value)
156{
157 for (size_t i = 0; i < size; i++) {
158 if (table[i].value == value) {
159 return table[i].name;
160 }
161 }
162 return "";
163}
164
165bool AudioPolicyManager::stringToBool(const char *value)
166{
167 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
168}
169
170
171// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700172// AudioPolicyInterface implementation
173// ----------------------------------------------------------------------------
174
175
Eric Laurente0720872014-03-11 09:30:41 -0700176status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700177 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700178 const char *device_address)
179{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700180 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700181
182 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
183
184 // connect/disconnect only 1 device at a time
185 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
186
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // handle output devices
188 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700189 SortedVector <audio_io_handle_t> outputs;
190
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
192 address,
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700193 0);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
195
Eric Laurente552edb2014-03-10 17:42:56 -0700196 // save a copy of the opened output descriptors before any output is opened or closed
197 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
198 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700199 switch (state)
200 {
201 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700202 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700204 ALOGW("setDeviceConnectionState() device already connected: %x", device);
205 return INVALID_OPERATION;
206 }
207 ALOGV("setDeviceConnectionState() connecting device %x", device);
208
Eric Laurent3a4311c2014-03-17 12:00:47 -0700209 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700210 return INVALID_OPERATION;
211 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700212 // outputs should never be empty here
213 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
214 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700215 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700216 outputs.size());
217 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700218 index = mAvailableOutputDevices.add(devDesc);
219 if (index >= 0) {
220 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700221 HwModule *module = getModuleForDevice(device);
222 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
223 "could not find HW module for device %08x", device);
224 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 } else {
226 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700227 }
228
229 break;
230 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700231 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700233 ALOGW("setDeviceConnectionState() device not connected: %x", device);
234 return INVALID_OPERATION;
235 }
236
237 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
238 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700239 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700240
Eric Laurent3a4311c2014-03-17 12:00:47 -0700241 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // not currently handling multiple simultaneous submixes: ignoring remote submix
243 // case and address
244 } break;
245
246 default:
247 ALOGE("setDeviceConnectionState() invalid state: %x", state);
248 return BAD_VALUE;
249 }
250
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
252 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700253 checkA2dpSuspend();
254 checkOutputForAllStrategies();
255 // outputs must be closed after checkOutputForAllStrategies() is executed
256 if (!outputs.isEmpty()) {
257 for (size_t i = 0; i < outputs.size(); i++) {
258 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
259 // close unused outputs after device disconnection or direct outputs that have been
260 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700261 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700262 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
263 (desc->mDirectOpenCount == 0))) {
264 closeOutput(outputs[i]);
265 }
266 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700267 // check again after closing A2DP output to reset mA2dpSuspended if needed
268 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700269 }
270
271 updateDevicesAndOutputs();
272 for (size_t i = 0; i < mOutputs.size(); i++) {
273 // do not force device change on duplicated output because if device is 0, it will
274 // also force a device 0 for the two outputs it is duplicated to which may override
275 // a valid device selection on those outputs.
276 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent951f4552014-05-20 10:48:17 -0700277 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700278 !mOutputs.valueAt(i)->isDuplicated(),
279 0);
280 }
281
282 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
283 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
284 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
285 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
286 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
287 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
288 } else {
Eric Laurentb52c1522014-05-20 11:27:36 -0700289 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700290 return NO_ERROR;
291 }
Eric Laurentd4692962014-05-05 18:13:44 -0700292 } // end if is output device
293
Eric Laurente552edb2014-03-10 17:42:56 -0700294 // handle input devices
295 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700296 SortedVector <audio_io_handle_t> inputs;
297
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
299 address,
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700300 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700301
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700303 switch (state)
304 {
305 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700306 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700307 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700308 ALOGW("setDeviceConnectionState() device already connected: %d", device);
309 return INVALID_OPERATION;
310 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700311 HwModule *module = getModuleForDevice(device);
312 if (module == NULL) {
313 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
314 device);
315 return INVALID_OPERATION;
316 }
Eric Laurentd4692962014-05-05 18:13:44 -0700317 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
318 return INVALID_OPERATION;
319 }
320
Eric Laurent3a4311c2014-03-17 12:00:47 -0700321 index = mAvailableInputDevices.add(devDesc);
322 if (index >= 0) {
323 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700324 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 } else {
326 return NO_MEMORY;
327 }
Eric Laurentd4692962014-05-05 18:13:44 -0700328 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700329
330 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700331 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700332 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700333 ALOGW("setDeviceConnectionState() device not connected: %d", device);
334 return INVALID_OPERATION;
335 }
Eric Laurentd4692962014-05-05 18:13:44 -0700336 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700337 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700338 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700339
340 default:
341 ALOGE("setDeviceConnectionState() invalid state: %x", state);
342 return BAD_VALUE;
343 }
344
Eric Laurentd4692962014-05-05 18:13:44 -0700345 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700346
Eric Laurentb52c1522014-05-20 11:27:36 -0700347 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700348 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700349 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700350
351 ALOGW("setDeviceConnectionState() invalid device: %x", device);
352 return BAD_VALUE;
353}
354
Eric Laurente0720872014-03-11 09:30:41 -0700355audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700356 const char *device_address)
357{
Eric Laurent3b73df72014-03-11 09:06:29 -0700358 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700359 String8 address = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
361 String8(device_address),
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700362 0);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700363 ssize_t index;
364 DeviceVector *deviceVector;
365
Eric Laurente552edb2014-03-10 17:42:56 -0700366 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700368 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700369 deviceVector = &mAvailableInputDevices;
370 } else {
371 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
372 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700373 }
374
Eric Laurent3a4311c2014-03-17 12:00:47 -0700375 index = deviceVector->indexOf(devDesc);
376 if (index >= 0) {
377 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
378 } else {
379 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
380 }
Eric Laurente552edb2014-03-10 17:42:56 -0700381}
382
Eric Laurente0720872014-03-11 09:30:41 -0700383void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700384{
385 ALOGV("setPhoneState() state %d", state);
386 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700388 ALOGW("setPhoneState() invalid state %d", state);
389 return;
390 }
391
392 if (state == mPhoneState ) {
393 ALOGW("setPhoneState() setting same state %d", state);
394 return;
395 }
396
397 // if leaving call state, handle special case of active streams
398 // pertaining to sonification strategy see handleIncallSonification()
399 if (isInCall()) {
400 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700401 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
402 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700403 }
404 }
405
406 // store previous phone state for management of sonification strategy below
407 int oldState = mPhoneState;
408 mPhoneState = state;
409 bool force = false;
410
411 // are we entering or starting a call
412 if (!isStateInCall(oldState) && isStateInCall(state)) {
413 ALOGV(" Entering call in setPhoneState()");
414 // force routing command to audio hardware when starting a call
415 // even if no device change is needed
416 force = true;
417 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
418 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
419 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
420 }
421 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
422 ALOGV(" Exiting call in setPhoneState()");
423 // force routing command to audio hardware when exiting a call
424 // even if no device change is needed
425 force = true;
426 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
427 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
428 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
429 }
430 } else if (isStateInCall(state) && (state != oldState)) {
431 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
432 // force routing command to audio hardware when switching between telephony and VoIP
433 // even if no device change is needed
434 force = true;
435 }
436
437 // check for device and output changes triggered by new phone state
Eric Laurent951f4552014-05-20 10:48:17 -0700438 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700439 checkA2dpSuspend();
440 checkOutputForAllStrategies();
441 updateDevicesAndOutputs();
442
443 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
444
445 // force routing command to audio hardware when ending call
446 // even if no device change is needed
447 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
448 newDevice = hwOutputDesc->device();
449 }
450
451 int delayMs = 0;
452 if (isStateInCall(state)) {
453 nsecs_t sysTime = systemTime();
454 for (size_t i = 0; i < mOutputs.size(); i++) {
455 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
456 // mute media and sonification strategies and delay device switch by the largest
457 // latency of any output where either strategy is active.
458 // This avoid sending the ring tone or music tail into the earpiece or headset.
459 if ((desc->isStrategyActive(STRATEGY_MEDIA,
460 SONIFICATION_HEADSET_MUSIC_DELAY,
461 sysTime) ||
462 desc->isStrategyActive(STRATEGY_SONIFICATION,
463 SONIFICATION_HEADSET_MUSIC_DELAY,
464 sysTime)) &&
465 (delayMs < (int)desc->mLatency*2)) {
466 delayMs = desc->mLatency*2;
467 }
468 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
469 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
470 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
471 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
472 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
473 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
474 }
475 }
476
477 // change routing is necessary
478 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
479
480 // if entering in call state, handle special case of active streams
481 // pertaining to sonification strategy see handleIncallSonification()
482 if (isStateInCall(state)) {
483 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700484 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
485 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700486 }
487 }
488
489 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700490 if (state == AUDIO_MODE_RINGTONE &&
491 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700492 mLimitRingtoneVolume = true;
493 } else {
494 mLimitRingtoneVolume = false;
495 }
496}
497
Eric Laurente0720872014-03-11 09:30:41 -0700498void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700499 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700500{
501 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
502
503 bool forceVolumeReeval = false;
504 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700505 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
506 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
507 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700508 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
509 return;
510 }
511 forceVolumeReeval = true;
512 mForceUse[usage] = config;
513 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700514 case AUDIO_POLICY_FORCE_FOR_MEDIA:
515 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
516 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
517 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
518 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
519 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700520 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
521 return;
522 }
523 mForceUse[usage] = config;
524 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700525 case AUDIO_POLICY_FORCE_FOR_RECORD:
526 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
527 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700528 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
529 return;
530 }
531 mForceUse[usage] = config;
532 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700533 case AUDIO_POLICY_FORCE_FOR_DOCK:
534 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
535 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
536 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
537 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
538 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
540 }
541 forceVolumeReeval = true;
542 mForceUse[usage] = config;
543 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700544 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
545 if (config != AUDIO_POLICY_FORCE_NONE &&
546 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700547 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
548 }
549 forceVolumeReeval = true;
550 mForceUse[usage] = config;
551 break;
552 default:
553 ALOGW("setForceUse() invalid usage %d", usage);
554 break;
555 }
556
557 // check for device and output changes triggered by new force usage
558 checkA2dpSuspend();
559 checkOutputForAllStrategies();
560 updateDevicesAndOutputs();
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent951f4552014-05-20 10:48:17 -0700563 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700564 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
565 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
566 applyStreamVolumes(output, newDevice, 0, true);
567 }
568 }
569
570 audio_io_handle_t activeInput = getActiveInput();
571 if (activeInput != 0) {
Eric Laurent951f4552014-05-20 10:48:17 -0700572 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700573 }
574
575}
576
Eric Laurente0720872014-03-11 09:30:41 -0700577audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700578{
579 return mForceUse[usage];
580}
581
Eric Laurente0720872014-03-11 09:30:41 -0700582void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700583{
584 ALOGV("setSystemProperty() property %s, value %s", property, value);
585}
586
587// Find a direct output profile compatible with the parameters passed, even if the input flags do
588// not explicitly request a direct output
Eric Laurent951f4552014-05-20 10:48:17 -0700589sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700590 audio_devices_t device,
591 uint32_t samplingRate,
592 audio_format_t format,
593 audio_channel_mask_t channelMask,
594 audio_output_flags_t flags)
595{
596 for (size_t i = 0; i < mHwModules.size(); i++) {
597 if (mHwModules[i]->mHandle == 0) {
598 continue;
599 }
600 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent951f4552014-05-20 10:48:17 -0700601 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700602 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700603 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
604 if (profile->isCompatibleProfile(device, samplingRate, format,
605 channelMask,
606 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700607 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700608 }
609 } else {
610 if (profile->isCompatibleProfile(device, samplingRate, format,
611 channelMask,
612 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700613 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700614 }
615 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700616 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
617 return profile;
618 }
Eric Laurente552edb2014-03-10 17:42:56 -0700619 }
620 }
621 return 0;
622}
623
Eric Laurente0720872014-03-11 09:30:41 -0700624audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700625 uint32_t samplingRate,
626 audio_format_t format,
627 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700628 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700629 const audio_offload_info_t *offloadInfo)
630{
631 audio_io_handle_t output = 0;
632 uint32_t latency = 0;
Eric Laurent3b73df72014-03-11 09:06:29 -0700633 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700634 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
635 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
636 device, stream, samplingRate, format, channelMask, flags);
637
638#ifdef AUDIO_POLICY_TEST
639 if (mCurOutput != 0) {
640 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
641 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
642
643 if (mTestOutputs[mCurOutput] == 0) {
644 ALOGV("getOutput() opening test output");
645 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
646 outputDesc->mDevice = mTestDevice;
647 outputDesc->mSamplingRate = mTestSamplingRate;
648 outputDesc->mFormat = mTestFormat;
649 outputDesc->mChannelMask = mTestChannels;
650 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700651 outputDesc->mFlags =
652 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700653 outputDesc->mRefCount[stream] = 0;
654 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
655 &outputDesc->mSamplingRate,
656 &outputDesc->mFormat,
657 &outputDesc->mChannelMask,
658 &outputDesc->mLatency,
659 outputDesc->mFlags,
660 offloadInfo);
661 if (mTestOutputs[mCurOutput]) {
662 AudioParameter outputCmd = AudioParameter();
663 outputCmd.addInt(String8("set_id"),mCurOutput);
664 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
665 addOutput(mTestOutputs[mCurOutput], outputDesc);
666 }
667 }
668 return mTestOutputs[mCurOutput];
669 }
670#endif //AUDIO_POLICY_TEST
671
672 // open a direct output if required by specified parameters
673 //force direct flag if offload flag is set: offloading implies a direct output stream
674 // and all common behaviors are driven by checking only the direct flag
675 // this should normally be set appropriately in the policy configuration file
676 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700677 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700678 }
679
680 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
681 // creating an offloaded track and tearing it down immediately after start when audioflinger
682 // detects there is an active non offloadable effect.
683 // FIXME: We should check the audio session here but we do not have it in this context.
684 // This may prevent offloading in rare situations where effects are left active by apps
685 // in the background.
Eric Laurent951f4552014-05-20 10:48:17 -0700686 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700687 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
688 !isNonOffloadableEffectEnabled()) {
689 profile = getProfileForDirectOutput(device,
690 samplingRate,
691 format,
692 channelMask,
693 (audio_output_flags_t)flags);
694 }
695
Eric Laurent951f4552014-05-20 10:48:17 -0700696 if (profile != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700697 AudioOutputDescriptor *outputDesc = NULL;
698
699 for (size_t i = 0; i < mOutputs.size(); i++) {
700 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
701 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
702 outputDesc = desc;
703 // reuse direct output if currently open and configured with same parameters
704 if ((samplingRate == outputDesc->mSamplingRate) &&
705 (format == outputDesc->mFormat) &&
706 (channelMask == outputDesc->mChannelMask)) {
707 outputDesc->mDirectOpenCount++;
708 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
709 return mOutputs.keyAt(i);
710 }
711 }
712 }
713 // close direct output if currently open and configured with different parameters
714 if (outputDesc != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -0700715 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700716 }
717 outputDesc = new AudioOutputDescriptor(profile);
718 outputDesc->mDevice = device;
719 outputDesc->mSamplingRate = samplingRate;
720 outputDesc->mFormat = format;
721 outputDesc->mChannelMask = channelMask;
722 outputDesc->mLatency = 0;
723 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
724 outputDesc->mRefCount[stream] = 0;
725 outputDesc->mStopTime[stream] = 0;
726 outputDesc->mDirectOpenCount = 1;
727 output = mpClientInterface->openOutput(profile->mModule->mHandle,
728 &outputDesc->mDevice,
729 &outputDesc->mSamplingRate,
730 &outputDesc->mFormat,
731 &outputDesc->mChannelMask,
732 &outputDesc->mLatency,
733 outputDesc->mFlags,
734 offloadInfo);
735
736 // only accept an output with the requested parameters
737 if (output == 0 ||
738 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
739 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
740 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
741 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
742 "format %d %d, channelMask %04x %04x", output, samplingRate,
743 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
744 outputDesc->mChannelMask);
745 if (output != 0) {
746 mpClientInterface->closeOutput(output);
747 }
748 delete outputDesc;
749 return 0;
750 }
751 audio_io_handle_t srcOutput = getOutputForEffect();
752 addOutput(output, outputDesc);
753 audio_io_handle_t dstOutput = getOutputForEffect();
754 if (dstOutput == output) {
755 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
756 }
757 mPreviousOutputs = mOutputs;
758 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700759 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700760 return output;
761 }
762
763 // ignoring channel mask due to downmix capability in mixer
764
765 // open a non direct output
766
767 // for non direct outputs, only PCM is supported
768 if (audio_is_linear_pcm(format)) {
769 // get which output is suitable for the specified stream. The actual
770 // routing change will happen when startOutput() will be called
771 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
772
773 output = selectOutput(outputs, flags);
774 }
775 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
776 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
777
778 ALOGV("getOutput() returns output %d", output);
779
780 return output;
781}
782
Eric Laurente0720872014-03-11 09:30:41 -0700783audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700784 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700785{
786 // select one output among several that provide a path to a particular device or set of
787 // devices (the list was previously build by getOutputsForDevice()).
788 // The priority is as follows:
789 // 1: the output with the highest number of requested policy flags
790 // 2: the primary output
791 // 3: the first output in the list
792
793 if (outputs.size() == 0) {
794 return 0;
795 }
796 if (outputs.size() == 1) {
797 return outputs[0];
798 }
799
800 int maxCommonFlags = 0;
801 audio_io_handle_t outputFlags = 0;
802 audio_io_handle_t outputPrimary = 0;
803
804 for (size_t i = 0; i < outputs.size(); i++) {
805 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
806 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700807 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700808 if (commonFlags > maxCommonFlags) {
809 outputFlags = outputs[i];
810 maxCommonFlags = commonFlags;
811 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
812 }
813 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
814 outputPrimary = outputs[i];
815 }
816 }
817 }
818
819 if (outputFlags != 0) {
820 return outputFlags;
821 }
822 if (outputPrimary != 0) {
823 return outputPrimary;
824 }
825
826 return outputs[0];
827}
828
Eric Laurente0720872014-03-11 09:30:41 -0700829status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700830 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700831 int session)
832{
833 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
834 ssize_t index = mOutputs.indexOfKey(output);
835 if (index < 0) {
836 ALOGW("startOutput() unknown output %d", output);
837 return BAD_VALUE;
838 }
839
840 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
841
842 // increment usage count for this stream on the requested output:
843 // NOTE that the usage count is the same for duplicated output and hardware output which is
844 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
845 outputDesc->changeRefCount(stream, 1);
846
847 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent951f4552014-05-20 10:48:17 -0700848 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700849 routing_strategy strategy = getStrategy(stream);
850 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
851 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
852 uint32_t waitMs = 0;
853 bool force = false;
854 for (size_t i = 0; i < mOutputs.size(); i++) {
855 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
856 if (desc != outputDesc) {
857 // force a device change if any other output is managed by the same hw
858 // module and has a current device selection that differs from selected device.
859 // In this case, the audio HAL must receive the new device selection so that it can
860 // change the device currently selected by the other active output.
861 if (outputDesc->sharesHwModuleWith(desc) &&
862 desc->device() != newDevice) {
863 force = true;
864 }
865 // wait for audio on other active outputs to be presented when starting
866 // a notification so that audio focus effect can propagate.
867 uint32_t latency = desc->latency();
868 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
869 waitMs = latency;
870 }
871 }
872 }
873 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
874
875 // handle special case for sonification while in call
876 if (isInCall()) {
877 handleIncallSonification(stream, true, false);
878 }
879
880 // apply volume rules for current stream and device if necessary
881 checkAndSetVolume(stream,
882 mStreams[stream].getVolumeIndex(newDevice),
883 output,
884 newDevice);
885
886 // update the outputs if starting an output with a stream that can affect notification
887 // routing
888 handleNotificationRoutingForStream(stream);
889 if (waitMs > muteWaitMs) {
890 usleep((waitMs - muteWaitMs) * 2 * 1000);
891 }
892 }
893 return NO_ERROR;
894}
895
896
Eric Laurente0720872014-03-11 09:30:41 -0700897status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700898 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700899 int session)
900{
901 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
902 ssize_t index = mOutputs.indexOfKey(output);
903 if (index < 0) {
904 ALOGW("stopOutput() unknown output %d", output);
905 return BAD_VALUE;
906 }
907
908 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
909
910 // handle special case for sonification while in call
911 if (isInCall()) {
912 handleIncallSonification(stream, false, false);
913 }
914
915 if (outputDesc->mRefCount[stream] > 0) {
916 // decrement usage count of this stream on the output
917 outputDesc->changeRefCount(stream, -1);
918 // store time at which the stream was stopped - see isStreamActive()
919 if (outputDesc->mRefCount[stream] == 0) {
920 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent951f4552014-05-20 10:48:17 -0700921 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700922 // delay the device switch by twice the latency because stopOutput() is executed when
923 // the track stop() command is received and at that time the audio track buffer can
924 // still contain data that needs to be drained. The latency only covers the audio HAL
925 // and kernel buffers. Also the latency does not always include additional delay in the
926 // audio path (audio DSP, CODEC ...)
927 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
928
929 // force restoring the device selection on other active outputs if it differs from the
930 // one being selected for this output
931 for (size_t i = 0; i < mOutputs.size(); i++) {
932 audio_io_handle_t curOutput = mOutputs.keyAt(i);
933 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
934 if (curOutput != output &&
935 desc->isActive() &&
936 outputDesc->sharesHwModuleWith(desc) &&
937 (newDevice != desc->device())) {
938 setOutputDevice(curOutput,
Eric Laurent951f4552014-05-20 10:48:17 -0700939 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700940 true,
941 outputDesc->mLatency*2);
942 }
943 }
944 // update the outputs if stopping one with a stream that can affect notification routing
945 handleNotificationRoutingForStream(stream);
946 }
947 return NO_ERROR;
948 } else {
949 ALOGW("stopOutput() refcount is already 0 for output %d", output);
950 return INVALID_OPERATION;
951 }
952}
953
Eric Laurente0720872014-03-11 09:30:41 -0700954void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700955{
956 ALOGV("releaseOutput() %d", output);
957 ssize_t index = mOutputs.indexOfKey(output);
958 if (index < 0) {
959 ALOGW("releaseOutput() releasing unknown output %d", output);
960 return;
961 }
962
963#ifdef AUDIO_POLICY_TEST
964 int testIndex = testOutputIndex(output);
965 if (testIndex != 0) {
966 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
967 if (outputDesc->isActive()) {
968 mpClientInterface->closeOutput(output);
969 delete mOutputs.valueAt(index);
970 mOutputs.removeItem(output);
971 mTestOutputs[testIndex] = 0;
972 }
973 return;
974 }
975#endif //AUDIO_POLICY_TEST
976
977 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -0700978 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700979 if (desc->mDirectOpenCount <= 0) {
980 ALOGW("releaseOutput() invalid open count %d for output %d",
981 desc->mDirectOpenCount, output);
982 return;
983 }
984 if (--desc->mDirectOpenCount == 0) {
985 closeOutput(output);
986 // If effects where present on the output, audioflinger moved them to the primary
987 // output by default: move them back to the appropriate output.
988 audio_io_handle_t dstOutput = getOutputForEffect();
989 if (dstOutput != mPrimaryOutput) {
990 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
991 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700992 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700993 }
994 }
995}
996
997
Eric Laurente0720872014-03-11 09:30:41 -0700998audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -0700999 uint32_t samplingRate,
1000 audio_format_t format,
1001 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001002 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001003{
1004 audio_io_handle_t input = 0;
1005 audio_devices_t device = getDeviceForInputSource(inputSource);
1006
1007 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1008 inputSource, samplingRate, format, channelMask, acoustics);
1009
1010 if (device == AUDIO_DEVICE_NONE) {
1011 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1012 return 0;
1013 }
1014
1015 // adapt channel selection to input source
1016 switch(inputSource) {
1017 case AUDIO_SOURCE_VOICE_UPLINK:
1018 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1019 break;
1020 case AUDIO_SOURCE_VOICE_DOWNLINK:
1021 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1022 break;
1023 case AUDIO_SOURCE_VOICE_CALL:
1024 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1025 break;
1026 default:
1027 break;
1028 }
1029
Eric Laurent951f4552014-05-20 10:48:17 -07001030 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001031 samplingRate,
1032 format,
1033 channelMask);
Eric Laurent951f4552014-05-20 10:48:17 -07001034 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001035 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1036 "channelMask %04x",
1037 device, samplingRate, format, channelMask);
1038 return 0;
1039 }
1040
1041 if (profile->mModule->mHandle == 0) {
1042 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1043 return 0;
1044 }
1045
1046 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
1047
1048 inputDesc->mInputSource = inputSource;
1049 inputDesc->mDevice = device;
1050 inputDesc->mSamplingRate = samplingRate;
1051 inputDesc->mFormat = format;
1052 inputDesc->mChannelMask = channelMask;
1053 inputDesc->mRefCount = 0;
1054 input = mpClientInterface->openInput(profile->mModule->mHandle,
1055 &inputDesc->mDevice,
1056 &inputDesc->mSamplingRate,
1057 &inputDesc->mFormat,
1058 &inputDesc->mChannelMask);
1059
1060 // only accept input with the exact requested set of parameters
1061 if (input == 0 ||
1062 (samplingRate != inputDesc->mSamplingRate) ||
1063 (format != inputDesc->mFormat) ||
1064 (channelMask != inputDesc->mChannelMask)) {
1065 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1066 samplingRate, format, channelMask);
1067 if (input != 0) {
1068 mpClientInterface->closeInput(input);
1069 }
1070 delete inputDesc;
1071 return 0;
1072 }
Eric Laurentd4692962014-05-05 18:13:44 -07001073 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001074 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001075 return input;
1076}
1077
Eric Laurente0720872014-03-11 09:30:41 -07001078status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001079{
1080 ALOGV("startInput() input %d", input);
1081 ssize_t index = mInputs.indexOfKey(input);
1082 if (index < 0) {
1083 ALOGW("startInput() unknown input %d", input);
1084 return BAD_VALUE;
1085 }
1086 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1087
1088#ifdef AUDIO_POLICY_TEST
1089 if (mTestInput == 0)
1090#endif //AUDIO_POLICY_TEST
1091 {
1092 // refuse 2 active AudioRecord clients at the same time except if the active input
1093 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1094 audio_io_handle_t activeInput = getActiveInput();
1095 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1096 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1097 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1098 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1099 stopInput(activeInput);
1100 releaseInput(activeInput);
1101 } else {
1102 ALOGW("startInput() input %d failed: other input already started", input);
1103 return INVALID_OPERATION;
1104 }
1105 }
1106 }
1107
Eric Laurent951f4552014-05-20 10:48:17 -07001108 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001109
1110 // automatically enable the remote submix output when input is started
1111 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1112 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001113 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001114 }
1115
Eric Laurente552edb2014-03-10 17:42:56 -07001116 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1117
Eric Laurente552edb2014-03-10 17:42:56 -07001118 inputDesc->mRefCount = 1;
1119 return NO_ERROR;
1120}
1121
Eric Laurente0720872014-03-11 09:30:41 -07001122status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001123{
1124 ALOGV("stopInput() input %d", input);
1125 ssize_t index = mInputs.indexOfKey(input);
1126 if (index < 0) {
1127 ALOGW("stopInput() unknown input %d", input);
1128 return BAD_VALUE;
1129 }
1130 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1131
1132 if (inputDesc->mRefCount == 0) {
1133 ALOGW("stopInput() input %d already stopped", input);
1134 return INVALID_OPERATION;
1135 } else {
1136 // automatically disable the remote submix output when input is stopped
1137 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1138 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001139 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001140 }
1141
Eric Laurent951f4552014-05-20 10:48:17 -07001142 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001143 inputDesc->mRefCount = 0;
1144 return NO_ERROR;
1145 }
1146}
1147
Eric Laurente0720872014-03-11 09:30:41 -07001148void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001149{
1150 ALOGV("releaseInput() %d", input);
1151 ssize_t index = mInputs.indexOfKey(input);
1152 if (index < 0) {
1153 ALOGW("releaseInput() releasing unknown input %d", input);
1154 return;
1155 }
1156 mpClientInterface->closeInput(input);
1157 delete mInputs.valueAt(index);
1158 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001159 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001160 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001161 ALOGV("releaseInput() exit");
1162}
1163
Eric Laurentd4692962014-05-05 18:13:44 -07001164void AudioPolicyManager::closeAllInputs() {
1165 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1166 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1167 }
1168 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001169 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001170}
1171
Eric Laurente0720872014-03-11 09:30:41 -07001172void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001173 int indexMin,
1174 int indexMax)
1175{
1176 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1177 if (indexMin < 0 || indexMin >= indexMax) {
1178 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1179 return;
1180 }
1181 mStreams[stream].mIndexMin = indexMin;
1182 mStreams[stream].mIndexMax = indexMax;
1183}
1184
Eric Laurente0720872014-03-11 09:30:41 -07001185status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001186 int index,
1187 audio_devices_t device)
1188{
1189
1190 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1191 return BAD_VALUE;
1192 }
1193 if (!audio_is_output_device(device)) {
1194 return BAD_VALUE;
1195 }
1196
1197 // Force max volume if stream cannot be muted
1198 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1199
1200 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1201 stream, device, index);
1202
1203 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1204 // clear all device specific values
1205 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1206 mStreams[stream].mIndexCur.clear();
1207 }
1208 mStreams[stream].mIndexCur.add(device, index);
1209
1210 // compute and apply stream volume on all outputs according to connected device
1211 status_t status = NO_ERROR;
1212 for (size_t i = 0; i < mOutputs.size(); i++) {
1213 audio_devices_t curDevice =
1214 getDeviceForVolume(mOutputs.valueAt(i)->device());
1215 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1216 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1217 if (volStatus != NO_ERROR) {
1218 status = volStatus;
1219 }
1220 }
1221 }
1222 return status;
1223}
1224
Eric Laurente0720872014-03-11 09:30:41 -07001225status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001226 int *index,
1227 audio_devices_t device)
1228{
1229 if (index == NULL) {
1230 return BAD_VALUE;
1231 }
1232 if (!audio_is_output_device(device)) {
1233 return BAD_VALUE;
1234 }
1235 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1236 // the strategy the stream belongs to.
1237 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1238 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1239 }
1240 device = getDeviceForVolume(device);
1241
1242 *index = mStreams[stream].getVolumeIndex(device);
1243 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1244 return NO_ERROR;
1245}
1246
Eric Laurente0720872014-03-11 09:30:41 -07001247audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001248 const SortedVector<audio_io_handle_t>& outputs)
1249{
1250 // select one output among several suitable for global effects.
1251 // The priority is as follows:
1252 // 1: An offloaded output. If the effect ends up not being offloadable,
1253 // AudioFlinger will invalidate the track and the offloaded output
1254 // will be closed causing the effect to be moved to a PCM output.
1255 // 2: A deep buffer output
1256 // 3: the first output in the list
1257
1258 if (outputs.size() == 0) {
1259 return 0;
1260 }
1261
1262 audio_io_handle_t outputOffloaded = 0;
1263 audio_io_handle_t outputDeepBuffer = 0;
1264
1265 for (size_t i = 0; i < outputs.size(); i++) {
1266 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001267 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001268 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1269 outputOffloaded = outputs[i];
1270 }
1271 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1272 outputDeepBuffer = outputs[i];
1273 }
1274 }
1275
1276 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1277 outputOffloaded, outputDeepBuffer);
1278 if (outputOffloaded != 0) {
1279 return outputOffloaded;
1280 }
1281 if (outputDeepBuffer != 0) {
1282 return outputDeepBuffer;
1283 }
1284
1285 return outputs[0];
1286}
1287
Eric Laurente0720872014-03-11 09:30:41 -07001288audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001289{
1290 // apply simple rule where global effects are attached to the same output as MUSIC streams
1291
Eric Laurent3b73df72014-03-11 09:06:29 -07001292 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001293 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1294 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1295
1296 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1297 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1298 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1299
1300 return output;
1301}
1302
Eric Laurente0720872014-03-11 09:30:41 -07001303status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001304 audio_io_handle_t io,
1305 uint32_t strategy,
1306 int session,
1307 int id)
1308{
1309 ssize_t index = mOutputs.indexOfKey(io);
1310 if (index < 0) {
1311 index = mInputs.indexOfKey(io);
1312 if (index < 0) {
1313 ALOGW("registerEffect() unknown io %d", io);
1314 return INVALID_OPERATION;
1315 }
1316 }
1317
1318 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1319 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1320 desc->name, desc->memoryUsage);
1321 return INVALID_OPERATION;
1322 }
1323 mTotalEffectsMemory += desc->memoryUsage;
1324 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1325 desc->name, io, strategy, session, id);
1326 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1327
1328 EffectDescriptor *pDesc = new EffectDescriptor();
1329 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1330 pDesc->mIo = io;
1331 pDesc->mStrategy = (routing_strategy)strategy;
1332 pDesc->mSession = session;
1333 pDesc->mEnabled = false;
1334
1335 mEffects.add(id, pDesc);
1336
1337 return NO_ERROR;
1338}
1339
Eric Laurente0720872014-03-11 09:30:41 -07001340status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001341{
1342 ssize_t index = mEffects.indexOfKey(id);
1343 if (index < 0) {
1344 ALOGW("unregisterEffect() unknown effect ID %d", id);
1345 return INVALID_OPERATION;
1346 }
1347
1348 EffectDescriptor *pDesc = mEffects.valueAt(index);
1349
1350 setEffectEnabled(pDesc, false);
1351
1352 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1353 ALOGW("unregisterEffect() memory %d too big for total %d",
1354 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1355 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1356 }
1357 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1358 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1359 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1360
1361 mEffects.removeItem(id);
1362 delete pDesc;
1363
1364 return NO_ERROR;
1365}
1366
Eric Laurente0720872014-03-11 09:30:41 -07001367status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001368{
1369 ssize_t index = mEffects.indexOfKey(id);
1370 if (index < 0) {
1371 ALOGW("unregisterEffect() unknown effect ID %d", id);
1372 return INVALID_OPERATION;
1373 }
1374
1375 return setEffectEnabled(mEffects.valueAt(index), enabled);
1376}
1377
Eric Laurente0720872014-03-11 09:30:41 -07001378status_t AudioPolicyManager::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001379{
1380 if (enabled == pDesc->mEnabled) {
1381 ALOGV("setEffectEnabled(%s) effect already %s",
1382 enabled?"true":"false", enabled?"enabled":"disabled");
1383 return INVALID_OPERATION;
1384 }
1385
1386 if (enabled) {
1387 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1388 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1389 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1390 return INVALID_OPERATION;
1391 }
1392 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1393 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1394 } else {
1395 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1396 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1397 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1398 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1399 }
1400 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1401 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1402 }
1403 pDesc->mEnabled = enabled;
1404 return NO_ERROR;
1405}
1406
Eric Laurente0720872014-03-11 09:30:41 -07001407bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001408{
1409 for (size_t i = 0; i < mEffects.size(); i++) {
1410 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1411 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1412 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1413 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1414 pDesc->mDesc.name, pDesc->mSession);
1415 return true;
1416 }
1417 }
1418 return false;
1419}
1420
Eric Laurente0720872014-03-11 09:30:41 -07001421bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001422{
1423 nsecs_t sysTime = systemTime();
1424 for (size_t i = 0; i < mOutputs.size(); i++) {
1425 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001426 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001427 return true;
1428 }
1429 }
1430 return false;
1431}
1432
Eric Laurente0720872014-03-11 09:30:41 -07001433bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001434 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001435{
1436 nsecs_t sysTime = systemTime();
1437 for (size_t i = 0; i < mOutputs.size(); i++) {
1438 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1439 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001440 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001441 return true;
1442 }
1443 }
1444 return false;
1445}
1446
Eric Laurente0720872014-03-11 09:30:41 -07001447bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001448{
1449 for (size_t i = 0; i < mInputs.size(); i++) {
1450 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1451 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001452 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001453 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1454 && (inputDescriptor->mRefCount > 0)) {
1455 return true;
1456 }
1457 }
1458 return false;
1459}
1460
1461
Eric Laurente0720872014-03-11 09:30:41 -07001462status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001463{
1464 const size_t SIZE = 256;
1465 char buffer[SIZE];
1466 String8 result;
1467
1468 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1469 result.append(buffer);
1470
1471 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1472 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001473 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1474 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001475 snprintf(buffer, SIZE, " Force use for communications %d\n",
1476 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001477 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001478 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001479 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001480 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001481 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001482 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001483 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001484 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001485 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001486
Eric Laurent3a4311c2014-03-17 12:00:47 -07001487 snprintf(buffer, SIZE, " Available output devices:\n");
1488 result.append(buffer);
1489 write(fd, result.string(), result.size());
1490 DeviceDescriptor::dumpHeader(fd, 2);
1491 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
1492 mAvailableOutputDevices[i]->dump(fd, 2);
1493 }
1494 snprintf(buffer, SIZE, "\n Available input devices:\n");
1495 write(fd, buffer, strlen(buffer));
1496 DeviceDescriptor::dumpHeader(fd, 2);
1497 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1498 mAvailableInputDevices[i]->dump(fd, 2);
1499 }
Eric Laurente552edb2014-03-10 17:42:56 -07001500
1501 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1502 write(fd, buffer, strlen(buffer));
1503 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001504 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001505 write(fd, buffer, strlen(buffer));
1506 mHwModules[i]->dump(fd);
1507 }
1508
1509 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1510 write(fd, buffer, strlen(buffer));
1511 for (size_t i = 0; i < mOutputs.size(); i++) {
1512 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1513 write(fd, buffer, strlen(buffer));
1514 mOutputs.valueAt(i)->dump(fd);
1515 }
1516
1517 snprintf(buffer, SIZE, "\nInputs dump:\n");
1518 write(fd, buffer, strlen(buffer));
1519 for (size_t i = 0; i < mInputs.size(); i++) {
1520 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1521 write(fd, buffer, strlen(buffer));
1522 mInputs.valueAt(i)->dump(fd);
1523 }
1524
1525 snprintf(buffer, SIZE, "\nStreams dump:\n");
1526 write(fd, buffer, strlen(buffer));
1527 snprintf(buffer, SIZE,
1528 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1529 write(fd, buffer, strlen(buffer));
Eric Laurent3b73df72014-03-11 09:06:29 -07001530 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001531 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001532 write(fd, buffer, strlen(buffer));
1533 mStreams[i].dump(fd);
1534 }
1535
1536 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1537 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1538 write(fd, buffer, strlen(buffer));
1539
1540 snprintf(buffer, SIZE, "Registered effects:\n");
1541 write(fd, buffer, strlen(buffer));
1542 for (size_t i = 0; i < mEffects.size(); i++) {
1543 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1544 write(fd, buffer, strlen(buffer));
1545 mEffects.valueAt(i)->dump(fd);
1546 }
1547
1548
1549 return NO_ERROR;
1550}
1551
1552// This function checks for the parameters which can be offloaded.
1553// This can be enhanced depending on the capability of the DSP and policy
1554// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001555bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001556{
1557 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001558 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001559 offloadInfo.sample_rate, offloadInfo.channel_mask,
1560 offloadInfo.format,
1561 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1562 offloadInfo.has_video);
1563
1564 // Check if offload has been disabled
1565 char propValue[PROPERTY_VALUE_MAX];
1566 if (property_get("audio.offload.disable", propValue, "0")) {
1567 if (atoi(propValue) != 0) {
1568 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1569 return false;
1570 }
1571 }
1572
1573 // Check if stream type is music, then only allow offload as of now.
1574 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1575 {
1576 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1577 return false;
1578 }
1579
1580 //TODO: enable audio offloading with video when ready
1581 if (offloadInfo.has_video)
1582 {
1583 ALOGV("isOffloadSupported: has_video == true, returning false");
1584 return false;
1585 }
1586
1587 //If duration is less than minimum value defined in property, return false
1588 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1589 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1590 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1591 return false;
1592 }
1593 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1594 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1595 return false;
1596 }
1597
1598 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1599 // creating an offloaded track and tearing it down immediately after start when audioflinger
1600 // detects there is an active non offloadable effect.
1601 // FIXME: We should check the audio session here but we do not have it in this context.
1602 // This may prevent offloading in rare situations where effects are left active by apps
1603 // in the background.
1604 if (isNonOffloadableEffectEnabled()) {
1605 return false;
1606 }
1607
1608 // See if there is a profile to support this.
1609 // AUDIO_DEVICE_NONE
Eric Laurent951f4552014-05-20 10:48:17 -07001610 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001611 offloadInfo.sample_rate,
1612 offloadInfo.format,
1613 offloadInfo.channel_mask,
1614 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent951f4552014-05-20 10:48:17 -07001615 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1616 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001617}
1618
Eric Laurent6a94d692014-05-20 11:18:06 -07001619status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1620 audio_port_type_t type,
1621 unsigned int *num_ports,
1622 struct audio_port *ports,
1623 unsigned int *generation)
1624{
1625 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1626 generation == NULL) {
1627 return BAD_VALUE;
1628 }
1629 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1630 if (ports == NULL) {
1631 *num_ports = 0;
1632 }
1633
1634 size_t portsWritten = 0;
1635 size_t portsMax = *num_ports;
1636 *num_ports = 0;
1637 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1638 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1639 for (size_t i = 0;
1640 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1641 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1642 }
1643 *num_ports += mAvailableOutputDevices.size();
1644 }
1645 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1646 for (size_t i = 0;
1647 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1648 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1649 }
1650 *num_ports += mAvailableInputDevices.size();
1651 }
1652 }
1653 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1654 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1655 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1656 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1657 }
1658 *num_ports += mInputs.size();
1659 }
1660 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1661 for (size_t i = 0; i < mOutputs.size() && portsWritten < portsMax; i++) {
1662 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1663 }
1664 *num_ports += mOutputs.size();
1665 }
1666 }
1667 *generation = curAudioPortGeneration();
1668 ALOGV("listAudioPorts() got %d ports needed %d", portsWritten, *num_ports);
1669 return NO_ERROR;
1670}
1671
1672status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1673{
1674 return NO_ERROR;
1675}
1676
1677AudioPolicyManager::AudioOutputDescriptor *AudioPolicyManager::getOutputFromId(
1678 audio_port_handle_t id) const
1679{
1680 AudioOutputDescriptor *outputDesc = NULL;
1681 for (size_t i = 0; i < mOutputs.size(); i++) {
1682 outputDesc = mOutputs.valueAt(i);
1683 if (outputDesc->mId == id) {
1684 break;
1685 }
1686 }
1687 return outputDesc;
1688}
1689
1690AudioPolicyManager::AudioInputDescriptor *AudioPolicyManager::getInputFromId(
1691 audio_port_handle_t id) const
1692{
1693 AudioInputDescriptor *inputDesc = NULL;
1694 for (size_t i = 0; i < mInputs.size(); i++) {
1695 inputDesc = mInputs.valueAt(i);
1696 if (inputDesc->mId == id) {
1697 break;
1698 }
1699 }
1700 return inputDesc;
1701}
1702
1703AudioPolicyManager::HwModule *AudioPolicyManager::getModuleForDevice(audio_devices_t device) const
1704{
1705 for (size_t i = 0; i < mHwModules.size(); i++) {
1706 if (mHwModules[i]->mHandle == 0) {
1707 continue;
1708 }
1709 if (audio_is_output_device(device)) {
1710 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1711 {
1712 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1713 return mHwModules[i];
1714 }
1715 }
1716 } else {
1717 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1718 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1719 device & ~AUDIO_DEVICE_BIT_IN) {
1720 return mHwModules[i];
1721 }
1722 }
1723 }
1724 }
1725 return NULL;
1726}
1727
1728status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1729 audio_patch_handle_t *handle,
1730 uid_t uid)
1731{
1732 ALOGV("createAudioPatch()");
1733
1734 if (handle == NULL || patch == NULL) {
1735 return BAD_VALUE;
1736 }
1737 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1738
1739 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1740 return INVALID_OPERATION;
1741 }
1742 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1743 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1744 return INVALID_OPERATION;
1745 }
1746
1747 sp<AudioPatch> patchDesc;
1748 ssize_t index = mAudioPatches.indexOfKey(*handle);
1749
1750 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1751 patch->sinks[0].type);
1752 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1753 patch->sources[0].role,
1754 patch->sources[0].type);
1755
1756 if (index >= 0) {
1757 patchDesc = mAudioPatches.valueAt(index);
1758 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1759 mUidCached, patchDesc->mUid, uid);
1760 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1761 return INVALID_OPERATION;
1762 }
1763 } else {
1764 *handle = 0;
1765 }
1766
1767 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1768 // TODO add support for mix to mix connection
1769 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1770 ALOGV("createAudioPatch() source mix sink not device");
1771 return BAD_VALUE;
1772 }
1773 // output mix to output device connection
1774 AudioOutputDescriptor *outputDesc = getOutputFromId(patch->sources[0].id);
1775 if (outputDesc == NULL) {
1776 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1777 return BAD_VALUE;
1778 }
1779 if (patchDesc != 0) {
1780 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1781 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1782 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1783 return BAD_VALUE;
1784 }
1785 }
1786 sp<DeviceDescriptor> devDesc =
1787 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1788 if (devDesc == 0) {
1789 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1790 return BAD_VALUE;
1791 }
1792
1793 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1794 patch->sources[0].sample_rate,
1795 patch->sources[0].format,
1796 patch->sources[0].channel_mask,
1797 AUDIO_OUTPUT_FLAG_NONE)) {
1798 return INVALID_OPERATION;
1799 }
1800 // TODO: reconfigure output format and channels here
1801 ALOGV("createAudioPatch() setting device %08x on output %d",
1802 devDesc->mType, outputDesc->mIoHandle);
1803 setOutputDevice(outputDesc->mIoHandle,
1804 devDesc->mType,
1805 true,
1806 0,
1807 handle);
1808 index = mAudioPatches.indexOfKey(*handle);
1809 if (index >= 0) {
1810 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1811 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1812 }
1813 patchDesc = mAudioPatches.valueAt(index);
1814 patchDesc->mUid = uid;
1815 ALOGV("createAudioPatch() success");
1816 } else {
1817 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1818 return INVALID_OPERATION;
1819 }
1820 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1821 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1822 // input device to input mix connection
1823 AudioInputDescriptor *inputDesc = getInputFromId(patch->sinks[0].id);
1824 if (inputDesc == NULL) {
1825 return BAD_VALUE;
1826 }
1827 if (patchDesc != 0) {
1828 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1829 return BAD_VALUE;
1830 }
1831 }
1832 sp<DeviceDescriptor> devDesc =
1833 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1834 if (devDesc == 0) {
1835 return BAD_VALUE;
1836 }
1837
1838 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1839 patch->sinks[0].sample_rate,
1840 patch->sinks[0].format,
1841 patch->sinks[0].channel_mask,
1842 AUDIO_OUTPUT_FLAG_NONE)) {
1843 return INVALID_OPERATION;
1844 }
1845 // TODO: reconfigure output format and channels here
1846 ALOGV("createAudioPatch() setting device %08x on output %d",
1847 devDesc->mType, inputDesc->mIoHandle);
1848 setInputDevice(inputDesc->mIoHandle,
1849 devDesc->mType,
1850 true,
1851 handle);
1852 index = mAudioPatches.indexOfKey(*handle);
1853 if (index >= 0) {
1854 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1855 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1856 }
1857 patchDesc = mAudioPatches.valueAt(index);
1858 patchDesc->mUid = uid;
1859 ALOGV("createAudioPatch() success");
1860 } else {
1861 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1862 return INVALID_OPERATION;
1863 }
1864 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1865 // device to device connection
1866 if (patchDesc != 0) {
1867 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1868 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1869 return BAD_VALUE;
1870 }
1871 }
1872
1873 sp<DeviceDescriptor> srcDeviceDesc =
1874 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1875 sp<DeviceDescriptor> sinkDeviceDesc =
1876 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1877 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1878 return BAD_VALUE;
1879 }
1880 //update source and sink with our own data as the data passed in the patch may
1881 // be incomplete.
1882 struct audio_patch newPatch = *patch;
1883 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1884 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1885
1886 // TODO: add support for devices on different HW modules
1887 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1888 return INVALID_OPERATION;
1889 }
1890 // TODO: check from routing capabilities in config file and other conflicting patches
1891
1892 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1893 if (index >= 0) {
1894 afPatchHandle = patchDesc->mAfPatchHandle;
1895 }
1896
1897 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1898 &afPatchHandle,
1899 0);
1900 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1901 status, afPatchHandle);
1902 if (status == NO_ERROR) {
1903 if (index < 0) {
1904 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1905 &newPatch, uid);
1906 addAudioPatch(patchDesc->mHandle, patchDesc);
1907 } else {
1908 patchDesc->mPatch = newPatch;
1909 }
1910 patchDesc->mAfPatchHandle = afPatchHandle;
1911 *handle = patchDesc->mHandle;
1912 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001913 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001914 } else {
1915 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1916 status);
1917 return INVALID_OPERATION;
1918 }
1919 } else {
1920 return BAD_VALUE;
1921 }
1922 } else {
1923 return BAD_VALUE;
1924 }
1925 return NO_ERROR;
1926}
1927
1928status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1929 uid_t uid)
1930{
1931 ALOGV("releaseAudioPatch() patch %d", handle);
1932
1933 ssize_t index = mAudioPatches.indexOfKey(handle);
1934
1935 if (index < 0) {
1936 return BAD_VALUE;
1937 }
1938 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1939 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1940 mUidCached, patchDesc->mUid, uid);
1941 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1942 return INVALID_OPERATION;
1943 }
1944
1945 struct audio_patch *patch = &patchDesc->mPatch;
1946 patchDesc->mUid = mUidCached;
1947 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1948 AudioOutputDescriptor *outputDesc = getOutputFromId(patch->sources[0].id);
1949 if (outputDesc == NULL) {
1950 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
1951 return BAD_VALUE;
1952 }
1953
1954 setOutputDevice(outputDesc->mIoHandle,
1955 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
1956 true,
1957 0,
1958 NULL);
1959 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1960 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1961 AudioInputDescriptor *inputDesc = getInputFromId(patch->sinks[0].id);
1962 if (inputDesc == NULL) {
1963 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
1964 return BAD_VALUE;
1965 }
1966 setInputDevice(inputDesc->mIoHandle,
1967 getNewInputDevice(inputDesc->mIoHandle),
1968 true,
1969 NULL);
1970 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1971 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
1972 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1973 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
1974 status, patchDesc->mAfPatchHandle);
1975 removeAudioPatch(patchDesc->mHandle);
1976 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001977 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001978 } else {
1979 return BAD_VALUE;
1980 }
1981 } else {
1982 return BAD_VALUE;
1983 }
1984 return NO_ERROR;
1985}
1986
1987status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
1988 struct audio_patch *patches,
1989 unsigned int *generation)
1990{
1991 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
1992 generation == NULL) {
1993 return BAD_VALUE;
1994 }
1995 ALOGV("listAudioPatches() num_patches %d patches %p available patches %d",
1996 *num_patches, patches, mAudioPatches.size());
1997 if (patches == NULL) {
1998 *num_patches = 0;
1999 }
2000
2001 size_t patchesWritten = 0;
2002 size_t patchesMax = *num_patches;
2003 for (size_t i = 0;
2004 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2005 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2006 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
2007 ALOGV("listAudioPatches() patch %d num_sources %d num_sinks %d",
2008 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2009 }
2010 *num_patches = mAudioPatches.size();
2011
2012 *generation = curAudioPortGeneration();
2013 ALOGV("listAudioPatches() got %d patches needed %d", patchesWritten, *num_patches);
2014 return NO_ERROR;
2015}
2016
2017status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config __unused)
2018{
2019 return NO_ERROR;
2020}
2021
2022void AudioPolicyManager::clearAudioPatches(uid_t uid)
2023{
2024 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2025 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2026 if (patchDesc->mUid == uid) {
2027 // releaseAudioPatch() removes the patch from mAudioPatches
2028 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2029 i--;
2030 }
2031 }
2032 }
2033}
2034
2035status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2036 const sp<AudioPatch>& patch)
2037{
2038 ssize_t index = mAudioPatches.indexOfKey(handle);
2039
2040 if (index >= 0) {
2041 ALOGW("addAudioPatch() patch %d already in", handle);
2042 return ALREADY_EXISTS;
2043 }
2044 mAudioPatches.add(handle, patch);
2045 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2046 "sink handle %d",
2047 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2048 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2049 return NO_ERROR;
2050}
2051
2052status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2053{
2054 ssize_t index = mAudioPatches.indexOfKey(handle);
2055
2056 if (index < 0) {
2057 ALOGW("removeAudioPatch() patch %d not in", handle);
2058 return ALREADY_EXISTS;
2059 }
2060 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2061 mAudioPatches.valueAt(index)->mAfPatchHandle);
2062 mAudioPatches.removeItemsAt(index);
2063 return NO_ERROR;
2064}
2065
Eric Laurente552edb2014-03-10 17:42:56 -07002066// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002067// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002068// ----------------------------------------------------------------------------
2069
Eric Laurent3a4311c2014-03-17 12:00:47 -07002070uint32_t AudioPolicyManager::nextUniqueId()
2071{
2072 return android_atomic_inc(&mNextUniqueId);
2073}
2074
Eric Laurent6a94d692014-05-20 11:18:06 -07002075uint32_t AudioPolicyManager::nextAudioPortGeneration()
2076{
2077 return android_atomic_inc(&mAudioPortGeneration);
2078}
2079
Eric Laurente0720872014-03-11 09:30:41 -07002080AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002081 :
2082#ifdef AUDIO_POLICY_TEST
2083 Thread(false),
2084#endif //AUDIO_POLICY_TEST
2085 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002086 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002087 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2088 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002089 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002090 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2091 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002092{
Eric Laurent6a94d692014-05-20 11:18:06 -07002093 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002094 mpClientInterface = clientInterface;
2095
Eric Laurent3b73df72014-03-11 09:06:29 -07002096 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2097 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002098 }
2099
Eric Laurent3a4311c2014-03-17 12:00:47 -07002100 mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002101 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2102 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2103 ALOGE("could not load audio policy configuration file, setting defaults");
2104 defaultAudioPolicyConfig();
2105 }
2106 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002107 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002108
2109 // must be done after reading the policy
2110 initializeVolumeCurves();
2111
2112 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002113 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2114 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002115 for (size_t i = 0; i < mHwModules.size(); i++) {
2116 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2117 if (mHwModules[i]->mHandle == 0) {
2118 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2119 continue;
2120 }
2121 // open all output streams needed to access attached devices
2122 // except for direct output streams that are only opened when they are actually
2123 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002124 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002125 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2126 {
Eric Laurent951f4552014-05-20 10:48:17 -07002127 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002128
Eric Laurent3a4311c2014-03-17 12:00:47 -07002129 if (outProfile->mSupportedDevices.isEmpty()) {
2130 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2131 continue;
2132 }
2133
2134 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2135 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002136 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
2137 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002138
Eric Laurent951f4552014-05-20 10:48:17 -07002139 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002140 audio_io_handle_t output = mpClientInterface->openOutput(
2141 outProfile->mModule->mHandle,
2142 &outputDesc->mDevice,
2143 &outputDesc->mSamplingRate,
2144 &outputDesc->mFormat,
2145 &outputDesc->mChannelMask,
2146 &outputDesc->mLatency,
2147 outputDesc->mFlags);
2148 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002149 ALOGW("Cannot open output stream for device %08x on hw module %s",
2150 outputDesc->mDevice,
2151 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002152 delete outputDesc;
2153 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002154 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent951f4552014-05-20 10:48:17 -07002155 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002156 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002157 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002158 // give a valid ID to an attached device once confirmed it is reachable
2159 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2160 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002161 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002162 }
2163 }
Eric Laurente552edb2014-03-10 17:42:56 -07002164 if (mPrimaryOutput == 0 &&
2165 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2166 mPrimaryOutput = output;
2167 }
2168 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002169 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002170 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002171 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002172 true);
2173 }
2174 }
2175 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002176 // open input streams needed to access attached devices to validate
2177 // mAvailableInputDevices list
2178 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2179 {
Eric Laurent951f4552014-05-20 10:48:17 -07002180 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002181
Eric Laurent3a4311c2014-03-17 12:00:47 -07002182 if (inProfile->mSupportedDevices.isEmpty()) {
2183 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2184 continue;
2185 }
2186
2187 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2188 if (profileTypes & inputDeviceTypes) {
2189 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(inProfile);
2190
2191 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent951f4552014-05-20 10:48:17 -07002192 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002193 audio_io_handle_t input = mpClientInterface->openInput(
2194 inProfile->mModule->mHandle,
2195 &inputDesc->mDevice,
2196 &inputDesc->mSamplingRate,
2197 &inputDesc->mFormat,
2198 &inputDesc->mChannelMask);
2199
2200 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002201 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent951f4552014-05-20 10:48:17 -07002202 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002203 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002204 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002205 // give a valid ID to an attached device once confirmed it is reachable
2206 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2207 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002208 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002209 }
2210 }
2211 mpClientInterface->closeInput(input);
2212 } else {
2213 ALOGW("Cannot open input stream for device %08x on hw module %s",
2214 inputDesc->mDevice,
2215 mHwModules[i]->mName);
2216 }
2217 delete inputDesc;
2218 }
2219 }
2220 }
2221 // make sure all attached devices have been allocated a unique ID
2222 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2223 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07002224 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002225 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2226 continue;
2227 }
2228 i++;
2229 }
2230 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2231 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07002232 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002233 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2234 continue;
2235 }
2236 i++;
2237 }
2238 // make sure default device is reachable
2239 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07002240 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002241 }
Eric Laurente552edb2014-03-10 17:42:56 -07002242
2243 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2244
2245 updateDevicesAndOutputs();
2246
2247#ifdef AUDIO_POLICY_TEST
2248 if (mPrimaryOutput != 0) {
2249 AudioParameter outputCmd = AudioParameter();
2250 outputCmd.addInt(String8("set_id"), 0);
2251 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2252
2253 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2254 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002255 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2256 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002257 mTestLatencyMs = 0;
2258 mCurOutput = 0;
2259 mDirectOutput = false;
2260 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2261 mTestOutputs[i] = 0;
2262 }
2263
2264 const size_t SIZE = 256;
2265 char buffer[SIZE];
2266 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2267 run(buffer, ANDROID_PRIORITY_AUDIO);
2268 }
2269#endif //AUDIO_POLICY_TEST
2270}
2271
Eric Laurente0720872014-03-11 09:30:41 -07002272AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002273{
2274#ifdef AUDIO_POLICY_TEST
2275 exit();
2276#endif //AUDIO_POLICY_TEST
2277 for (size_t i = 0; i < mOutputs.size(); i++) {
2278 mpClientInterface->closeOutput(mOutputs.keyAt(i));
2279 delete mOutputs.valueAt(i);
2280 }
2281 for (size_t i = 0; i < mInputs.size(); i++) {
2282 mpClientInterface->closeInput(mInputs.keyAt(i));
2283 delete mInputs.valueAt(i);
2284 }
2285 for (size_t i = 0; i < mHwModules.size(); i++) {
2286 delete mHwModules[i];
2287 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002288 mAvailableOutputDevices.clear();
2289 mAvailableInputDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002290}
2291
Eric Laurente0720872014-03-11 09:30:41 -07002292status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002293{
2294 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2295}
2296
2297#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002298bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002299{
2300 ALOGV("entering threadLoop()");
2301 while (!exitPending())
2302 {
2303 String8 command;
2304 int valueInt;
2305 String8 value;
2306
2307 Mutex::Autolock _l(mLock);
2308 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2309
2310 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2311 AudioParameter param = AudioParameter(command);
2312
2313 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2314 valueInt != 0) {
2315 ALOGV("Test command %s received", command.string());
2316 String8 target;
2317 if (param.get(String8("target"), target) != NO_ERROR) {
2318 target = "Manager";
2319 }
2320 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2321 param.remove(String8("test_cmd_policy_output"));
2322 mCurOutput = valueInt;
2323 }
2324 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2325 param.remove(String8("test_cmd_policy_direct"));
2326 if (value == "false") {
2327 mDirectOutput = false;
2328 } else if (value == "true") {
2329 mDirectOutput = true;
2330 }
2331 }
2332 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2333 param.remove(String8("test_cmd_policy_input"));
2334 mTestInput = valueInt;
2335 }
2336
2337 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2338 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002339 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002340 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002341 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002342 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002343 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002344 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002345 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002346 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002347 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002348 if (target == "Manager") {
2349 mTestFormat = format;
2350 } else if (mTestOutputs[mCurOutput] != 0) {
2351 AudioParameter outputParam = AudioParameter();
2352 outputParam.addInt(String8("format"), format);
2353 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2354 }
2355 }
2356 }
2357 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2358 param.remove(String8("test_cmd_policy_channels"));
2359 int channels = 0;
2360
2361 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002362 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002363 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002364 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002365 }
2366 if (channels != 0) {
2367 if (target == "Manager") {
2368 mTestChannels = channels;
2369 } else if (mTestOutputs[mCurOutput] != 0) {
2370 AudioParameter outputParam = AudioParameter();
2371 outputParam.addInt(String8("channels"), channels);
2372 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2373 }
2374 }
2375 }
2376 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2377 param.remove(String8("test_cmd_policy_sampleRate"));
2378 if (valueInt >= 0 && valueInt <= 96000) {
2379 int samplingRate = valueInt;
2380 if (target == "Manager") {
2381 mTestSamplingRate = samplingRate;
2382 } else if (mTestOutputs[mCurOutput] != 0) {
2383 AudioParameter outputParam = AudioParameter();
2384 outputParam.addInt(String8("sampling_rate"), samplingRate);
2385 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2386 }
2387 }
2388 }
2389
2390 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2391 param.remove(String8("test_cmd_policy_reopen"));
2392
2393 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2394 mpClientInterface->closeOutput(mPrimaryOutput);
2395
2396 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2397
2398 delete mOutputs.valueFor(mPrimaryOutput);
2399 mOutputs.removeItem(mPrimaryOutput);
2400
2401 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
2402 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2403 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2404 &outputDesc->mDevice,
2405 &outputDesc->mSamplingRate,
2406 &outputDesc->mFormat,
2407 &outputDesc->mChannelMask,
2408 &outputDesc->mLatency,
2409 outputDesc->mFlags);
2410 if (mPrimaryOutput == 0) {
2411 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2412 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2413 } else {
2414 AudioParameter outputCmd = AudioParameter();
2415 outputCmd.addInt(String8("set_id"), 0);
2416 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2417 addOutput(mPrimaryOutput, outputDesc);
2418 }
2419 }
2420
2421
2422 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2423 }
2424 }
2425 return false;
2426}
2427
Eric Laurente0720872014-03-11 09:30:41 -07002428void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002429{
2430 {
2431 AutoMutex _l(mLock);
2432 requestExit();
2433 mWaitWorkCV.signal();
2434 }
2435 requestExitAndWait();
2436}
2437
Eric Laurente0720872014-03-11 09:30:41 -07002438int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002439{
2440 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2441 if (output == mTestOutputs[i]) return i;
2442 }
2443 return 0;
2444}
2445#endif //AUDIO_POLICY_TEST
2446
2447// ---
2448
Eric Laurent951f4552014-05-20 10:48:17 -07002449void AudioPolicyManager::addOutput(audio_io_handle_t output, AudioOutputDescriptor *outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002450{
Eric Laurent951f4552014-05-20 10:48:17 -07002451 outputDesc->mIoHandle = output;
2452 outputDesc->mId = nextUniqueId();
2453 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002454 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002455}
2456
Eric Laurent951f4552014-05-20 10:48:17 -07002457void AudioPolicyManager::addInput(audio_io_handle_t input, AudioInputDescriptor *inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002458{
Eric Laurent951f4552014-05-20 10:48:17 -07002459 inputDesc->mIoHandle = input;
2460 inputDesc->mId = nextUniqueId();
2461 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002462 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002463}
Eric Laurente552edb2014-03-10 17:42:56 -07002464
Eric Laurent3a4311c2014-03-17 12:00:47 -07002465String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2466{
2467 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2468 return String8("a2dp_sink_address=")+address;
2469 }
2470 return address;
2471}
2472
Eric Laurente0720872014-03-11 09:30:41 -07002473status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002474 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002475 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002476 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002477{
2478 AudioOutputDescriptor *desc;
2479
Eric Laurent3b73df72014-03-11 09:06:29 -07002480 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002481 // first list already open outputs that can be routed to this device
2482 for (size_t i = 0; i < mOutputs.size(); i++) {
2483 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002484 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002485 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2486 outputs.add(mOutputs.keyAt(i));
2487 }
2488 }
2489 // then look for output profiles that can be routed to this device
Eric Laurent951f4552014-05-20 10:48:17 -07002490 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002491 for (size_t i = 0; i < mHwModules.size(); i++)
2492 {
2493 if (mHwModules[i]->mHandle == 0) {
2494 continue;
2495 }
2496 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2497 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002498 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002499 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002500 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2501 }
2502 }
2503 }
2504
2505 if (profiles.isEmpty() && outputs.isEmpty()) {
2506 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2507 return BAD_VALUE;
2508 }
2509
2510 // open outputs for matching profiles if needed. Direct outputs are also opened to
2511 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2512 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent951f4552014-05-20 10:48:17 -07002513 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002514
2515 // nothing to do if one output is already opened for this profile
2516 size_t j;
2517 for (j = 0; j < mOutputs.size(); j++) {
2518 desc = mOutputs.valueAt(j);
2519 if (!desc->isDuplicated() && desc->mProfile == profile) {
2520 break;
2521 }
2522 }
2523 if (j != mOutputs.size()) {
2524 continue;
2525 }
2526
Eric Laurent3a4311c2014-03-17 12:00:47 -07002527 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002528 desc = new AudioOutputDescriptor(profile);
2529 desc->mDevice = device;
2530 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2531 offloadInfo.sample_rate = desc->mSamplingRate;
2532 offloadInfo.format = desc->mFormat;
2533 offloadInfo.channel_mask = desc->mChannelMask;
2534
2535 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2536 &desc->mDevice,
2537 &desc->mSamplingRate,
2538 &desc->mFormat,
2539 &desc->mChannelMask,
2540 &desc->mLatency,
2541 desc->mFlags,
2542 &offloadInfo);
2543 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002544 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002545 if (!address.isEmpty()) {
2546 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002547 }
2548
Eric Laurentd4692962014-05-05 18:13:44 -07002549 // Here is where we step through and resolve any "dynamic" fields
2550 String8 reply;
2551 char *value;
2552 if (profile->mSamplingRates[0] == 0) {
2553 reply = mpClientInterface->getParameters(output,
2554 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2555 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2556 reply.string());
2557 value = strpbrk((char *)reply.string(), "=");
2558 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002559 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002560 }
Eric Laurentd4692962014-05-05 18:13:44 -07002561 }
2562 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2563 reply = mpClientInterface->getParameters(output,
2564 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2565 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2566 reply.string());
2567 value = strpbrk((char *)reply.string(), "=");
2568 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002569 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002570 }
Eric Laurentd4692962014-05-05 18:13:44 -07002571 }
2572 if (profile->mChannelMasks[0] == 0) {
2573 reply = mpClientInterface->getParameters(output,
2574 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2575 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2576 reply.string());
2577 value = strpbrk((char *)reply.string(), "=");
2578 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002579 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002580 }
Eric Laurentd4692962014-05-05 18:13:44 -07002581 }
2582 if (((profile->mSamplingRates[0] == 0) &&
2583 (profile->mSamplingRates.size() < 2)) ||
2584 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2585 (profile->mFormats.size() < 2)) ||
2586 ((profile->mChannelMasks[0] == 0) &&
2587 (profile->mChannelMasks.size() < 2))) {
2588 ALOGW("checkOutputsForDevice() direct output missing param");
2589 mpClientInterface->closeOutput(output);
2590 output = 0;
2591 } else if (profile->mSamplingRates[0] == 0) {
2592 mpClientInterface->closeOutput(output);
2593 desc->mSamplingRate = profile->mSamplingRates[1];
2594 offloadInfo.sample_rate = desc->mSamplingRate;
2595 output = mpClientInterface->openOutput(
2596 profile->mModule->mHandle,
2597 &desc->mDevice,
2598 &desc->mSamplingRate,
2599 &desc->mFormat,
2600 &desc->mChannelMask,
2601 &desc->mLatency,
2602 desc->mFlags,
2603 &offloadInfo);
2604 }
2605
2606 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002607 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002608 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2609 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002610
Eric Laurentd4692962014-05-05 18:13:44 -07002611 // set initial stream volume for device
2612 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002613
Eric Laurentd4692962014-05-05 18:13:44 -07002614 //TODO: configure audio effect output stage here
2615
2616 // open a duplicating output thread for the new output and the primary output
2617 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2618 mPrimaryOutput);
2619 if (duplicatedOutput != 0) {
2620 // add duplicated output descriptor
2621 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
2622 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2623 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2624 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2625 dupOutputDesc->mFormat = desc->mFormat;
2626 dupOutputDesc->mChannelMask = desc->mChannelMask;
2627 dupOutputDesc->mLatency = desc->mLatency;
2628 addOutput(duplicatedOutput, dupOutputDesc);
2629 applyStreamVolumes(duplicatedOutput, device, 0, true);
2630 } else {
2631 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2632 mPrimaryOutput, output);
2633 mpClientInterface->closeOutput(output);
2634 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002635 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002636 output = 0;
2637 }
Eric Laurente552edb2014-03-10 17:42:56 -07002638 }
2639 }
2640 }
2641 if (output == 0) {
2642 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2643 delete desc;
2644 profiles.removeAt(profile_index);
2645 profile_index--;
2646 } else {
2647 outputs.add(output);
2648 ALOGV("checkOutputsForDevice(): adding output %d", output);
2649 }
2650 }
2651
2652 if (profiles.isEmpty()) {
2653 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2654 return BAD_VALUE;
2655 }
Eric Laurentd4692962014-05-05 18:13:44 -07002656 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002657 // check if one opened output is not needed any more after disconnecting one device
2658 for (size_t i = 0; i < mOutputs.size(); i++) {
2659 desc = mOutputs.valueAt(i);
2660 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002661 !(desc->mProfile->mSupportedDevices.types() &
2662 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002663 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2664 outputs.add(mOutputs.keyAt(i));
2665 }
2666 }
Eric Laurentd4692962014-05-05 18:13:44 -07002667 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002668 for (size_t i = 0; i < mHwModules.size(); i++)
2669 {
2670 if (mHwModules[i]->mHandle == 0) {
2671 continue;
2672 }
2673 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2674 {
Eric Laurent951f4552014-05-20 10:48:17 -07002675 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002676 if (profile->mSupportedDevices.types() & device) {
2677 ALOGV("checkOutputsForDevice(): "
2678 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002679 if (profile->mSamplingRates[0] == 0) {
2680 profile->mSamplingRates.clear();
2681 profile->mSamplingRates.add(0);
2682 }
2683 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2684 profile->mFormats.clear();
2685 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2686 }
2687 if (profile->mChannelMasks[0] == 0) {
2688 profile->mChannelMasks.clear();
2689 profile->mChannelMasks.add(0);
2690 }
2691 }
2692 }
2693 }
2694 }
2695 return NO_ERROR;
2696}
2697
Eric Laurentd4692962014-05-05 18:13:44 -07002698status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2699 audio_policy_dev_state_t state,
2700 SortedVector<audio_io_handle_t>& inputs,
2701 const String8 address)
2702{
2703 AudioInputDescriptor *desc;
2704 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2705 // first list already open inputs that can be routed to this device
2706 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2707 desc = mInputs.valueAt(input_index);
2708 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2709 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2710 inputs.add(mInputs.keyAt(input_index));
2711 }
2712 }
2713
2714 // then look for input profiles that can be routed to this device
Eric Laurent951f4552014-05-20 10:48:17 -07002715 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002716 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2717 {
2718 if (mHwModules[module_idx]->mHandle == 0) {
2719 continue;
2720 }
2721 for (size_t profile_index = 0;
2722 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2723 profile_index++)
2724 {
2725 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2726 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2727 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2728 profile_index, module_idx);
2729 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2730 }
2731 }
2732 }
2733
2734 if (profiles.isEmpty() && inputs.isEmpty()) {
2735 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2736 return BAD_VALUE;
2737 }
2738
2739 // open inputs for matching profiles if needed. Direct inputs are also opened to
2740 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2741 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2742
Eric Laurent951f4552014-05-20 10:48:17 -07002743 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002744 // nothing to do if one input is already opened for this profile
2745 size_t input_index;
2746 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2747 desc = mInputs.valueAt(input_index);
2748 if (desc->mProfile == profile) {
2749 break;
2750 }
2751 }
2752 if (input_index != mInputs.size()) {
2753 continue;
2754 }
2755
2756 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2757 desc = new AudioInputDescriptor(profile);
2758 desc->mDevice = device;
2759
2760 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2761 &desc->mDevice,
2762 &desc->mSamplingRate,
2763 &desc->mFormat,
2764 &desc->mChannelMask);
2765
2766 if (input != 0) {
2767 if (!address.isEmpty()) {
2768 mpClientInterface->setParameters(input, addressToParameter(device, address));
2769 }
2770
2771 // Here is where we step through and resolve any "dynamic" fields
2772 String8 reply;
2773 char *value;
2774 if (profile->mSamplingRates[0] == 0) {
2775 reply = mpClientInterface->getParameters(input,
2776 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2777 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2778 reply.string());
2779 value = strpbrk((char *)reply.string(), "=");
2780 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002781 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002782 }
2783 }
2784 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2785 reply = mpClientInterface->getParameters(input,
2786 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2787 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2788 value = strpbrk((char *)reply.string(), "=");
2789 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002790 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002791 }
2792 }
2793 if (profile->mChannelMasks[0] == 0) {
2794 reply = mpClientInterface->getParameters(input,
2795 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2796 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2797 reply.string());
2798 value = strpbrk((char *)reply.string(), "=");
2799 if (value != NULL) {
Eric Laurent951f4552014-05-20 10:48:17 -07002800 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002801 }
2802 }
2803 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2804 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2805 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2806 ALOGW("checkInputsForDevice() direct input missing param");
2807 mpClientInterface->closeInput(input);
2808 input = 0;
2809 }
2810
2811 if (input != 0) {
2812 addInput(input, desc);
2813 }
2814 } // endif input != 0
2815
2816 if (input == 0) {
2817 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2818 delete desc;
2819 profiles.removeAt(profile_index);
2820 profile_index--;
2821 } else {
2822 inputs.add(input);
2823 ALOGV("checkInputsForDevice(): adding input %d", input);
2824 }
2825 } // end scan profiles
2826
2827 if (profiles.isEmpty()) {
2828 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2829 return BAD_VALUE;
2830 }
2831 } else {
2832 // Disconnect
2833 // check if one opened input is not needed any more after disconnecting one device
2834 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2835 desc = mInputs.valueAt(input_index);
2836 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2837 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2838 mInputs.keyAt(input_index));
2839 inputs.add(mInputs.keyAt(input_index));
2840 }
2841 }
2842 // Clear any profiles associated with the disconnected device.
2843 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2844 if (mHwModules[module_index]->mHandle == 0) {
2845 continue;
2846 }
2847 for (size_t profile_index = 0;
2848 profile_index < mHwModules[module_index]->mInputProfiles.size();
2849 profile_index++) {
Eric Laurent951f4552014-05-20 10:48:17 -07002850 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002851 if (profile->mSupportedDevices.types() & device) {
2852 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2853 profile_index, module_index);
2854 if (profile->mSamplingRates[0] == 0) {
2855 profile->mSamplingRates.clear();
2856 profile->mSamplingRates.add(0);
2857 }
2858 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2859 profile->mFormats.clear();
2860 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2861 }
2862 if (profile->mChannelMasks[0] == 0) {
2863 profile->mChannelMasks.clear();
2864 profile->mChannelMasks.add(0);
2865 }
2866 }
2867 }
2868 }
2869 } // end disconnect
2870
2871 return NO_ERROR;
2872}
2873
2874
Eric Laurente0720872014-03-11 09:30:41 -07002875void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002876{
2877 ALOGV("closeOutput(%d)", output);
2878
2879 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2880 if (outputDesc == NULL) {
2881 ALOGW("closeOutput() unknown output %d", output);
2882 return;
2883 }
2884
2885 // look for duplicated outputs connected to the output being removed.
2886 for (size_t i = 0; i < mOutputs.size(); i++) {
2887 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2888 if (dupOutputDesc->isDuplicated() &&
2889 (dupOutputDesc->mOutput1 == outputDesc ||
2890 dupOutputDesc->mOutput2 == outputDesc)) {
2891 AudioOutputDescriptor *outputDesc2;
2892 if (dupOutputDesc->mOutput1 == outputDesc) {
2893 outputDesc2 = dupOutputDesc->mOutput2;
2894 } else {
2895 outputDesc2 = dupOutputDesc->mOutput1;
2896 }
2897 // As all active tracks on duplicated output will be deleted,
2898 // and as they were also referenced on the other output, the reference
2899 // count for their stream type must be adjusted accordingly on
2900 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07002901 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07002902 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07002903 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07002904 }
2905 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2906 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2907
2908 mpClientInterface->closeOutput(duplicatedOutput);
2909 delete mOutputs.valueFor(duplicatedOutput);
2910 mOutputs.removeItem(duplicatedOutput);
2911 }
2912 }
2913
2914 AudioParameter param;
2915 param.add(String8("closing"), String8("true"));
2916 mpClientInterface->setParameters(output, param.toString());
2917
2918 mpClientInterface->closeOutput(output);
2919 delete outputDesc;
2920 mOutputs.removeItem(output);
2921 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002922 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002923}
2924
Eric Laurente0720872014-03-11 09:30:41 -07002925SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07002926 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2927{
2928 SortedVector<audio_io_handle_t> outputs;
2929
2930 ALOGVV("getOutputsForDevice() device %04x", device);
2931 for (size_t i = 0; i < openOutputs.size(); i++) {
2932 ALOGVV("output %d isDuplicated=%d device=%04x",
2933 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2934 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2935 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2936 outputs.add(openOutputs.keyAt(i));
2937 }
2938 }
2939 return outputs;
2940}
2941
Eric Laurente0720872014-03-11 09:30:41 -07002942bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07002943 SortedVector<audio_io_handle_t>& outputs2)
2944{
2945 if (outputs1.size() != outputs2.size()) {
2946 return false;
2947 }
2948 for (size_t i = 0; i < outputs1.size(); i++) {
2949 if (outputs1[i] != outputs2[i]) {
2950 return false;
2951 }
2952 }
2953 return true;
2954}
2955
Eric Laurente0720872014-03-11 09:30:41 -07002956void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07002957{
2958 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2959 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2960 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2961 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2962
2963 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2964 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2965 strategy, srcOutputs[0], dstOutputs[0]);
2966 // mute strategy while moving tracks from one output to another
2967 for (size_t i = 0; i < srcOutputs.size(); i++) {
2968 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2969 if (desc->isStrategyActive(strategy)) {
2970 setStrategyMute(strategy, true, srcOutputs[i]);
2971 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2972 }
2973 }
2974
2975 // Move effects associated to this strategy from previous output to new output
2976 if (strategy == STRATEGY_MEDIA) {
2977 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2978 SortedVector<audio_io_handle_t> moved;
2979 for (size_t i = 0; i < mEffects.size(); i++) {
2980 EffectDescriptor *desc = mEffects.valueAt(i);
2981 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2982 desc->mIo != fxOutput) {
2983 if (moved.indexOf(desc->mIo) < 0) {
2984 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2985 mEffects.keyAt(i), fxOutput);
2986 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2987 fxOutput);
2988 moved.add(desc->mIo);
2989 }
2990 desc->mIo = fxOutput;
2991 }
2992 }
2993 }
2994 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07002995 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2996 if (getStrategy((audio_stream_type_t)i) == strategy) {
2997 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07002998 }
2999 }
3000 }
3001}
3002
Eric Laurente0720872014-03-11 09:30:41 -07003003void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003004{
3005 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3006 checkOutputForStrategy(STRATEGY_PHONE);
3007 checkOutputForStrategy(STRATEGY_SONIFICATION);
3008 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3009 checkOutputForStrategy(STRATEGY_MEDIA);
3010 checkOutputForStrategy(STRATEGY_DTMF);
3011}
3012
Eric Laurente0720872014-03-11 09:30:41 -07003013audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003014{
Eric Laurente552edb2014-03-10 17:42:56 -07003015 for (size_t i = 0; i < mOutputs.size(); i++) {
3016 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
3017 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3018 return mOutputs.keyAt(i);
3019 }
3020 }
3021
3022 return 0;
3023}
3024
Eric Laurente0720872014-03-11 09:30:41 -07003025void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003026{
Eric Laurente552edb2014-03-10 17:42:56 -07003027 audio_io_handle_t a2dpOutput = getA2dpOutput();
3028 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003029 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003030 return;
3031 }
3032
Eric Laurent3a4311c2014-03-17 12:00:47 -07003033 bool isScoConnected =
3034 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003035 // suspend A2DP output if:
3036 // (NOT already suspended) &&
3037 // ((SCO device is connected &&
3038 // (forced usage for communication || for record is SCO))) ||
3039 // (phone state is ringing || in call)
3040 //
3041 // restore A2DP output if:
3042 // (Already suspended) &&
3043 // ((SCO device is NOT connected ||
3044 // (forced usage NOT for communication && NOT for record is SCO))) &&
3045 // (phone state is NOT ringing && NOT in call)
3046 //
3047 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003048 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003049 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3050 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3051 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3052 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003053
3054 mpClientInterface->restoreOutput(a2dpOutput);
3055 mA2dpSuspended = false;
3056 }
3057 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003058 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003059 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3060 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3061 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3062 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003063
3064 mpClientInterface->suspendOutput(a2dpOutput);
3065 mA2dpSuspended = true;
3066 }
3067 }
3068}
3069
Eric Laurent951f4552014-05-20 10:48:17 -07003070audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003071{
3072 audio_devices_t device = AUDIO_DEVICE_NONE;
3073
3074 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003075
3076 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3077 if (index >= 0) {
3078 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3079 if (patchDesc->mUid != mUidCached) {
3080 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3081 outputDesc->device(), outputDesc->mPatchHandle);
3082 return outputDesc->device();
3083 }
3084 }
3085
Eric Laurente552edb2014-03-10 17:42:56 -07003086 // check the following by order of priority to request a routing change if necessary:
3087 // 1: the strategy enforced audible is active on the output:
3088 // use device for strategy enforced audible
3089 // 2: we are in call or the strategy phone is active on the output:
3090 // use device for strategy phone
3091 // 3: the strategy sonification is active on the output:
3092 // use device for strategy sonification
3093 // 4: the strategy "respectful" sonification is active on the output:
3094 // use device for strategy "respectful" sonification
3095 // 5: the strategy media is active on the output:
3096 // use device for strategy media
3097 // 6: the strategy DTMF is active on the output:
3098 // use device for strategy DTMF
3099 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3100 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3101 } else if (isInCall() ||
3102 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3103 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3104 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3105 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3106 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3107 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3108 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3109 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3110 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3111 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3112 }
3113
Eric Laurent951f4552014-05-20 10:48:17 -07003114 ALOGV("getNewOutputDevice() selected device %x", device);
3115 return device;
3116}
3117
3118audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3119{
3120 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003121
3122 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3123 if (index >= 0) {
3124 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3125 if (patchDesc->mUid != mUidCached) {
3126 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3127 inputDesc->mDevice, inputDesc->mPatchHandle);
3128 return inputDesc->mDevice;
3129 }
3130 }
3131
Eric Laurent951f4552014-05-20 10:48:17 -07003132 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3133
3134 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003135 return device;
3136}
3137
Eric Laurente0720872014-03-11 09:30:41 -07003138uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003139 return (uint32_t)getStrategy(stream);
3140}
3141
Eric Laurente0720872014-03-11 09:30:41 -07003142audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003143 // By checking the range of stream before calling getStrategy, we avoid
3144 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3145 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003146 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003147 return AUDIO_DEVICE_NONE;
3148 }
3149 audio_devices_t devices;
3150 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3151 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3152 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3153 for (size_t i = 0; i < outputs.size(); i++) {
3154 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
3155 if (outputDesc->isStrategyActive(strategy)) {
3156 devices = outputDesc->device();
3157 break;
3158 }
Eric Laurente552edb2014-03-10 17:42:56 -07003159 }
3160 return devices;
3161}
3162
Eric Laurente0720872014-03-11 09:30:41 -07003163AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003164 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003165 // stream to strategy mapping
3166 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003167 case AUDIO_STREAM_VOICE_CALL:
3168 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003169 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003170 case AUDIO_STREAM_RING:
3171 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003172 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003173 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003174 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003175 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003176 return STRATEGY_DTMF;
3177 default:
3178 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003179 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003180 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3181 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003182 case AUDIO_STREAM_TTS:
3183 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003184 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003185 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003186 return STRATEGY_ENFORCED_AUDIBLE;
3187 }
3188}
3189
Eric Laurente0720872014-03-11 09:30:41 -07003190void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003191 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003192 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003193 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3194 updateDevicesAndOutputs();
3195 break;
3196 default:
3197 break;
3198 }
3199}
3200
Eric Laurente0720872014-03-11 09:30:41 -07003201audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003202 bool fromCache)
3203{
3204 uint32_t device = AUDIO_DEVICE_NONE;
3205
3206 if (fromCache) {
3207 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3208 strategy, mDeviceForStrategy[strategy]);
3209 return mDeviceForStrategy[strategy];
3210 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003211 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003212 switch (strategy) {
3213
3214 case STRATEGY_SONIFICATION_RESPECTFUL:
3215 if (isInCall()) {
3216 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003217 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003218 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3219 // while media is playing on a remote device, use the the sonification behavior.
3220 // Note that we test this usecase before testing if media is playing because
3221 // the isStreamActive() method only informs about the activity of a stream, not
3222 // if it's for local playback. Note also that we use the same delay between both tests
3223 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003224 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003225 // while media is playing (or has recently played), use the same device
3226 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3227 } else {
3228 // when media is not playing anymore, fall back on the sonification behavior
3229 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3230 }
3231
3232 break;
3233
3234 case STRATEGY_DTMF:
3235 if (!isInCall()) {
3236 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3237 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3238 break;
3239 }
3240 // when in call, DTMF and PHONE strategies follow the same rules
3241 // FALL THROUGH
3242
3243 case STRATEGY_PHONE:
3244 // for phone strategy, we first consider the forced use and then the available devices by order
3245 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003246 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3247 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003248 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003249 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003250 if (device) break;
3251 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003252 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003253 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003254 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003255 if (device) break;
3256 // if SCO device is requested but no SCO device is available, fall back to default case
3257 // FALL THROUGH
3258
3259 default: // FORCE_NONE
3260 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003261 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003262 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003263 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003264 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003265 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003266 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003267 if (device) break;
3268 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003269 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003270 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003271 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003272 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003273 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003274 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003275 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003276 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003277 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003278 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003279 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003280 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003281 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003282 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003283 if (device) break;
3284 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003285 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003286 if (device) break;
Eric Laurent951f4552014-05-20 10:48:17 -07003287 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003288 if (device == AUDIO_DEVICE_NONE) {
3289 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3290 }
3291 break;
3292
Eric Laurent3b73df72014-03-11 09:06:29 -07003293 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003294 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3295 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003296 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003297 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003298 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003299 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003300 if (device) break;
3301 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003302 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003303 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003304 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003305 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003306 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003307 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003308 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003309 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003310 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003311 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003312 if (device) break;
3313 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003314 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003315 if (device) break;
Eric Laurent951f4552014-05-20 10:48:17 -07003316 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003317 if (device == AUDIO_DEVICE_NONE) {
3318 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3319 }
3320 break;
3321 }
3322 break;
3323
3324 case STRATEGY_SONIFICATION:
3325
3326 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3327 // handleIncallSonification().
3328 if (isInCall()) {
3329 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3330 break;
3331 }
3332 // FALL THROUGH
3333
3334 case STRATEGY_ENFORCED_AUDIBLE:
3335 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3336 // except:
3337 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3338 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3339
3340 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003341 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003342 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003343 if (device == AUDIO_DEVICE_NONE) {
3344 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3345 }
3346 }
3347 // The second device used for sonification is the same as the device used by media strategy
3348 // FALL THROUGH
3349
3350 case STRATEGY_MEDIA: {
3351 uint32_t device2 = AUDIO_DEVICE_NONE;
3352 if (strategy != STRATEGY_SONIFICATION) {
3353 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003354 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003355 }
3356 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003357 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003358 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003359 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003360 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003361 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003362 }
3363 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003364 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003365 }
3366 }
3367 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003368 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003369 }
3370 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003371 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003372 }
3373 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003374 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003375 }
3376 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003377 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003378 }
3379 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003380 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003381 }
3382 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3383 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003384 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003385 }
3386 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003387 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003388 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003389 }
3390 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003391 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003392 }
3393
3394 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3395 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3396 device |= device2;
3397 if (device) break;
Eric Laurent951f4552014-05-20 10:48:17 -07003398 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003399 if (device == AUDIO_DEVICE_NONE) {
3400 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3401 }
3402 } break;
3403
3404 default:
3405 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3406 break;
3407 }
3408
3409 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3410 return device;
3411}
3412
Eric Laurente0720872014-03-11 09:30:41 -07003413void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003414{
3415 for (int i = 0; i < NUM_STRATEGIES; i++) {
3416 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3417 }
3418 mPreviousOutputs = mOutputs;
3419}
3420
Eric Laurente0720872014-03-11 09:30:41 -07003421uint32_t AudioPolicyManager::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003422 audio_devices_t prevDevice,
3423 uint32_t delayMs)
3424{
3425 // mute/unmute strategies using an incompatible device combination
3426 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3427 // if unmuting, unmute only after the specified delay
3428 if (outputDesc->isDuplicated()) {
3429 return 0;
3430 }
3431
3432 uint32_t muteWaitMs = 0;
3433 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003434 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003435
3436 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3437 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3438 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3439 bool doMute = false;
3440
3441 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3442 doMute = true;
3443 outputDesc->mStrategyMutedByDevice[i] = true;
3444 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3445 doMute = true;
3446 outputDesc->mStrategyMutedByDevice[i] = false;
3447 }
Eric Laurent99401132014-05-07 19:48:15 -07003448 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003449 for (size_t j = 0; j < mOutputs.size(); j++) {
3450 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
3451 // skip output if it does not share any device with current output
3452 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3453 == AUDIO_DEVICE_NONE) {
3454 continue;
3455 }
3456 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3457 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3458 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3459 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3460 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003461 if (mute) {
3462 // FIXME: should not need to double latency if volume could be applied
3463 // immediately by the audioflinger mixer. We must account for the delay
3464 // between now and the next time the audioflinger thread for this output
3465 // will process a buffer (which corresponds to one buffer size,
3466 // usually 1/2 or 1/4 of the latency).
3467 if (muteWaitMs < desc->latency() * 2) {
3468 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003469 }
3470 }
3471 }
3472 }
3473 }
3474 }
3475
Eric Laurent99401132014-05-07 19:48:15 -07003476 // temporary mute output if device selection changes to avoid volume bursts due to
3477 // different per device volumes
3478 if (outputDesc->isActive() && (device != prevDevice)) {
3479 if (muteWaitMs < outputDesc->latency() * 2) {
3480 muteWaitMs = outputDesc->latency() * 2;
3481 }
3482 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3483 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent951f4552014-05-20 10:48:17 -07003484 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003485 // do tempMute unmute after twice the mute wait time
Eric Laurent951f4552014-05-20 10:48:17 -07003486 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003487 muteWaitMs *2, device);
3488 }
3489 }
3490 }
3491
Eric Laurente552edb2014-03-10 17:42:56 -07003492 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3493 if (muteWaitMs > delayMs) {
3494 muteWaitMs -= delayMs;
3495 usleep(muteWaitMs * 1000);
3496 return muteWaitMs;
3497 }
3498 return 0;
3499}
3500
Eric Laurente0720872014-03-11 09:30:41 -07003501uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003502 audio_devices_t device,
3503 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003504 int delayMs,
3505 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003506{
3507 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
3508 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3509 AudioParameter param;
3510 uint32_t muteWaitMs;
3511
3512 if (outputDesc->isDuplicated()) {
Eric Laurent951f4552014-05-20 10:48:17 -07003513 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3514 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003515 return muteWaitMs;
3516 }
3517 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3518 // output profile
3519 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003520 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003521 return 0;
3522 }
3523
3524 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003525 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003526
3527 audio_devices_t prevDevice = outputDesc->mDevice;
3528
3529 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3530
3531 if (device != AUDIO_DEVICE_NONE) {
3532 outputDesc->mDevice = device;
3533 }
3534 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3535
3536 // Do not change the routing if:
3537 // - the requested device is AUDIO_DEVICE_NONE
3538 // - the requested device is the same as current device and force is not specified.
3539 // Doing this check here allows the caller to call setOutputDevice() without conditions
3540 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3541 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3542 return muteWaitMs;
3543 }
3544
3545 ALOGV("setOutputDevice() changing device");
Eric Laurent951f4552014-05-20 10:48:17 -07003546
Eric Laurente552edb2014-03-10 17:42:56 -07003547 // do the routing
Eric Laurent951f4552014-05-20 10:48:17 -07003548 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003549 resetOutputDevice(output, delayMs, NULL);
Eric Laurent951f4552014-05-20 10:48:17 -07003550 } else {
3551 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3552 if (!deviceList.isEmpty()) {
3553 struct audio_patch patch;
3554 outputDesc->toAudioPortConfig(&patch.sources[0]);
3555 patch.num_sources = 1;
3556 patch.num_sinks = 0;
3557 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3558 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent951f4552014-05-20 10:48:17 -07003559 patch.num_sinks++;
3560 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003561 ssize_t index;
3562 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3563 index = mAudioPatches.indexOfKey(*patchHandle);
3564 } else {
3565 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3566 }
3567 sp< AudioPatch> patchDesc;
3568 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3569 if (index >= 0) {
3570 patchDesc = mAudioPatches.valueAt(index);
3571 afPatchHandle = patchDesc->mAfPatchHandle;
3572 }
3573
Eric Laurent951f4552014-05-20 10:48:17 -07003574 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003575 &afPatchHandle,
3576 delayMs);
Eric Laurent951f4552014-05-20 10:48:17 -07003577 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3578 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003579 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent951f4552014-05-20 10:48:17 -07003580 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003581 if (index < 0) {
3582 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3583 &patch, mUidCached);
3584 addAudioPatch(patchDesc->mHandle, patchDesc);
3585 } else {
3586 patchDesc->mPatch = patch;
3587 }
3588 patchDesc->mAfPatchHandle = afPatchHandle;
3589 patchDesc->mUid = mUidCached;
3590 if (patchHandle) {
3591 *patchHandle = patchDesc->mHandle;
3592 }
3593 outputDesc->mPatchHandle = patchDesc->mHandle;
3594 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003595 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent951f4552014-05-20 10:48:17 -07003596 }
3597 }
3598 }
Eric Laurente552edb2014-03-10 17:42:56 -07003599
3600 // update stream volumes according to new device
3601 applyStreamVolumes(output, device, delayMs);
3602
3603 return muteWaitMs;
3604}
3605
Eric Laurent951f4552014-05-20 10:48:17 -07003606status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003607 int delayMs,
3608 audio_patch_handle_t *patchHandle)
Eric Laurent951f4552014-05-20 10:48:17 -07003609{
3610 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003611 ssize_t index;
3612 if (patchHandle) {
3613 index = mAudioPatches.indexOfKey(*patchHandle);
3614 } else {
3615 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3616 }
3617 if (index < 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07003618 return INVALID_OPERATION;
3619 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003620 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3621 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent951f4552014-05-20 10:48:17 -07003622 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3623 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003624 removeAudioPatch(patchDesc->mHandle);
3625 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003626 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent951f4552014-05-20 10:48:17 -07003627 return status;
3628}
3629
3630status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3631 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003632 bool force,
3633 audio_patch_handle_t *patchHandle)
Eric Laurent951f4552014-05-20 10:48:17 -07003634{
3635 status_t status = NO_ERROR;
3636
3637 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
3638 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3639 inputDesc->mDevice = device;
3640
3641 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3642 if (!deviceList.isEmpty()) {
3643 struct audio_patch patch;
3644 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3645 patch.num_sinks = 1;
3646 //only one input device for now
3647 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent951f4552014-05-20 10:48:17 -07003648 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003649 ssize_t index;
3650 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3651 index = mAudioPatches.indexOfKey(*patchHandle);
3652 } else {
3653 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3654 }
3655 sp< AudioPatch> patchDesc;
3656 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3657 if (index >= 0) {
3658 patchDesc = mAudioPatches.valueAt(index);
3659 afPatchHandle = patchDesc->mAfPatchHandle;
3660 }
3661
Eric Laurent951f4552014-05-20 10:48:17 -07003662 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003663 &afPatchHandle,
Eric Laurent951f4552014-05-20 10:48:17 -07003664 0);
3665 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003666 status, afPatchHandle);
Eric Laurent951f4552014-05-20 10:48:17 -07003667 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003668 if (index < 0) {
3669 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3670 &patch, mUidCached);
3671 addAudioPatch(patchDesc->mHandle, patchDesc);
3672 } else {
3673 patchDesc->mPatch = patch;
3674 }
3675 patchDesc->mAfPatchHandle = afPatchHandle;
3676 patchDesc->mUid = mUidCached;
3677 if (patchHandle) {
3678 *patchHandle = patchDesc->mHandle;
3679 }
3680 inputDesc->mPatchHandle = patchDesc->mHandle;
3681 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003682 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent951f4552014-05-20 10:48:17 -07003683 }
3684 }
3685 }
3686 return status;
3687}
3688
Eric Laurent6a94d692014-05-20 11:18:06 -07003689status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3690 audio_patch_handle_t *patchHandle)
Eric Laurent951f4552014-05-20 10:48:17 -07003691{
3692 AudioInputDescriptor *inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003693 ssize_t index;
3694 if (patchHandle) {
3695 index = mAudioPatches.indexOfKey(*patchHandle);
3696 } else {
3697 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3698 }
3699 if (index < 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07003700 return INVALID_OPERATION;
3701 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003702 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3703 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent951f4552014-05-20 10:48:17 -07003704 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3705 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003706 removeAudioPatch(patchDesc->mHandle);
3707 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003708 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent951f4552014-05-20 10:48:17 -07003709 return status;
3710}
3711
3712sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003713 uint32_t samplingRate,
3714 audio_format_t format,
3715 audio_channel_mask_t channelMask)
3716{
3717 // Choose an input profile based on the requested capture parameters: select the first available
3718 // profile supporting all requested parameters.
3719
3720 for (size_t i = 0; i < mHwModules.size(); i++)
3721 {
3722 if (mHwModules[i]->mHandle == 0) {
3723 continue;
3724 }
3725 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3726 {
Eric Laurent951f4552014-05-20 10:48:17 -07003727 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003728 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003729 if (profile->isCompatibleProfile(device, samplingRate, format,
3730 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3731 return profile;
3732 }
3733 }
3734 }
3735 return NULL;
3736}
3737
Eric Laurente0720872014-03-11 09:30:41 -07003738audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003739{
3740 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003741 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3742 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003743 switch (inputSource) {
3744 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003745 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003746 device = AUDIO_DEVICE_IN_VOICE_CALL;
3747 break;
3748 }
3749 // FALL THROUGH
3750
3751 case AUDIO_SOURCE_DEFAULT:
3752 case AUDIO_SOURCE_MIC:
3753 case AUDIO_SOURCE_VOICE_RECOGNITION:
3754 case AUDIO_SOURCE_HOTWORD:
3755 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003756 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003757 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003758 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003759 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003760 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003761 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3762 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003763 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003764 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3765 }
3766 break;
3767 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003768 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003769 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003770 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003771 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3772 }
3773 break;
3774 case AUDIO_SOURCE_VOICE_DOWNLINK:
3775 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003776 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003777 device = AUDIO_DEVICE_IN_VOICE_CALL;
3778 }
3779 break;
3780 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003781 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003782 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3783 }
3784 break;
3785 default:
3786 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3787 break;
3788 }
3789 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3790 return device;
3791}
3792
Eric Laurente0720872014-03-11 09:30:41 -07003793bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003794{
3795 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3796 device &= ~AUDIO_DEVICE_BIT_IN;
3797 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3798 return true;
3799 }
3800 return false;
3801}
3802
Eric Laurente0720872014-03-11 09:30:41 -07003803audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003804{
3805 for (size_t i = 0; i < mInputs.size(); i++) {
3806 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
3807 if ((input_descriptor->mRefCount > 0)
3808 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3809 return mInputs.keyAt(i);
3810 }
3811 }
3812 return 0;
3813}
3814
3815
Eric Laurente0720872014-03-11 09:30:41 -07003816audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003817{
3818 if (device == AUDIO_DEVICE_NONE) {
3819 // this happens when forcing a route update and no track is active on an output.
3820 // In this case the returned category is not important.
3821 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003822 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003823 // Multiple device selection is either:
3824 // - speaker + one other device: give priority to speaker in this case.
3825 // - one A2DP device + another device: happens with duplicated output. In this case
3826 // retain the device on the A2DP output as the other must not correspond to an active
3827 // selection if not the speaker.
3828 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3829 device = AUDIO_DEVICE_OUT_SPEAKER;
3830 } else {
3831 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3832 }
3833 }
3834
Eric Laurent3b73df72014-03-11 09:06:29 -07003835 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003836 "getDeviceForVolume() invalid device combination: %08x",
3837 device);
3838
3839 return device;
3840}
3841
Eric Laurente0720872014-03-11 09:30:41 -07003842AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003843{
3844 switch(getDeviceForVolume(device)) {
3845 case AUDIO_DEVICE_OUT_EARPIECE:
3846 return DEVICE_CATEGORY_EARPIECE;
3847 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3848 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3849 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3850 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3851 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3852 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3853 return DEVICE_CATEGORY_HEADSET;
3854 case AUDIO_DEVICE_OUT_SPEAKER:
3855 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3856 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3857 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3858 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3859 case AUDIO_DEVICE_OUT_USB_DEVICE:
3860 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3861 default:
3862 return DEVICE_CATEGORY_SPEAKER;
3863 }
3864}
3865
Eric Laurente0720872014-03-11 09:30:41 -07003866float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003867 int indexInUi)
3868{
3869 device_category deviceCategory = getDeviceCategory(device);
3870 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3871
3872 // the volume index in the UI is relative to the min and max volume indices for this stream type
3873 int nbSteps = 1 + curve[VOLMAX].mIndex -
3874 curve[VOLMIN].mIndex;
3875 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3876 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3877
3878 // find what part of the curve this index volume belongs to, or if it's out of bounds
3879 int segment = 0;
3880 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3881 return 0.0f;
3882 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3883 segment = 0;
3884 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3885 segment = 1;
3886 } else if (volIdx <= curve[VOLMAX].mIndex) {
3887 segment = 2;
3888 } else { // out of bounds
3889 return 1.0f;
3890 }
3891
3892 // linear interpolation in the attenuation table in dB
3893 float decibels = curve[segment].mDBAttenuation +
3894 ((float)(volIdx - curve[segment].mIndex)) *
3895 ( (curve[segment+1].mDBAttenuation -
3896 curve[segment].mDBAttenuation) /
3897 ((float)(curve[segment+1].mIndex -
3898 curve[segment].mIndex)) );
3899
3900 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3901
3902 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3903 curve[segment].mIndex, volIdx,
3904 curve[segment+1].mIndex,
3905 curve[segment].mDBAttenuation,
3906 decibels,
3907 curve[segment+1].mDBAttenuation,
3908 amplification);
3909
3910 return amplification;
3911}
3912
Eric Laurente0720872014-03-11 09:30:41 -07003913const AudioPolicyManager::VolumeCurvePoint
3914 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003915 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3916};
3917
Eric Laurente0720872014-03-11 09:30:41 -07003918const AudioPolicyManager::VolumeCurvePoint
3919 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003920 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3921};
3922
Eric Laurente0720872014-03-11 09:30:41 -07003923const AudioPolicyManager::VolumeCurvePoint
3924 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003925 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3926};
3927
Eric Laurente0720872014-03-11 09:30:41 -07003928const AudioPolicyManager::VolumeCurvePoint
3929 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003930 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3931};
3932
Eric Laurente0720872014-03-11 09:30:41 -07003933const AudioPolicyManager::VolumeCurvePoint
3934 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003935 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3936};
3937
3938// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3939// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3940// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3941// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3942
Eric Laurente0720872014-03-11 09:30:41 -07003943const AudioPolicyManager::VolumeCurvePoint
3944 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003945 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3946};
3947
Eric Laurente0720872014-03-11 09:30:41 -07003948const AudioPolicyManager::VolumeCurvePoint
3949 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003950 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3951};
3952
Eric Laurente0720872014-03-11 09:30:41 -07003953const AudioPolicyManager::VolumeCurvePoint
3954 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003955 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3956};
3957
Eric Laurente0720872014-03-11 09:30:41 -07003958const AudioPolicyManager::VolumeCurvePoint
3959 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003960 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3961};
3962
Eric Laurente0720872014-03-11 09:30:41 -07003963const AudioPolicyManager::VolumeCurvePoint
3964 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003965 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3966};
3967
Eric Laurente0720872014-03-11 09:30:41 -07003968const AudioPolicyManager::VolumeCurvePoint
3969 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
3970 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003971 { // AUDIO_STREAM_VOICE_CALL
3972 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3973 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3974 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3975 },
3976 { // AUDIO_STREAM_SYSTEM
3977 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3978 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3979 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3980 },
3981 { // AUDIO_STREAM_RING
3982 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3983 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3984 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3985 },
3986 { // AUDIO_STREAM_MUSIC
3987 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3988 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3989 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3990 },
3991 { // AUDIO_STREAM_ALARM
3992 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3993 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3994 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3995 },
3996 { // AUDIO_STREAM_NOTIFICATION
3997 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3998 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3999 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4000 },
4001 { // AUDIO_STREAM_BLUETOOTH_SCO
4002 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4003 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4004 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4005 },
4006 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4007 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4008 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4009 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4010 },
4011 { // AUDIO_STREAM_DTMF
4012 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4013 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4014 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4015 },
4016 { // AUDIO_STREAM_TTS
4017 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4018 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4019 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4020 },
4021};
4022
Eric Laurente0720872014-03-11 09:30:41 -07004023void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004024{
4025 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4026 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4027 mStreams[i].mVolumeCurve[j] =
4028 sVolumeProfiles[i][j];
4029 }
4030 }
4031
4032 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4033 if (mSpeakerDrcEnabled) {
4034 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4035 sDefaultSystemVolumeCurveDrc;
4036 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4037 sSpeakerSonificationVolumeCurveDrc;
4038 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4039 sSpeakerSonificationVolumeCurveDrc;
4040 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4041 sSpeakerSonificationVolumeCurveDrc;
4042 }
4043}
4044
Eric Laurente0720872014-03-11 09:30:41 -07004045float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004046 int index,
4047 audio_io_handle_t output,
4048 audio_devices_t device)
4049{
4050 float volume = 1.0;
4051 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
4052 StreamDescriptor &streamDesc = mStreams[stream];
4053
4054 if (device == AUDIO_DEVICE_NONE) {
4055 device = outputDesc->device();
4056 }
4057
4058 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004059 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004060 index != mStreams[stream].mIndexMin &&
4061 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
4062 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
4063 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
4064 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
4065 return 1.0;
4066 }
4067
4068 volume = volIndexToAmpl(device, streamDesc, index);
4069
4070 // if a headset is connected, apply the following rules to ring tones and notifications
4071 // to avoid sound level bursts in user's ears:
4072 // - always attenuate ring tones and notifications volume by 6dB
4073 // - if music is playing, always limit the volume to current music volume,
4074 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004075 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004076 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4077 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4078 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4079 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4080 ((stream_strategy == STRATEGY_SONIFICATION)
4081 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004082 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004083 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004084 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004085 streamDesc.mCanBeMuted) {
4086 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4087 // when the phone is ringing we must consider that music could have been paused just before
4088 // by the music application and behave as if music was active if the last music track was
4089 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004090 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004091 mLimitRingtoneVolume) {
4092 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004093 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4094 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004095 output,
4096 musicDevice);
4097 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4098 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4099 if (volume > minVol) {
4100 volume = minVol;
4101 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4102 }
4103 }
4104 }
4105
4106 return volume;
4107}
4108
Eric Laurente0720872014-03-11 09:30:41 -07004109status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004110 int index,
4111 audio_io_handle_t output,
4112 audio_devices_t device,
4113 int delayMs,
4114 bool force)
4115{
4116
4117 // do not change actual stream volume if the stream is muted
4118 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4119 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4120 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4121 return NO_ERROR;
4122 }
4123
4124 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004125 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4126 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4127 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4128 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004129 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004130 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004131 return INVALID_OPERATION;
4132 }
4133
4134 float volume = computeVolume(stream, index, output, device);
4135 // We actually change the volume if:
4136 // - the float value returned by computeVolume() changed
4137 // - the force flag is set
4138 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4139 force) {
4140 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4141 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4142 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4143 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004144 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4145 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004146 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004147 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004148 }
4149
Eric Laurent3b73df72014-03-11 09:06:29 -07004150 if (stream == AUDIO_STREAM_VOICE_CALL ||
4151 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004152 float voiceVolume;
4153 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004154 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004155 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4156 } else {
4157 voiceVolume = 1.0;
4158 }
4159
4160 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4161 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4162 mLastVoiceVolume = voiceVolume;
4163 }
4164 }
4165
4166 return NO_ERROR;
4167}
4168
Eric Laurente0720872014-03-11 09:30:41 -07004169void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004170 audio_devices_t device,
4171 int delayMs,
4172 bool force)
4173{
4174 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4175
Eric Laurent3b73df72014-03-11 09:06:29 -07004176 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4177 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004178 mStreams[stream].getVolumeIndex(device),
4179 output,
4180 device,
4181 delayMs,
4182 force);
4183 }
4184}
4185
Eric Laurente0720872014-03-11 09:30:41 -07004186void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004187 bool on,
4188 audio_io_handle_t output,
4189 int delayMs,
4190 audio_devices_t device)
4191{
4192 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004193 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4194 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4195 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004196 }
4197 }
4198}
4199
Eric Laurente0720872014-03-11 09:30:41 -07004200void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004201 bool on,
4202 audio_io_handle_t output,
4203 int delayMs,
4204 audio_devices_t device)
4205{
4206 StreamDescriptor &streamDesc = mStreams[stream];
4207 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
4208 if (device == AUDIO_DEVICE_NONE) {
4209 device = outputDesc->device();
4210 }
4211
4212 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4213 stream, on, output, outputDesc->mMuteCount[stream], device);
4214
4215 if (on) {
4216 if (outputDesc->mMuteCount[stream] == 0) {
4217 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004218 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4219 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004220 checkAndSetVolume(stream, 0, output, device, delayMs);
4221 }
4222 }
4223 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4224 outputDesc->mMuteCount[stream]++;
4225 } else {
4226 if (outputDesc->mMuteCount[stream] == 0) {
4227 ALOGV("setStreamMute() unmuting non muted stream!");
4228 return;
4229 }
4230 if (--outputDesc->mMuteCount[stream] == 0) {
4231 checkAndSetVolume(stream,
4232 streamDesc.getVolumeIndex(device),
4233 output,
4234 device,
4235 delayMs);
4236 }
4237 }
4238}
4239
Eric Laurente0720872014-03-11 09:30:41 -07004240void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004241 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004242{
4243 // if the stream pertains to sonification strategy and we are in call we must
4244 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4245 // in the device used for phone strategy and play the tone if the selected device does not
4246 // interfere with the device used for phone strategy
4247 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4248 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004249 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004250 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4251 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
4252 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
4253 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4254 stream, starting, outputDesc->mDevice, stateChange);
4255 if (outputDesc->mRefCount[stream]) {
4256 int muteCount = 1;
4257 if (stateChange) {
4258 muteCount = outputDesc->mRefCount[stream];
4259 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004260 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004261 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4262 for (int i = 0; i < muteCount; i++) {
4263 setStreamMute(stream, starting, mPrimaryOutput);
4264 }
4265 } else {
4266 ALOGV("handleIncallSonification() high visibility");
4267 if (outputDesc->device() &
4268 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4269 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4270 for (int i = 0; i < muteCount; i++) {
4271 setStreamMute(stream, starting, mPrimaryOutput);
4272 }
4273 }
4274 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004275 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4276 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004277 } else {
4278 mpClientInterface->stopTone();
4279 }
4280 }
4281 }
4282 }
4283}
4284
Eric Laurente0720872014-03-11 09:30:41 -07004285bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004286{
4287 return isStateInCall(mPhoneState);
4288}
4289
Eric Laurente0720872014-03-11 09:30:41 -07004290bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004291 return ((state == AUDIO_MODE_IN_CALL) ||
4292 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004293}
4294
Eric Laurente0720872014-03-11 09:30:41 -07004295uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004296{
4297 return MAX_EFFECTS_CPU_LOAD;
4298}
4299
Eric Laurente0720872014-03-11 09:30:41 -07004300uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004301{
4302 return MAX_EFFECTS_MEMORY;
4303}
4304
Eric Laurent6a94d692014-05-20 11:18:06 -07004305
Eric Laurente552edb2014-03-10 17:42:56 -07004306// --- AudioOutputDescriptor class implementation
4307
Eric Laurente0720872014-03-11 09:30:41 -07004308AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent951f4552014-05-20 10:48:17 -07004309 const sp<IOProfile>& profile)
4310 : mId(0), mIoHandle(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
Eric Laurente552edb2014-03-10 17:42:56 -07004311 mChannelMask(0), mLatency(0),
Eric Laurent951f4552014-05-20 10:48:17 -07004312 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004313 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4314{
4315 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004316 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004317 mRefCount[i] = 0;
4318 mCurVolume[i] = -1.0;
4319 mMuteCount[i] = 0;
4320 mStopTime[i] = 0;
4321 }
4322 for (int i = 0; i < NUM_STRATEGIES; i++) {
4323 mStrategyMutedByDevice[i] = false;
4324 }
4325 if (profile != NULL) {
4326 mSamplingRate = profile->mSamplingRates[0];
4327 mFormat = profile->mFormats[0];
4328 mChannelMask = profile->mChannelMasks[0];
4329 mFlags = profile->mFlags;
4330 }
4331}
4332
Eric Laurente0720872014-03-11 09:30:41 -07004333audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004334{
4335 if (isDuplicated()) {
4336 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4337 } else {
4338 return mDevice;
4339 }
4340}
4341
Eric Laurente0720872014-03-11 09:30:41 -07004342uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004343{
4344 if (isDuplicated()) {
4345 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4346 } else {
4347 return mLatency;
4348 }
4349}
4350
Eric Laurente0720872014-03-11 09:30:41 -07004351bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurente552edb2014-03-10 17:42:56 -07004352 const AudioOutputDescriptor *outputDesc)
4353{
4354 if (isDuplicated()) {
4355 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4356 } else if (outputDesc->isDuplicated()){
4357 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4358 } else {
4359 return (mProfile->mModule == outputDesc->mProfile->mModule);
4360 }
4361}
4362
Eric Laurente0720872014-03-11 09:30:41 -07004363void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004364 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004365{
4366 // forward usage count change to attached outputs
4367 if (isDuplicated()) {
4368 mOutput1->changeRefCount(stream, delta);
4369 mOutput2->changeRefCount(stream, delta);
4370 }
4371 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004372 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4373 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004374 mRefCount[stream] = 0;
4375 return;
4376 }
4377 mRefCount[stream] += delta;
4378 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4379}
4380
Eric Laurente0720872014-03-11 09:30:41 -07004381audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004382{
4383 if (isDuplicated()) {
4384 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4385 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004386 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004387 }
4388}
4389
Eric Laurente0720872014-03-11 09:30:41 -07004390bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004391{
4392 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4393}
4394
Eric Laurente0720872014-03-11 09:30:41 -07004395bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004396 uint32_t inPastMs,
4397 nsecs_t sysTime) const
4398{
4399 if ((sysTime == 0) && (inPastMs != 0)) {
4400 sysTime = systemTime();
4401 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004402 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4403 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004404 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004405 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004406 return true;
4407 }
4408 }
4409 return false;
4410}
4411
Eric Laurente0720872014-03-11 09:30:41 -07004412bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004413 uint32_t inPastMs,
4414 nsecs_t sysTime) const
4415{
4416 if (mRefCount[stream] != 0) {
4417 return true;
4418 }
4419 if (inPastMs == 0) {
4420 return false;
4421 }
4422 if (sysTime == 0) {
4423 sysTime = systemTime();
4424 }
4425 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4426 return true;
4427 }
4428 return false;
4429}
4430
Eric Laurent951f4552014-05-20 10:48:17 -07004431void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004432 struct audio_port_config *dstConfig,
4433 const struct audio_port_config *srcConfig) const
Eric Laurent951f4552014-05-20 10:48:17 -07004434{
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 dstConfig->id = mId;
4436 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4437 dstConfig->type = AUDIO_PORT_TYPE_MIX;
4438 dstConfig->sample_rate = mSamplingRate;
4439 dstConfig->channel_mask = mChannelMask;
4440 dstConfig->format = mFormat;
4441 dstConfig->gain.index = -1;
4442 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
Eric Laurent951f4552014-05-20 10:48:17 -07004443 AUDIO_PORT_CONFIG_FORMAT;
Eric Laurent6a94d692014-05-20 11:18:06 -07004444 // use supplied variable configuration parameters if any
4445 if (srcConfig != NULL) {
4446 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
4447 dstConfig->sample_rate = srcConfig->sample_rate;
4448 }
4449 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
4450 dstConfig->channel_mask = srcConfig->channel_mask;
4451 }
4452 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
4453 dstConfig->format = srcConfig->format;
4454 }
4455 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
4456 dstConfig->gain = srcConfig->gain;
4457 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
4458 }
4459 }
4460 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4461 dstConfig->ext.mix.handle = mIoHandle;
4462 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent951f4552014-05-20 10:48:17 -07004463}
4464
4465void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4466 struct audio_port *port) const
4467{
4468 mProfile->toAudioPort(port);
4469 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 toAudioPortConfig(&port->active_config);
4471 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent951f4552014-05-20 10:48:17 -07004472 port->ext.mix.handle = mIoHandle;
4473 port->ext.mix.latency_class =
4474 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4475}
Eric Laurente552edb2014-03-10 17:42:56 -07004476
Eric Laurente0720872014-03-11 09:30:41 -07004477status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004478{
4479 const size_t SIZE = 256;
4480 char buffer[SIZE];
4481 String8 result;
4482
4483 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4484 result.append(buffer);
4485 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4486 result.append(buffer);
4487 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4488 result.append(buffer);
4489 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4490 result.append(buffer);
4491 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4492 result.append(buffer);
4493 snprintf(buffer, SIZE, " Devices %08x\n", device());
4494 result.append(buffer);
4495 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4496 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004497 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4498 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4499 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004500 result.append(buffer);
4501 }
4502 write(fd, result.string(), result.size());
4503
4504 return NO_ERROR;
4505}
4506
4507// --- AudioInputDescriptor class implementation
4508
Eric Laurent951f4552014-05-20 10:48:17 -07004509AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
4510 : mId(0), mIoHandle(0), mSamplingRate(0),
4511 mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
4512 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004513 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004514{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004515 if (profile != NULL) {
4516 mSamplingRate = profile->mSamplingRates[0];
4517 mFormat = profile->mFormats[0];
4518 mChannelMask = profile->mChannelMasks[0];
4519 }
Eric Laurente552edb2014-03-10 17:42:56 -07004520}
4521
Eric Laurent951f4552014-05-20 10:48:17 -07004522void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004523 struct audio_port_config *dstConfig,
4524 const struct audio_port_config *srcConfig) const
Eric Laurent951f4552014-05-20 10:48:17 -07004525{
Eric Laurent6a94d692014-05-20 11:18:06 -07004526 dstConfig->id = mId;
4527 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4528 dstConfig->type = AUDIO_PORT_TYPE_MIX;
4529 dstConfig->sample_rate = mSamplingRate;
4530 dstConfig->channel_mask = mChannelMask;
4531 dstConfig->format = mFormat;
4532 dstConfig->gain.index = -1;
4533 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4534 AUDIO_PORT_CONFIG_FORMAT;
4535 // use supplied variable configuration parameters if any
4536 if (srcConfig != NULL) {
4537 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
4538 dstConfig->sample_rate = srcConfig->sample_rate;
4539 }
4540 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
4541 dstConfig->channel_mask = srcConfig->channel_mask;
4542 }
4543 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
4544 dstConfig->format = srcConfig->format;
4545 }
4546 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
4547 dstConfig->gain = srcConfig->gain;
4548 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
4549 }
4550 }
Eric Laurent951f4552014-05-20 10:48:17 -07004551}
4552
4553void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4554 struct audio_port *port) const
4555{
4556 mProfile->toAudioPort(port);
4557 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004558 toAudioPortConfig(&port->active_config);
4559 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent951f4552014-05-20 10:48:17 -07004560 port->ext.mix.handle = mIoHandle;
4561 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4562}
4563
Eric Laurente0720872014-03-11 09:30:41 -07004564status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004565{
4566 const size_t SIZE = 256;
4567 char buffer[SIZE];
4568 String8 result;
4569
4570 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4571 result.append(buffer);
4572 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4573 result.append(buffer);
4574 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4575 result.append(buffer);
4576 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4577 result.append(buffer);
4578 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4579 result.append(buffer);
4580 write(fd, result.string(), result.size());
4581
4582 return NO_ERROR;
4583}
4584
4585// --- StreamDescriptor class implementation
4586
Eric Laurente0720872014-03-11 09:30:41 -07004587AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004588 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4589{
4590 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4591}
4592
Eric Laurente0720872014-03-11 09:30:41 -07004593int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004594{
Eric Laurente0720872014-03-11 09:30:41 -07004595 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004596 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4597 if (mIndexCur.indexOfKey(device) < 0) {
4598 device = AUDIO_DEVICE_OUT_DEFAULT;
4599 }
4600 return mIndexCur.valueFor(device);
4601}
4602
Eric Laurente0720872014-03-11 09:30:41 -07004603void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004604{
4605 const size_t SIZE = 256;
4606 char buffer[SIZE];
4607 String8 result;
4608
4609 snprintf(buffer, SIZE, "%s %02d %02d ",
4610 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4611 result.append(buffer);
4612 for (size_t i = 0; i < mIndexCur.size(); i++) {
4613 snprintf(buffer, SIZE, "%04x : %02d, ",
4614 mIndexCur.keyAt(i),
4615 mIndexCur.valueAt(i));
4616 result.append(buffer);
4617 }
4618 result.append("\n");
4619
4620 write(fd, result.string(), result.size());
4621}
4622
4623// --- EffectDescriptor class implementation
4624
Eric Laurente0720872014-03-11 09:30:41 -07004625status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004626{
4627 const size_t SIZE = 256;
4628 char buffer[SIZE];
4629 String8 result;
4630
4631 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4632 result.append(buffer);
4633 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4634 result.append(buffer);
4635 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4636 result.append(buffer);
4637 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4638 result.append(buffer);
4639 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4640 result.append(buffer);
4641 write(fd, result.string(), result.size());
4642
4643 return NO_ERROR;
4644}
4645
Eric Laurent951f4552014-05-20 10:48:17 -07004646// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004647
Eric Laurente0720872014-03-11 09:30:41 -07004648AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07004649 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
4650{
4651}
4652
Eric Laurente0720872014-03-11 09:30:41 -07004653AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004654{
4655 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004656 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004657 }
4658 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004659 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004660 }
4661 free((void *)mName);
4662}
4663
Eric Laurente0720872014-03-11 09:30:41 -07004664void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004665{
4666 const size_t SIZE = 256;
4667 char buffer[SIZE];
4668 String8 result;
4669
4670 snprintf(buffer, SIZE, " - name: %s\n", mName);
4671 result.append(buffer);
4672 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4673 result.append(buffer);
4674 write(fd, result.string(), result.size());
4675 if (mOutputProfiles.size()) {
4676 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4677 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004678 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004679 write(fd, buffer, strlen(buffer));
4680 mOutputProfiles[i]->dump(fd);
4681 }
4682 }
4683 if (mInputProfiles.size()) {
4684 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4685 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004686 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004687 write(fd, buffer, strlen(buffer));
4688 mInputProfiles[i]->dump(fd);
4689 }
4690 }
4691}
4692
Eric Laurent951f4552014-05-20 10:48:17 -07004693// --- AudioPort class implementation
4694
4695void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
4696{
4697 port->role = mRole;
4698 port->type = mType;
4699 unsigned int i;
4700 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
4701 port->sample_rates[i] = mSamplingRates[i];
4702 }
4703 port->num_sample_rates = i;
4704 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
4705 port->channel_masks[i] = mChannelMasks[i];
4706 }
4707 port->num_channel_masks = i;
4708 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
4709 port->formats[i] = mFormats[i];
4710 }
4711 port->num_formats = i;
4712 port->num_gains = 0;
4713}
4714
4715
4716void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
4717{
4718 char *str = strtok(name, "|");
4719
4720 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4721 // rates should be read from the output stream after it is opened for the first time
4722 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4723 mSamplingRates.add(0);
4724 return;
4725 }
4726
4727 while (str != NULL) {
4728 uint32_t rate = atoi(str);
4729 if (rate != 0) {
4730 ALOGV("loadSamplingRates() adding rate %d", rate);
4731 mSamplingRates.add(rate);
4732 }
4733 str = strtok(NULL, "|");
4734 }
4735 return;
4736}
4737
4738void AudioPolicyManager::AudioPort::loadFormats(char *name)
4739{
4740 char *str = strtok(name, "|");
4741
4742 // by convention, "0' in the first entry in mFormats indicates the supported formats
4743 // should be read from the output stream after it is opened for the first time
4744 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4745 mFormats.add(AUDIO_FORMAT_DEFAULT);
4746 return;
4747 }
4748
4749 while (str != NULL) {
4750 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4751 ARRAY_SIZE(sFormatNameToEnumTable),
4752 str);
4753 if (format != AUDIO_FORMAT_DEFAULT) {
4754 mFormats.add(format);
4755 }
4756 str = strtok(NULL, "|");
4757 }
4758 return;
4759}
4760
4761void AudioPolicyManager::AudioPort::loadInChannels(char *name)
4762{
4763 const char *str = strtok(name, "|");
4764
4765 ALOGV("loadInChannels() %s", name);
4766
4767 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4768 mChannelMasks.add(0);
4769 return;
4770 }
4771
4772 while (str != NULL) {
4773 audio_channel_mask_t channelMask =
4774 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4775 ARRAY_SIZE(sInChannelsNameToEnumTable),
4776 str);
4777 if (channelMask != 0) {
4778 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4779 mChannelMasks.add(channelMask);
4780 }
4781 str = strtok(NULL, "|");
4782 }
4783 return;
4784}
4785
4786void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
4787{
4788 const char *str = strtok(name, "|");
4789
4790 ALOGV("loadOutChannels() %s", name);
4791
4792 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4793 // masks should be read from the output stream after it is opened for the first time
4794 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4795 mChannelMasks.add(0);
4796 return;
4797 }
4798
4799 while (str != NULL) {
4800 audio_channel_mask_t channelMask =
4801 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4802 ARRAY_SIZE(sOutChannelsNameToEnumTable),
4803 str);
4804 if (channelMask != 0) {
4805 mChannelMasks.add(channelMask);
4806 }
4807 str = strtok(NULL, "|");
4808 }
4809 return;
4810}
4811
4812// --- IOProfile class implementation
4813
4814AudioPolicyManager::IOProfile::IOProfile(audio_port_role_t role, HwModule *module)
4815 : AudioPort(AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07004816{
4817}
4818
Eric Laurente0720872014-03-11 09:30:41 -07004819AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07004820{
4821}
4822
4823// checks if the IO profile is compatible with specified parameters.
4824// Sampling rate, format and channel mask must be specified in order to
4825// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07004826bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07004827 uint32_t samplingRate,
4828 audio_format_t format,
4829 audio_channel_mask_t channelMask,
4830 audio_output_flags_t flags) const
4831{
4832 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
4833 return false;
4834 }
4835
Eric Laurent3a4311c2014-03-17 12:00:47 -07004836 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07004837 return false;
4838 }
4839 if ((mFlags & flags) != flags) {
4840 return false;
4841 }
4842 size_t i;
4843 for (i = 0; i < mSamplingRates.size(); i++)
4844 {
4845 if (mSamplingRates[i] == samplingRate) {
4846 break;
4847 }
4848 }
4849 if (i == mSamplingRates.size()) {
4850 return false;
4851 }
4852 for (i = 0; i < mFormats.size(); i++)
4853 {
4854 if (mFormats[i] == format) {
4855 break;
4856 }
4857 }
4858 if (i == mFormats.size()) {
4859 return false;
4860 }
4861 for (i = 0; i < mChannelMasks.size(); i++)
4862 {
4863 if (mChannelMasks[i] == channelMask) {
4864 break;
4865 }
4866 }
4867 if (i == mChannelMasks.size()) {
4868 return false;
4869 }
4870 return true;
4871}
4872
Eric Laurente0720872014-03-11 09:30:41 -07004873void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004874{
4875 const size_t SIZE = 256;
4876 char buffer[SIZE];
4877 String8 result;
4878
4879 snprintf(buffer, SIZE, " - sampling rates: ");
4880 result.append(buffer);
4881 for (size_t i = 0; i < mSamplingRates.size(); i++) {
4882 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
4883 result.append(buffer);
4884 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
4885 }
4886
4887 snprintf(buffer, SIZE, " - channel masks: ");
4888 result.append(buffer);
4889 for (size_t i = 0; i < mChannelMasks.size(); i++) {
4890 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
4891 result.append(buffer);
4892 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
4893 }
4894
4895 snprintf(buffer, SIZE, " - formats: ");
4896 result.append(buffer);
4897 for (size_t i = 0; i < mFormats.size(); i++) {
4898 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
4899 result.append(buffer);
4900 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
4901 }
4902
Eric Laurent3a4311c2014-03-17 12:00:47 -07004903 snprintf(buffer, SIZE, " - devices:\n");
Eric Laurente552edb2014-03-10 17:42:56 -07004904 result.append(buffer);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004905 write(fd, result.string(), result.size());
4906 DeviceDescriptor::dumpHeader(fd, 6);
4907 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
4908 mSupportedDevices[i]->dump(fd, 6);
4909 }
4910
Eric Laurente552edb2014-03-10 17:42:56 -07004911 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
4912 result.append(buffer);
4913
4914 write(fd, result.string(), result.size());
4915}
4916
Eric Laurentd4692962014-05-05 18:13:44 -07004917void AudioPolicyManager::IOProfile::log()
4918{
4919 const size_t SIZE = 256;
4920 char buffer[SIZE];
4921 String8 result;
4922
4923 ALOGV(" - sampling rates: ");
4924 for (size_t i = 0; i < mSamplingRates.size(); i++) {
4925 ALOGV(" %d", mSamplingRates[i]);
4926 }
4927
4928 ALOGV(" - channel masks: ");
4929 for (size_t i = 0; i < mChannelMasks.size(); i++) {
4930 ALOGV(" 0x%04x", mChannelMasks[i]);
4931 }
4932
4933 ALOGV(" - formats: ");
4934 for (size_t i = 0; i < mFormats.size(); i++) {
4935 ALOGV(" 0x%08x", mFormats[i]);
4936 }
4937
4938 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
4939 ALOGV(" - flags: 0x%04x\n", mFlags);
4940}
4941
4942
Eric Laurent3a4311c2014-03-17 12:00:47 -07004943// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004944
Eric Laurent3a4311c2014-03-17 12:00:47 -07004945bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07004946{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004947 // Devices are considered equal if they:
4948 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
4949 // - have the same address or one device does not specify the address
4950 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent951f4552014-05-20 10:48:17 -07004951 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004952 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07004953 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07004954 mChannelMask == other->mChannelMask);
4955}
4956
4957void AudioPolicyManager::DeviceVector::refreshTypes()
4958{
Eric Laurent951f4552014-05-20 10:48:17 -07004959 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004960 for(size_t i = 0; i < size(); i++) {
Eric Laurent951f4552014-05-20 10:48:17 -07004961 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004962 }
Eric Laurent951f4552014-05-20 10:48:17 -07004963 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004964}
4965
4966ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
4967{
4968 for(size_t i = 0; i < size(); i++) {
4969 if (item->equals(itemAt(i))) {
4970 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07004971 }
4972 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004973 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07004974}
4975
Eric Laurent3a4311c2014-03-17 12:00:47 -07004976ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07004977{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004978 ssize_t ret = indexOf(item);
4979
4980 if (ret < 0) {
4981 ret = SortedVector::add(item);
4982 if (ret >= 0) {
4983 refreshTypes();
4984 }
4985 } else {
Eric Laurent951f4552014-05-20 10:48:17 -07004986 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004987 ret = -1;
4988 }
4989 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07004990}
4991
Eric Laurent3a4311c2014-03-17 12:00:47 -07004992ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
4993{
4994 size_t i;
4995 ssize_t ret = indexOf(item);
4996
4997 if (ret < 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07004998 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004999 } else {
5000 ret = SortedVector::removeAt(ret);
5001 if (ret >= 0) {
5002 refreshTypes();
5003 }
5004 }
5005 return ret;
5006}
5007
5008void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5009{
5010 DeviceVector deviceList;
5011
5012 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5013 types &= ~role_bit;
5014
5015 while (types) {
5016 uint32_t i = 31 - __builtin_clz(types);
5017 uint32_t type = 1 << i;
5018 types &= ~type;
5019 add(new DeviceDescriptor(type | role_bit));
5020 }
5021}
5022
Eric Laurent951f4552014-05-20 10:48:17 -07005023sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5024 audio_devices_t type, String8 address) const
5025{
5026 sp<DeviceDescriptor> device;
5027 for (size_t i = 0; i < size(); i++) {
5028 if (itemAt(i)->mDeviceType == type) {
5029 device = itemAt(i);
5030 if (itemAt(i)->mAddress = address) {
5031 break;
5032 }
5033 }
5034 }
5035 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5036 type, address.string(), device.get());
5037 return device;
5038}
5039
Eric Laurent6a94d692014-05-20 11:18:06 -07005040sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5041 audio_port_handle_t id) const
5042{
5043 sp<DeviceDescriptor> device;
5044 for (size_t i = 0; i < size(); i++) {
5045 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%d)->mId %d", id, i, itemAt(i)->mId);
5046 if (itemAt(i)->mId == id) {
5047 device = itemAt(i);
5048 break;
5049 }
5050 }
5051 return device;
5052}
5053
Eric Laurent951f4552014-05-20 10:48:17 -07005054AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5055 audio_devices_t type) const
5056{
5057 DeviceVector devices;
5058 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5059 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5060 devices.add(itemAt(i));
5061 type &= ~itemAt(i)->mDeviceType;
5062 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5063 itemAt(i)->mDeviceType, itemAt(i).get());
5064 }
5065 }
5066 return devices;
5067}
5068
Eric Laurent6a94d692014-05-20 11:18:06 -07005069void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5070 struct audio_port_config *dstConfig,
5071 const struct audio_port_config *srcConfig) const
Eric Laurent951f4552014-05-20 10:48:17 -07005072{
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 dstConfig->id = mId;
5074 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent951f4552014-05-20 10:48:17 -07005075 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005076 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
5077 dstConfig->channel_mask = mChannelMask;
5078 dstConfig->gain.index = -1;
5079 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK;
5080 // use supplied variable configuration parameters if any
5081 if (srcConfig != NULL) {
5082 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5083 dstConfig->channel_mask = srcConfig->channel_mask;
5084 }
5085 if (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5086 dstConfig->gain = srcConfig->gain;
5087 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5088 }
5089 }
5090 dstConfig->ext.device.type = mDeviceType;
5091 dstConfig->ext.device.hw_module = mModule->mHandle;
5092 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent951f4552014-05-20 10:48:17 -07005093}
5094
5095void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5096{
5097 AudioPort::toAudioPort(port);
5098 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005099 toAudioPortConfig(&port->active_config);
Eric Laurent951f4552014-05-20 10:48:17 -07005100 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005101 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent951f4552014-05-20 10:48:17 -07005102 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5103}
5104
Eric Laurent3a4311c2014-03-17 12:00:47 -07005105void AudioPolicyManager::DeviceDescriptor::dumpHeader(int fd, int spaces)
5106{
5107 const size_t SIZE = 256;
5108 char buffer[SIZE];
5109
5110 snprintf(buffer, SIZE, "%*s%-48s %-2s %-8s %-32s \n",
5111 spaces, "", "Type", "ID", "Cnl Mask", "Address");
5112 write(fd, buffer, strlen(buffer));
5113}
5114
5115status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces) const
5116{
5117 const size_t SIZE = 256;
5118 char buffer[SIZE];
5119
5120 snprintf(buffer, SIZE, "%*s%-48s %2d %08x %-32s \n",
5121 spaces, "",
5122 enumToString(sDeviceNameToEnumTable,
5123 ARRAY_SIZE(sDeviceNameToEnumTable),
Eric Laurent951f4552014-05-20 10:48:17 -07005124 mDeviceType),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005125 mId, mChannelMask, mAddress.string());
5126 write(fd, buffer, strlen(buffer));
5127
5128 return NO_ERROR;
5129}
5130
5131
5132// --- audio_policy.conf file parsing
5133
Eric Laurente0720872014-03-11 09:30:41 -07005134audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005135{
5136 uint32_t flag = 0;
5137
5138 // it is OK to cast name to non const here as we are not going to use it after
5139 // strtok() modifies it
5140 char *flagName = strtok(name, "|");
5141 while (flagName != NULL) {
5142 if (strlen(flagName) != 0) {
5143 flag |= stringToEnum(sFlagNameToEnumTable,
5144 ARRAY_SIZE(sFlagNameToEnumTable),
5145 flagName);
5146 }
5147 flagName = strtok(NULL, "|");
5148 }
5149 //force direct flag if offload flag is set: offloading implies a direct output stream
5150 // and all common behaviors are driven by checking only the direct flag
5151 // this should normally be set appropriately in the policy configuration file
5152 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5153 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5154 }
5155
5156 return (audio_output_flags_t)flag;
5157}
5158
Eric Laurente0720872014-03-11 09:30:41 -07005159audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005160{
5161 uint32_t device = 0;
5162
5163 char *devName = strtok(name, "|");
5164 while (devName != NULL) {
5165 if (strlen(devName) != 0) {
5166 device |= stringToEnum(sDeviceNameToEnumTable,
5167 ARRAY_SIZE(sDeviceNameToEnumTable),
5168 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005169 }
Eric Laurente552edb2014-03-10 17:42:56 -07005170 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005171 }
Eric Laurente552edb2014-03-10 17:42:56 -07005172 return device;
5173}
5174
Eric Laurente0720872014-03-11 09:30:41 -07005175status_t AudioPolicyManager::loadInput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07005176{
5177 cnode *node = root->first_child;
5178
Eric Laurent951f4552014-05-20 10:48:17 -07005179 sp<IOProfile> profile = new IOProfile(AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005180
5181 while (node) {
5182 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07005183 profile->loadSamplingRates((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005184 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07005185 profile->loadFormats((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005186 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07005187 profile->loadInChannels((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005188 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005189 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07005190 }
5191 node = node->next;
5192 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005193 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07005194 "loadInput() invalid supported devices");
5195 ALOGW_IF(profile->mChannelMasks.size() == 0,
5196 "loadInput() invalid supported channel masks");
5197 ALOGW_IF(profile->mSamplingRates.size() == 0,
5198 "loadInput() invalid supported sampling rates");
5199 ALOGW_IF(profile->mFormats.size() == 0,
5200 "loadInput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005201 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07005202 (profile->mChannelMasks.size() != 0) &&
5203 (profile->mSamplingRates.size() != 0) &&
5204 (profile->mFormats.size() != 0)) {
5205
Eric Laurent3a4311c2014-03-17 12:00:47 -07005206 ALOGV("loadInput() adding input Supported Devices %04x",
5207 profile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005208
5209 module->mInputProfiles.add(profile);
5210 return NO_ERROR;
5211 } else {
Eric Laurente552edb2014-03-10 17:42:56 -07005212 return BAD_VALUE;
5213 }
5214}
5215
Eric Laurente0720872014-03-11 09:30:41 -07005216status_t AudioPolicyManager::loadOutput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07005217{
5218 cnode *node = root->first_child;
5219
Eric Laurent951f4552014-05-20 10:48:17 -07005220 sp<IOProfile> profile = new IOProfile(AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005221
5222 while (node) {
5223 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07005224 profile->loadSamplingRates((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005225 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07005226 profile->loadFormats((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005227 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
Eric Laurent951f4552014-05-20 10:48:17 -07005228 profile->loadOutChannels((char *)node->value);
Eric Laurente552edb2014-03-10 17:42:56 -07005229 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005230 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07005231 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5232 profile->mFlags = parseFlagNames((char *)node->value);
5233 }
5234 node = node->next;
5235 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005236 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07005237 "loadOutput() invalid supported devices");
5238 ALOGW_IF(profile->mChannelMasks.size() == 0,
5239 "loadOutput() invalid supported channel masks");
5240 ALOGW_IF(profile->mSamplingRates.size() == 0,
5241 "loadOutput() invalid supported sampling rates");
5242 ALOGW_IF(profile->mFormats.size() == 0,
5243 "loadOutput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005244 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07005245 (profile->mChannelMasks.size() != 0) &&
5246 (profile->mSamplingRates.size() != 0) &&
5247 (profile->mFormats.size() != 0)) {
5248
Eric Laurent3a4311c2014-03-17 12:00:47 -07005249 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5250 profile->mSupportedDevices.types(), profile->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07005251
5252 module->mOutputProfiles.add(profile);
5253 return NO_ERROR;
5254 } else {
Eric Laurente552edb2014-03-10 17:42:56 -07005255 return BAD_VALUE;
5256 }
5257}
5258
Eric Laurente0720872014-03-11 09:30:41 -07005259void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005260{
5261 cnode *node = config_find(root, OUTPUTS_TAG);
5262 status_t status = NAME_NOT_FOUND;
5263
5264 HwModule *module = new HwModule(root->name);
5265
5266 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005267 node = node->first_child;
5268 while (node) {
5269 ALOGV("loadHwModule() loading output %s", node->name);
5270 status_t tmpStatus = loadOutput(node, module);
5271 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5272 status = tmpStatus;
5273 }
5274 node = node->next;
5275 }
5276 }
5277 node = config_find(root, INPUTS_TAG);
5278 if (node != NULL) {
5279 node = node->first_child;
5280 while (node) {
5281 ALOGV("loadHwModule() loading input %s", node->name);
5282 status_t tmpStatus = loadInput(node, module);
5283 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5284 status = tmpStatus;
5285 }
5286 node = node->next;
5287 }
5288 }
5289 if (status == NO_ERROR) {
5290 mHwModules.add(module);
5291 } else {
5292 delete module;
5293 }
5294}
5295
Eric Laurente0720872014-03-11 09:30:41 -07005296void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005297{
5298 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5299 if (node == NULL) {
5300 return;
5301 }
5302
5303 node = node->first_child;
5304 while (node) {
5305 ALOGV("loadHwModules() loading module %s", node->name);
5306 loadHwModule(node);
5307 node = node->next;
5308 }
5309}
5310
Eric Laurente0720872014-03-11 09:30:41 -07005311void AudioPolicyManager::loadGlobalConfig(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005312{
5313 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
5314 if (node == NULL) {
5315 return;
5316 }
5317 node = node->first_child;
5318 while (node) {
5319 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005320 mAvailableOutputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
5321 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5322 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005323 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005324 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005325 ARRAY_SIZE(sDeviceNameToEnumTable),
5326 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005327 if (device != AUDIO_DEVICE_NONE) {
5328 mDefaultOutputDevice = new DeviceDescriptor(device);
5329 } else {
5330 ALOGW("loadGlobalConfig() default device not specified");
5331 }
Eric Laurent951f4552014-05-20 10:48:17 -07005332 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005333 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005334 mAvailableInputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
5335 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005336 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5337 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5338 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
5339 }
5340 node = node->next;
5341 }
5342}
5343
Eric Laurente0720872014-03-11 09:30:41 -07005344status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005345{
5346 cnode *root;
5347 char *data;
5348
5349 data = (char *)load_file(path, NULL);
5350 if (data == NULL) {
5351 return -ENODEV;
5352 }
5353 root = config_node("", "");
5354 config_load(root, data);
5355
5356 loadGlobalConfig(root);
5357 loadHwModules(root);
5358
5359 config_free(root);
5360 free(root);
5361 free(data);
5362
5363 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5364
5365 return NO_ERROR;
5366}
5367
Eric Laurente0720872014-03-11 09:30:41 -07005368void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07005369{
5370 HwModule *module;
Eric Laurent951f4552014-05-20 10:48:17 -07005371 sp<IOProfile> profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005372 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUILTIN_MIC);
5373 mAvailableOutputDevices.add(mDefaultOutputDevice);
5374 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005375
5376 module = new HwModule("primary");
5377
Eric Laurent951f4552014-05-20 10:48:17 -07005378 profile = new IOProfile(AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005379 profile->mSamplingRates.add(44100);
5380 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5381 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005382 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005383 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
5384 module->mOutputProfiles.add(profile);
5385
Eric Laurent951f4552014-05-20 10:48:17 -07005386 profile = new IOProfile(AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005387 profile->mSamplingRates.add(8000);
5388 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5389 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005390 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005391 module->mInputProfiles.add(profile);
5392
5393 mHwModules.add(module);
5394}
5395
5396}; // namespace android