blob: 74c62073232e0f57540fe1e8aefc75bb3fe341f7 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
33
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
39#include <hardware/audio.h>
40#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070041#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070043#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070044
Eric Laurent3b73df72014-03-11 09:06:29 -070045namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070046
47// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070048// Definitions for audio_policy.conf file parsing
49// ----------------------------------------------------------------------------
50
51struct StringToEnum {
52 const char *name;
53 uint32_t value;
54};
55
56#define STRING_TO_ENUM(string) { #string, string }
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
59const StringToEnum sDeviceNameToEnumTable[] = {
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070073 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070074 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700104};
105
106const StringToEnum sFlagNameToEnumTable[] = {
107 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
113};
114
115const StringToEnum sFormatNameToEnumTable[] = {
116 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
122 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
123 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
124 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700125 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
126 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
127 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
128 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
129 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700130};
131
132const StringToEnum sOutChannelsNameToEnumTable[] = {
133 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
134 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
135 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
136 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
137};
138
139const StringToEnum sInChannelsNameToEnumTable[] = {
140 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
141 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
142 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
143};
144
Eric Laurent1afeecb2014-05-14 08:52:28 -0700145const StringToEnum sGainModeNameToEnumTable[] = {
146 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
147 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
148 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
149};
150
Eric Laurent3a4311c2014-03-17 12:00:47 -0700151
152uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
153 size_t size,
154 const char *name)
155{
156 for (size_t i = 0; i < size; i++) {
157 if (strcmp(table[i].name, name) == 0) {
158 ALOGV("stringToEnum() found %s", table[i].name);
159 return table[i].value;
160 }
161 }
162 return 0;
163}
164
165const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
166 size_t size,
167 uint32_t value)
168{
169 for (size_t i = 0; i < size; i++) {
170 if (table[i].value == value) {
171 return table[i].name;
172 }
173 }
174 return "";
175}
176
177bool AudioPolicyManager::stringToBool(const char *value)
178{
179 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
180}
181
182
183// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700184// AudioPolicyInterface implementation
185// ----------------------------------------------------------------------------
186
187
Eric Laurente0720872014-03-11 09:30:41 -0700188status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700189 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700190 const char *device_address)
191{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
194 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
195
196 // connect/disconnect only 1 device at a time
197 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 // handle output devices
200 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700201 SortedVector <audio_io_handle_t> outputs;
202
Eric Laurent1afeecb2014-05-14 08:52:28 -0700203 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
204 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700205 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
206
Eric Laurente552edb2014-03-10 17:42:56 -0700207 // save a copy of the opened output descriptors before any output is opened or closed
208 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
209 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700210 switch (state)
211 {
212 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700213 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700214 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700215 ALOGW("setDeviceConnectionState() device already connected: %x", device);
216 return INVALID_OPERATION;
217 }
218 ALOGV("setDeviceConnectionState() connecting device %x", device);
219
Eric Laurent3a4311c2014-03-17 12:00:47 -0700220 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700221 return INVALID_OPERATION;
222 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700223 // outputs should never be empty here
224 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
225 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700226 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700227 outputs.size());
228 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700229 index = mAvailableOutputDevices.add(devDesc);
230 if (index >= 0) {
231 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700232 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700233 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
234 "could not find HW module for device %08x", device);
235 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 } else {
237 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700238 }
239
240 break;
241 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700242 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700244 ALOGW("setDeviceConnectionState() device not connected: %x", device);
245 return INVALID_OPERATION;
246 }
247
248 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
249 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700253 // not currently handling multiple simultaneous submixes: ignoring remote submix
254 // case and address
255 } break;
256
257 default:
258 ALOGE("setDeviceConnectionState() invalid state: %x", state);
259 return BAD_VALUE;
260 }
261
Eric Laurent3a4311c2014-03-17 12:00:47 -0700262 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
263 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700264 checkA2dpSuspend();
265 checkOutputForAllStrategies();
266 // outputs must be closed after checkOutputForAllStrategies() is executed
267 if (!outputs.isEmpty()) {
268 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700269 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700270 // close unused outputs after device disconnection or direct outputs that have been
271 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700272 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700273 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
274 (desc->mDirectOpenCount == 0))) {
275 closeOutput(outputs[i]);
276 }
277 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 // check again after closing A2DP output to reset mA2dpSuspended if needed
279 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700280 }
281
282 updateDevicesAndOutputs();
283 for (size_t i = 0; i < mOutputs.size(); i++) {
284 // do not force device change on duplicated output because if device is 0, it will
285 // also force a device 0 for the two outputs it is duplicated to which may override
286 // a valid device selection on those outputs.
287 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700288 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700289 !mOutputs.valueAt(i)->isDuplicated(),
290 0);
291 }
292
Eric Laurent72aa32f2014-05-30 18:51:48 -0700293 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700294 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700295 } // end if is output device
296
Eric Laurente552edb2014-03-10 17:42:56 -0700297 // handle input devices
298 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700299 SortedVector <audio_io_handle_t> inputs;
300
Eric Laurent1afeecb2014-05-14 08:52:28 -0700301 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
302 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700304 switch (state)
305 {
306 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700307 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700308 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700309 ALOGW("setDeviceConnectionState() device already connected: %d", device);
310 return INVALID_OPERATION;
311 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700312 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700313 if (module == NULL) {
314 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
315 device);
316 return INVALID_OPERATION;
317 }
Eric Laurentd4692962014-05-05 18:13:44 -0700318 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
319 return INVALID_OPERATION;
320 }
321
Eric Laurent3a4311c2014-03-17 12:00:47 -0700322 index = mAvailableInputDevices.add(devDesc);
323 if (index >= 0) {
324 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700325 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 } else {
327 return NO_MEMORY;
328 }
Eric Laurentd4692962014-05-05 18:13:44 -0700329 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700330
331 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700332 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700334 ALOGW("setDeviceConnectionState() device not connected: %d", device);
335 return INVALID_OPERATION;
336 }
Eric Laurentd4692962014-05-05 18:13:44 -0700337 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700338 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700339 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700340
341 default:
342 ALOGE("setDeviceConnectionState() invalid state: %x", state);
343 return BAD_VALUE;
344 }
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700347
Eric Laurentb52c1522014-05-20 11:27:36 -0700348 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700349 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700350 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700351
352 ALOGW("setDeviceConnectionState() invalid device: %x", device);
353 return BAD_VALUE;
354}
355
Eric Laurente0720872014-03-11 09:30:41 -0700356audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700357 const char *device_address)
358{
Eric Laurent3b73df72014-03-11 09:06:29 -0700359 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700361 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
362 devDesc->mAddress = String8(device_address);
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 Laurent1c333e22014-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
Eric Laurent1f2f2232014-06-02 12:01:23 -0700443 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700444
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++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700455 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700456 // 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 Laurent1c333e22014-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 Laurent1c333e22014-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 Laurent1c333e22014-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 Laurent1c333e22014-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{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700631
Eric Laurent3b73df72014-03-11 09:06:29 -0700632 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700633 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
634 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
635 device, stream, samplingRate, format, channelMask, flags);
636
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700637 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
638 offloadInfo);
639}
640
641audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
642 uint32_t samplingRate,
643 audio_format_t format,
644 audio_channel_mask_t channelMask,
645 audio_output_flags_t flags,
646 const audio_offload_info_t *offloadInfo)
647{
648 if (attr == NULL) {
649 ALOGE("getOutputForAttr() called with NULL audio attributes");
650 return 0;
651 }
652 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
653 attr->usage, attr->content_type, attr->tags);
654
655 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
656 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
657 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
658 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
659 device, samplingRate, format, channelMask, flags);
660
661 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
662 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
663 offloadInfo);
664}
665
666audio_io_handle_t AudioPolicyManager::getOutputForDevice(
667 audio_devices_t device,
668 audio_stream_type_t stream,
669 uint32_t samplingRate,
670 audio_format_t format,
671 audio_channel_mask_t channelMask,
672 audio_output_flags_t flags,
673 const audio_offload_info_t *offloadInfo)
674{
675 audio_io_handle_t output = 0;
676 uint32_t latency = 0;
677
Eric Laurente552edb2014-03-10 17:42:56 -0700678#ifdef AUDIO_POLICY_TEST
679 if (mCurOutput != 0) {
680 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
681 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
682
683 if (mTestOutputs[mCurOutput] == 0) {
684 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700685 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700686 outputDesc->mDevice = mTestDevice;
687 outputDesc->mSamplingRate = mTestSamplingRate;
688 outputDesc->mFormat = mTestFormat;
689 outputDesc->mChannelMask = mTestChannels;
690 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700691 outputDesc->mFlags =
692 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700693 outputDesc->mRefCount[stream] = 0;
694 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
695 &outputDesc->mSamplingRate,
696 &outputDesc->mFormat,
697 &outputDesc->mChannelMask,
698 &outputDesc->mLatency,
699 outputDesc->mFlags,
700 offloadInfo);
701 if (mTestOutputs[mCurOutput]) {
702 AudioParameter outputCmd = AudioParameter();
703 outputCmd.addInt(String8("set_id"),mCurOutput);
704 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
705 addOutput(mTestOutputs[mCurOutput], outputDesc);
706 }
707 }
708 return mTestOutputs[mCurOutput];
709 }
710#endif //AUDIO_POLICY_TEST
711
712 // open a direct output if required by specified parameters
713 //force direct flag if offload flag is set: offloading implies a direct output stream
714 // and all common behaviors are driven by checking only the direct flag
715 // this should normally be set appropriately in the policy configuration file
716 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700717 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700718 }
719
720 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
721 // creating an offloaded track and tearing it down immediately after start when audioflinger
722 // detects there is an active non offloadable effect.
723 // FIXME: We should check the audio session here but we do not have it in this context.
724 // This may prevent offloading in rare situations where effects are left active by apps
725 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700726 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700727 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
728 !isNonOffloadableEffectEnabled()) {
729 profile = getProfileForDirectOutput(device,
730 samplingRate,
731 format,
732 channelMask,
733 (audio_output_flags_t)flags);
734 }
735
Eric Laurent1c333e22014-05-20 10:48:17 -0700736 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700737 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700738
739 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700740 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700741 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
742 outputDesc = desc;
743 // reuse direct output if currently open and configured with same parameters
744 if ((samplingRate == outputDesc->mSamplingRate) &&
745 (format == outputDesc->mFormat) &&
746 (channelMask == outputDesc->mChannelMask)) {
747 outputDesc->mDirectOpenCount++;
748 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
749 return mOutputs.keyAt(i);
750 }
751 }
752 }
753 // close direct output if currently open and configured with different parameters
754 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700755 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700756 }
757 outputDesc = new AudioOutputDescriptor(profile);
758 outputDesc->mDevice = device;
759 outputDesc->mSamplingRate = samplingRate;
760 outputDesc->mFormat = format;
761 outputDesc->mChannelMask = channelMask;
762 outputDesc->mLatency = 0;
763 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
764 outputDesc->mRefCount[stream] = 0;
765 outputDesc->mStopTime[stream] = 0;
766 outputDesc->mDirectOpenCount = 1;
767 output = mpClientInterface->openOutput(profile->mModule->mHandle,
768 &outputDesc->mDevice,
769 &outputDesc->mSamplingRate,
770 &outputDesc->mFormat,
771 &outputDesc->mChannelMask,
772 &outputDesc->mLatency,
773 outputDesc->mFlags,
774 offloadInfo);
775
776 // only accept an output with the requested parameters
777 if (output == 0 ||
778 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
779 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
780 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
781 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
782 "format %d %d, channelMask %04x %04x", output, samplingRate,
783 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
784 outputDesc->mChannelMask);
785 if (output != 0) {
786 mpClientInterface->closeOutput(output);
787 }
Eric Laurente552edb2014-03-10 17:42:56 -0700788 return 0;
789 }
790 audio_io_handle_t srcOutput = getOutputForEffect();
791 addOutput(output, outputDesc);
792 audio_io_handle_t dstOutput = getOutputForEffect();
793 if (dstOutput == output) {
794 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
795 }
796 mPreviousOutputs = mOutputs;
797 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700798 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700799 return output;
800 }
801
802 // ignoring channel mask due to downmix capability in mixer
803
804 // open a non direct output
805
806 // for non direct outputs, only PCM is supported
807 if (audio_is_linear_pcm(format)) {
808 // get which output is suitable for the specified stream. The actual
809 // routing change will happen when startOutput() will be called
810 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
811
812 output = selectOutput(outputs, flags);
813 }
814 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
815 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
816
817 ALOGV("getOutput() returns output %d", output);
818
819 return output;
820}
821
Eric Laurente0720872014-03-11 09:30:41 -0700822audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700823 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700824{
825 // select one output among several that provide a path to a particular device or set of
826 // devices (the list was previously build by getOutputsForDevice()).
827 // The priority is as follows:
828 // 1: the output with the highest number of requested policy flags
829 // 2: the primary output
830 // 3: the first output in the list
831
832 if (outputs.size() == 0) {
833 return 0;
834 }
835 if (outputs.size() == 1) {
836 return outputs[0];
837 }
838
839 int maxCommonFlags = 0;
840 audio_io_handle_t outputFlags = 0;
841 audio_io_handle_t outputPrimary = 0;
842
843 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700844 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700845 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700846 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 if (commonFlags > maxCommonFlags) {
848 outputFlags = outputs[i];
849 maxCommonFlags = commonFlags;
850 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
851 }
852 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
853 outputPrimary = outputs[i];
854 }
855 }
856 }
857
858 if (outputFlags != 0) {
859 return outputFlags;
860 }
861 if (outputPrimary != 0) {
862 return outputPrimary;
863 }
864
865 return outputs[0];
866}
867
Eric Laurente0720872014-03-11 09:30:41 -0700868status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700869 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700870 int session)
871{
872 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
873 ssize_t index = mOutputs.indexOfKey(output);
874 if (index < 0) {
875 ALOGW("startOutput() unknown output %d", output);
876 return BAD_VALUE;
877 }
878
Eric Laurent1f2f2232014-06-02 12:01:23 -0700879 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700880
881 // increment usage count for this stream on the requested output:
882 // NOTE that the usage count is the same for duplicated output and hardware output which is
883 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
884 outputDesc->changeRefCount(stream, 1);
885
886 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700887 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700888 routing_strategy strategy = getStrategy(stream);
889 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
890 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
891 uint32_t waitMs = 0;
892 bool force = false;
893 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700894 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700895 if (desc != outputDesc) {
896 // force a device change if any other output is managed by the same hw
897 // module and has a current device selection that differs from selected device.
898 // In this case, the audio HAL must receive the new device selection so that it can
899 // change the device currently selected by the other active output.
900 if (outputDesc->sharesHwModuleWith(desc) &&
901 desc->device() != newDevice) {
902 force = true;
903 }
904 // wait for audio on other active outputs to be presented when starting
905 // a notification so that audio focus effect can propagate.
906 uint32_t latency = desc->latency();
907 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
908 waitMs = latency;
909 }
910 }
911 }
912 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
913
914 // handle special case for sonification while in call
915 if (isInCall()) {
916 handleIncallSonification(stream, true, false);
917 }
918
919 // apply volume rules for current stream and device if necessary
920 checkAndSetVolume(stream,
921 mStreams[stream].getVolumeIndex(newDevice),
922 output,
923 newDevice);
924
925 // update the outputs if starting an output with a stream that can affect notification
926 // routing
927 handleNotificationRoutingForStream(stream);
928 if (waitMs > muteWaitMs) {
929 usleep((waitMs - muteWaitMs) * 2 * 1000);
930 }
931 }
932 return NO_ERROR;
933}
934
935
Eric Laurente0720872014-03-11 09:30:41 -0700936status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700937 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700938 int session)
939{
940 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
941 ssize_t index = mOutputs.indexOfKey(output);
942 if (index < 0) {
943 ALOGW("stopOutput() unknown output %d", output);
944 return BAD_VALUE;
945 }
946
Eric Laurent1f2f2232014-06-02 12:01:23 -0700947 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700948
949 // handle special case for sonification while in call
950 if (isInCall()) {
951 handleIncallSonification(stream, false, false);
952 }
953
954 if (outputDesc->mRefCount[stream] > 0) {
955 // decrement usage count of this stream on the output
956 outputDesc->changeRefCount(stream, -1);
957 // store time at which the stream was stopped - see isStreamActive()
958 if (outputDesc->mRefCount[stream] == 0) {
959 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700960 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700961 // delay the device switch by twice the latency because stopOutput() is executed when
962 // the track stop() command is received and at that time the audio track buffer can
963 // still contain data that needs to be drained. The latency only covers the audio HAL
964 // and kernel buffers. Also the latency does not always include additional delay in the
965 // audio path (audio DSP, CODEC ...)
966 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
967
968 // force restoring the device selection on other active outputs if it differs from the
969 // one being selected for this output
970 for (size_t i = 0; i < mOutputs.size(); i++) {
971 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700972 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700973 if (curOutput != output &&
974 desc->isActive() &&
975 outputDesc->sharesHwModuleWith(desc) &&
976 (newDevice != desc->device())) {
977 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700978 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700979 true,
980 outputDesc->mLatency*2);
981 }
982 }
983 // update the outputs if stopping one with a stream that can affect notification routing
984 handleNotificationRoutingForStream(stream);
985 }
986 return NO_ERROR;
987 } else {
988 ALOGW("stopOutput() refcount is already 0 for output %d", output);
989 return INVALID_OPERATION;
990 }
991}
992
Eric Laurente0720872014-03-11 09:30:41 -0700993void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700994{
995 ALOGV("releaseOutput() %d", output);
996 ssize_t index = mOutputs.indexOfKey(output);
997 if (index < 0) {
998 ALOGW("releaseOutput() releasing unknown output %d", output);
999 return;
1000 }
1001
1002#ifdef AUDIO_POLICY_TEST
1003 int testIndex = testOutputIndex(output);
1004 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001005 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001006 if (outputDesc->isActive()) {
1007 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001008 mOutputs.removeItem(output);
1009 mTestOutputs[testIndex] = 0;
1010 }
1011 return;
1012 }
1013#endif //AUDIO_POLICY_TEST
1014
Eric Laurent1f2f2232014-06-02 12:01:23 -07001015 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001016 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001017 if (desc->mDirectOpenCount <= 0) {
1018 ALOGW("releaseOutput() invalid open count %d for output %d",
1019 desc->mDirectOpenCount, output);
1020 return;
1021 }
1022 if (--desc->mDirectOpenCount == 0) {
1023 closeOutput(output);
1024 // If effects where present on the output, audioflinger moved them to the primary
1025 // output by default: move them back to the appropriate output.
1026 audio_io_handle_t dstOutput = getOutputForEffect();
1027 if (dstOutput != mPrimaryOutput) {
1028 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1029 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001030 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001031 }
1032 }
1033}
1034
1035
Eric Laurente0720872014-03-11 09:30:41 -07001036audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001037 uint32_t samplingRate,
1038 audio_format_t format,
1039 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001040 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001041{
1042 audio_io_handle_t input = 0;
1043 audio_devices_t device = getDeviceForInputSource(inputSource);
1044
1045 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1046 inputSource, samplingRate, format, channelMask, acoustics);
1047
1048 if (device == AUDIO_DEVICE_NONE) {
1049 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1050 return 0;
1051 }
1052
1053 // adapt channel selection to input source
1054 switch(inputSource) {
1055 case AUDIO_SOURCE_VOICE_UPLINK:
1056 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1057 break;
1058 case AUDIO_SOURCE_VOICE_DOWNLINK:
1059 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1060 break;
1061 case AUDIO_SOURCE_VOICE_CALL:
1062 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1063 break;
1064 default:
1065 break;
1066 }
1067
Eric Laurent1c333e22014-05-20 10:48:17 -07001068 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001069 samplingRate,
1070 format,
1071 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001072 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001073 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1074 "channelMask %04x",
1075 device, samplingRate, format, channelMask);
1076 return 0;
1077 }
1078
1079 if (profile->mModule->mHandle == 0) {
1080 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1081 return 0;
1082 }
1083
Eric Laurent1f2f2232014-06-02 12:01:23 -07001084 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001085
1086 inputDesc->mInputSource = inputSource;
1087 inputDesc->mDevice = device;
1088 inputDesc->mSamplingRate = samplingRate;
1089 inputDesc->mFormat = format;
1090 inputDesc->mChannelMask = channelMask;
1091 inputDesc->mRefCount = 0;
1092 input = mpClientInterface->openInput(profile->mModule->mHandle,
1093 &inputDesc->mDevice,
1094 &inputDesc->mSamplingRate,
1095 &inputDesc->mFormat,
1096 &inputDesc->mChannelMask);
1097
1098 // only accept input with the exact requested set of parameters
1099 if (input == 0 ||
1100 (samplingRate != inputDesc->mSamplingRate) ||
1101 (format != inputDesc->mFormat) ||
1102 (channelMask != inputDesc->mChannelMask)) {
1103 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1104 samplingRate, format, channelMask);
1105 if (input != 0) {
1106 mpClientInterface->closeInput(input);
1107 }
Eric Laurente552edb2014-03-10 17:42:56 -07001108 return 0;
1109 }
Eric Laurentd4692962014-05-05 18:13:44 -07001110 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001111 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001112 return input;
1113}
1114
Eric Laurente0720872014-03-11 09:30:41 -07001115status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001116{
1117 ALOGV("startInput() input %d", input);
1118 ssize_t index = mInputs.indexOfKey(input);
1119 if (index < 0) {
1120 ALOGW("startInput() unknown input %d", input);
1121 return BAD_VALUE;
1122 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001123 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001124
1125#ifdef AUDIO_POLICY_TEST
1126 if (mTestInput == 0)
1127#endif //AUDIO_POLICY_TEST
1128 {
1129 // refuse 2 active AudioRecord clients at the same time except if the active input
1130 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1131 audio_io_handle_t activeInput = getActiveInput();
1132 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001133 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001134 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1135 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1136 stopInput(activeInput);
1137 releaseInput(activeInput);
1138 } else {
1139 ALOGW("startInput() input %d failed: other input already started", input);
1140 return INVALID_OPERATION;
1141 }
1142 }
1143 }
1144
Eric Laurent1c333e22014-05-20 10:48:17 -07001145 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001146
1147 // automatically enable the remote submix output when input is started
1148 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1149 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001150 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001151 }
1152
Eric Laurente552edb2014-03-10 17:42:56 -07001153 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1154
Eric Laurente552edb2014-03-10 17:42:56 -07001155 inputDesc->mRefCount = 1;
1156 return NO_ERROR;
1157}
1158
Eric Laurente0720872014-03-11 09:30:41 -07001159status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001160{
1161 ALOGV("stopInput() input %d", input);
1162 ssize_t index = mInputs.indexOfKey(input);
1163 if (index < 0) {
1164 ALOGW("stopInput() unknown input %d", input);
1165 return BAD_VALUE;
1166 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001167 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001168
1169 if (inputDesc->mRefCount == 0) {
1170 ALOGW("stopInput() input %d already stopped", input);
1171 return INVALID_OPERATION;
1172 } else {
1173 // automatically disable the remote submix output when input is stopped
1174 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1175 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001176 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001177 }
1178
Eric Laurent1c333e22014-05-20 10:48:17 -07001179 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001180 inputDesc->mRefCount = 0;
1181 return NO_ERROR;
1182 }
1183}
1184
Eric Laurente0720872014-03-11 09:30:41 -07001185void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
1187 ALOGV("releaseInput() %d", input);
1188 ssize_t index = mInputs.indexOfKey(input);
1189 if (index < 0) {
1190 ALOGW("releaseInput() releasing unknown input %d", input);
1191 return;
1192 }
1193 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001194 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001195 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001196 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001197 ALOGV("releaseInput() exit");
1198}
1199
Eric Laurentd4692962014-05-05 18:13:44 -07001200void AudioPolicyManager::closeAllInputs() {
1201 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1202 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1203 }
1204 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001205 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001206}
1207
Eric Laurente0720872014-03-11 09:30:41 -07001208void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001209 int indexMin,
1210 int indexMax)
1211{
1212 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1213 if (indexMin < 0 || indexMin >= indexMax) {
1214 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1215 return;
1216 }
1217 mStreams[stream].mIndexMin = indexMin;
1218 mStreams[stream].mIndexMax = indexMax;
1219}
1220
Eric Laurente0720872014-03-11 09:30:41 -07001221status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001222 int index,
1223 audio_devices_t device)
1224{
1225
1226 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1227 return BAD_VALUE;
1228 }
1229 if (!audio_is_output_device(device)) {
1230 return BAD_VALUE;
1231 }
1232
1233 // Force max volume if stream cannot be muted
1234 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1235
1236 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1237 stream, device, index);
1238
1239 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1240 // clear all device specific values
1241 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1242 mStreams[stream].mIndexCur.clear();
1243 }
1244 mStreams[stream].mIndexCur.add(device, index);
1245
1246 // compute and apply stream volume on all outputs according to connected device
1247 status_t status = NO_ERROR;
1248 for (size_t i = 0; i < mOutputs.size(); i++) {
1249 audio_devices_t curDevice =
1250 getDeviceForVolume(mOutputs.valueAt(i)->device());
1251 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1252 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1253 if (volStatus != NO_ERROR) {
1254 status = volStatus;
1255 }
1256 }
1257 }
1258 return status;
1259}
1260
Eric Laurente0720872014-03-11 09:30:41 -07001261status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001262 int *index,
1263 audio_devices_t device)
1264{
1265 if (index == NULL) {
1266 return BAD_VALUE;
1267 }
1268 if (!audio_is_output_device(device)) {
1269 return BAD_VALUE;
1270 }
1271 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1272 // the strategy the stream belongs to.
1273 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1274 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1275 }
1276 device = getDeviceForVolume(device);
1277
1278 *index = mStreams[stream].getVolumeIndex(device);
1279 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1280 return NO_ERROR;
1281}
1282
Eric Laurente0720872014-03-11 09:30:41 -07001283audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001284 const SortedVector<audio_io_handle_t>& outputs)
1285{
1286 // select one output among several suitable for global effects.
1287 // The priority is as follows:
1288 // 1: An offloaded output. If the effect ends up not being offloadable,
1289 // AudioFlinger will invalidate the track and the offloaded output
1290 // will be closed causing the effect to be moved to a PCM output.
1291 // 2: A deep buffer output
1292 // 3: the first output in the list
1293
1294 if (outputs.size() == 0) {
1295 return 0;
1296 }
1297
1298 audio_io_handle_t outputOffloaded = 0;
1299 audio_io_handle_t outputDeepBuffer = 0;
1300
1301 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001302 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001303 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001304 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1305 outputOffloaded = outputs[i];
1306 }
1307 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1308 outputDeepBuffer = outputs[i];
1309 }
1310 }
1311
1312 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1313 outputOffloaded, outputDeepBuffer);
1314 if (outputOffloaded != 0) {
1315 return outputOffloaded;
1316 }
1317 if (outputDeepBuffer != 0) {
1318 return outputDeepBuffer;
1319 }
1320
1321 return outputs[0];
1322}
1323
Eric Laurente0720872014-03-11 09:30:41 -07001324audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001325{
1326 // apply simple rule where global effects are attached to the same output as MUSIC streams
1327
Eric Laurent3b73df72014-03-11 09:06:29 -07001328 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001329 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1330 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1331
1332 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1333 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1334 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1335
1336 return output;
1337}
1338
Eric Laurente0720872014-03-11 09:30:41 -07001339status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001340 audio_io_handle_t io,
1341 uint32_t strategy,
1342 int session,
1343 int id)
1344{
1345 ssize_t index = mOutputs.indexOfKey(io);
1346 if (index < 0) {
1347 index = mInputs.indexOfKey(io);
1348 if (index < 0) {
1349 ALOGW("registerEffect() unknown io %d", io);
1350 return INVALID_OPERATION;
1351 }
1352 }
1353
1354 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1355 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1356 desc->name, desc->memoryUsage);
1357 return INVALID_OPERATION;
1358 }
1359 mTotalEffectsMemory += desc->memoryUsage;
1360 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1361 desc->name, io, strategy, session, id);
1362 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1363
Eric Laurent1f2f2232014-06-02 12:01:23 -07001364 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1365 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1366 effectDesc->mIo = io;
1367 effectDesc->mStrategy = (routing_strategy)strategy;
1368 effectDesc->mSession = session;
1369 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001370
Eric Laurent1f2f2232014-06-02 12:01:23 -07001371 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001372
1373 return NO_ERROR;
1374}
1375
Eric Laurente0720872014-03-11 09:30:41 -07001376status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001377{
1378 ssize_t index = mEffects.indexOfKey(id);
1379 if (index < 0) {
1380 ALOGW("unregisterEffect() unknown effect ID %d", id);
1381 return INVALID_OPERATION;
1382 }
1383
Eric Laurent1f2f2232014-06-02 12:01:23 -07001384 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001385
Eric Laurent1f2f2232014-06-02 12:01:23 -07001386 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001387
Eric Laurent1f2f2232014-06-02 12:01:23 -07001388 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001389 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001390 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1391 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001392 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001393 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001394 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001395 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001396
1397 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001398
1399 return NO_ERROR;
1400}
1401
Eric Laurente0720872014-03-11 09:30:41 -07001402status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001403{
1404 ssize_t index = mEffects.indexOfKey(id);
1405 if (index < 0) {
1406 ALOGW("unregisterEffect() unknown effect ID %d", id);
1407 return INVALID_OPERATION;
1408 }
1409
1410 return setEffectEnabled(mEffects.valueAt(index), enabled);
1411}
1412
Eric Laurent1f2f2232014-06-02 12:01:23 -07001413status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001414{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001415 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001416 ALOGV("setEffectEnabled(%s) effect already %s",
1417 enabled?"true":"false", enabled?"enabled":"disabled");
1418 return INVALID_OPERATION;
1419 }
1420
1421 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001423 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001424 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001425 return INVALID_OPERATION;
1426 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001427 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001428 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1429 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001430 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001431 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001432 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1433 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001434 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001435 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001436 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1437 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001438 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001439 return NO_ERROR;
1440}
1441
Eric Laurente0720872014-03-11 09:30:41 -07001442bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001443{
1444 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001445 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1446 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1447 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001448 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001449 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001450 return true;
1451 }
1452 }
1453 return false;
1454}
1455
Eric Laurente0720872014-03-11 09:30:41 -07001456bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001457{
1458 nsecs_t sysTime = systemTime();
1459 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001460 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001461 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001462 return true;
1463 }
1464 }
1465 return false;
1466}
1467
Eric Laurente0720872014-03-11 09:30:41 -07001468bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001469 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001470{
1471 nsecs_t sysTime = systemTime();
1472 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001473 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001474 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001475 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001476 return true;
1477 }
1478 }
1479 return false;
1480}
1481
Eric Laurente0720872014-03-11 09:30:41 -07001482bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001483{
1484 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001485 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001486 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001487 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001488 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1489 && (inputDescriptor->mRefCount > 0)) {
1490 return true;
1491 }
1492 }
1493 return false;
1494}
1495
1496
Eric Laurente0720872014-03-11 09:30:41 -07001497status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001498{
1499 const size_t SIZE = 256;
1500 char buffer[SIZE];
1501 String8 result;
1502
1503 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1504 result.append(buffer);
1505
1506 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1507 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001508 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1509 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001510 snprintf(buffer, SIZE, " Force use for communications %d\n",
1511 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001512 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001513 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001514 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001515 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001516 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001517 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001518 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001519 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001520 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001521
Eric Laurent3a4311c2014-03-17 12:00:47 -07001522 snprintf(buffer, SIZE, " Available output devices:\n");
1523 result.append(buffer);
1524 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001525 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001526 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001527 }
1528 snprintf(buffer, SIZE, "\n Available input devices:\n");
1529 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001530 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001531 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001532 }
Eric Laurente552edb2014-03-10 17:42:56 -07001533
1534 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1535 write(fd, buffer, strlen(buffer));
1536 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001537 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001538 write(fd, buffer, strlen(buffer));
1539 mHwModules[i]->dump(fd);
1540 }
1541
1542 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1543 write(fd, buffer, strlen(buffer));
1544 for (size_t i = 0; i < mOutputs.size(); i++) {
1545 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1546 write(fd, buffer, strlen(buffer));
1547 mOutputs.valueAt(i)->dump(fd);
1548 }
1549
1550 snprintf(buffer, SIZE, "\nInputs dump:\n");
1551 write(fd, buffer, strlen(buffer));
1552 for (size_t i = 0; i < mInputs.size(); i++) {
1553 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1554 write(fd, buffer, strlen(buffer));
1555 mInputs.valueAt(i)->dump(fd);
1556 }
1557
1558 snprintf(buffer, SIZE, "\nStreams dump:\n");
1559 write(fd, buffer, strlen(buffer));
1560 snprintf(buffer, SIZE,
1561 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1562 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001563 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001564 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 write(fd, buffer, strlen(buffer));
1566 mStreams[i].dump(fd);
1567 }
1568
1569 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1570 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1571 write(fd, buffer, strlen(buffer));
1572
1573 snprintf(buffer, SIZE, "Registered effects:\n");
1574 write(fd, buffer, strlen(buffer));
1575 for (size_t i = 0; i < mEffects.size(); i++) {
1576 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1577 write(fd, buffer, strlen(buffer));
1578 mEffects.valueAt(i)->dump(fd);
1579 }
1580
1581
1582 return NO_ERROR;
1583}
1584
1585// This function checks for the parameters which can be offloaded.
1586// This can be enhanced depending on the capability of the DSP and policy
1587// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001588bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001589{
1590 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001591 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001592 offloadInfo.sample_rate, offloadInfo.channel_mask,
1593 offloadInfo.format,
1594 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1595 offloadInfo.has_video);
1596
1597 // Check if offload has been disabled
1598 char propValue[PROPERTY_VALUE_MAX];
1599 if (property_get("audio.offload.disable", propValue, "0")) {
1600 if (atoi(propValue) != 0) {
1601 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1602 return false;
1603 }
1604 }
1605
1606 // Check if stream type is music, then only allow offload as of now.
1607 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1608 {
1609 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1610 return false;
1611 }
1612
1613 //TODO: enable audio offloading with video when ready
1614 if (offloadInfo.has_video)
1615 {
1616 ALOGV("isOffloadSupported: has_video == true, returning false");
1617 return false;
1618 }
1619
1620 //If duration is less than minimum value defined in property, return false
1621 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1622 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1623 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1624 return false;
1625 }
1626 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1627 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1628 return false;
1629 }
1630
1631 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1632 // creating an offloaded track and tearing it down immediately after start when audioflinger
1633 // detects there is an active non offloadable effect.
1634 // FIXME: We should check the audio session here but we do not have it in this context.
1635 // This may prevent offloading in rare situations where effects are left active by apps
1636 // in the background.
1637 if (isNonOffloadableEffectEnabled()) {
1638 return false;
1639 }
1640
1641 // See if there is a profile to support this.
1642 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001643 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001644 offloadInfo.sample_rate,
1645 offloadInfo.format,
1646 offloadInfo.channel_mask,
1647 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001648 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1649 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001650}
1651
Eric Laurent6a94d692014-05-20 11:18:06 -07001652status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1653 audio_port_type_t type,
1654 unsigned int *num_ports,
1655 struct audio_port *ports,
1656 unsigned int *generation)
1657{
1658 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1659 generation == NULL) {
1660 return BAD_VALUE;
1661 }
1662 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1663 if (ports == NULL) {
1664 *num_ports = 0;
1665 }
1666
1667 size_t portsWritten = 0;
1668 size_t portsMax = *num_ports;
1669 *num_ports = 0;
1670 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1671 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1672 for (size_t i = 0;
1673 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1674 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1675 }
1676 *num_ports += mAvailableOutputDevices.size();
1677 }
1678 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1679 for (size_t i = 0;
1680 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1681 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1682 }
1683 *num_ports += mAvailableInputDevices.size();
1684 }
1685 }
1686 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1687 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1688 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1689 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1690 }
1691 *num_ports += mInputs.size();
1692 }
1693 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1694 for (size_t i = 0; i < mOutputs.size() && portsWritten < portsMax; i++) {
1695 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1696 }
1697 *num_ports += mOutputs.size();
1698 }
1699 }
1700 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001701 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001702 return NO_ERROR;
1703}
1704
1705status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1706{
1707 return NO_ERROR;
1708}
1709
Eric Laurent1f2f2232014-06-02 12:01:23 -07001710sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001711 audio_port_handle_t id) const
1712{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001713 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001714 for (size_t i = 0; i < mOutputs.size(); i++) {
1715 outputDesc = mOutputs.valueAt(i);
1716 if (outputDesc->mId == id) {
1717 break;
1718 }
1719 }
1720 return outputDesc;
1721}
1722
Eric Laurent1f2f2232014-06-02 12:01:23 -07001723sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001724 audio_port_handle_t id) const
1725{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001726 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001727 for (size_t i = 0; i < mInputs.size(); i++) {
1728 inputDesc = mInputs.valueAt(i);
1729 if (inputDesc->mId == id) {
1730 break;
1731 }
1732 }
1733 return inputDesc;
1734}
1735
Eric Laurent1f2f2232014-06-02 12:01:23 -07001736sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1737 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001738{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001739 sp <HwModule> module;
1740
Eric Laurent6a94d692014-05-20 11:18:06 -07001741 for (size_t i = 0; i < mHwModules.size(); i++) {
1742 if (mHwModules[i]->mHandle == 0) {
1743 continue;
1744 }
1745 if (audio_is_output_device(device)) {
1746 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1747 {
1748 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1749 return mHwModules[i];
1750 }
1751 }
1752 } else {
1753 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1754 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1755 device & ~AUDIO_DEVICE_BIT_IN) {
1756 return mHwModules[i];
1757 }
1758 }
1759 }
1760 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001761 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001762}
1763
Eric Laurent1f2f2232014-06-02 12:01:23 -07001764sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001765{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001766 sp <HwModule> module;
1767
Eric Laurent1afeecb2014-05-14 08:52:28 -07001768 for (size_t i = 0; i < mHwModules.size(); i++)
1769 {
1770 if (strcmp(mHwModules[i]->mName, name) == 0) {
1771 return mHwModules[i];
1772 }
1773 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001774 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001775}
1776
1777
Eric Laurent6a94d692014-05-20 11:18:06 -07001778status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1779 audio_patch_handle_t *handle,
1780 uid_t uid)
1781{
1782 ALOGV("createAudioPatch()");
1783
1784 if (handle == NULL || patch == NULL) {
1785 return BAD_VALUE;
1786 }
1787 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1788
1789 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1790 return INVALID_OPERATION;
1791 }
1792 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1793 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1794 return INVALID_OPERATION;
1795 }
1796
1797 sp<AudioPatch> patchDesc;
1798 ssize_t index = mAudioPatches.indexOfKey(*handle);
1799
1800 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1801 patch->sinks[0].type);
1802 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1803 patch->sources[0].role,
1804 patch->sources[0].type);
1805
1806 if (index >= 0) {
1807 patchDesc = mAudioPatches.valueAt(index);
1808 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1809 mUidCached, patchDesc->mUid, uid);
1810 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1811 return INVALID_OPERATION;
1812 }
1813 } else {
1814 *handle = 0;
1815 }
1816
1817 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1818 // TODO add support for mix to mix connection
1819 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1820 ALOGV("createAudioPatch() source mix sink not device");
1821 return BAD_VALUE;
1822 }
1823 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001824 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001825 if (outputDesc == NULL) {
1826 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1827 return BAD_VALUE;
1828 }
1829 if (patchDesc != 0) {
1830 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1831 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1832 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1833 return BAD_VALUE;
1834 }
1835 }
1836 sp<DeviceDescriptor> devDesc =
1837 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1838 if (devDesc == 0) {
1839 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1840 return BAD_VALUE;
1841 }
1842
1843 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1844 patch->sources[0].sample_rate,
1845 patch->sources[0].format,
1846 patch->sources[0].channel_mask,
1847 AUDIO_OUTPUT_FLAG_NONE)) {
1848 return INVALID_OPERATION;
1849 }
1850 // TODO: reconfigure output format and channels here
1851 ALOGV("createAudioPatch() setting device %08x on output %d",
1852 devDesc->mType, outputDesc->mIoHandle);
1853 setOutputDevice(outputDesc->mIoHandle,
1854 devDesc->mType,
1855 true,
1856 0,
1857 handle);
1858 index = mAudioPatches.indexOfKey(*handle);
1859 if (index >= 0) {
1860 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1861 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1862 }
1863 patchDesc = mAudioPatches.valueAt(index);
1864 patchDesc->mUid = uid;
1865 ALOGV("createAudioPatch() success");
1866 } else {
1867 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1868 return INVALID_OPERATION;
1869 }
1870 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1871 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1872 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001873 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001874 if (inputDesc == NULL) {
1875 return BAD_VALUE;
1876 }
1877 if (patchDesc != 0) {
1878 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1879 return BAD_VALUE;
1880 }
1881 }
1882 sp<DeviceDescriptor> devDesc =
1883 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1884 if (devDesc == 0) {
1885 return BAD_VALUE;
1886 }
1887
1888 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1889 patch->sinks[0].sample_rate,
1890 patch->sinks[0].format,
1891 patch->sinks[0].channel_mask,
1892 AUDIO_OUTPUT_FLAG_NONE)) {
1893 return INVALID_OPERATION;
1894 }
1895 // TODO: reconfigure output format and channels here
1896 ALOGV("createAudioPatch() setting device %08x on output %d",
1897 devDesc->mType, inputDesc->mIoHandle);
1898 setInputDevice(inputDesc->mIoHandle,
1899 devDesc->mType,
1900 true,
1901 handle);
1902 index = mAudioPatches.indexOfKey(*handle);
1903 if (index >= 0) {
1904 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1905 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1906 }
1907 patchDesc = mAudioPatches.valueAt(index);
1908 patchDesc->mUid = uid;
1909 ALOGV("createAudioPatch() success");
1910 } else {
1911 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1912 return INVALID_OPERATION;
1913 }
1914 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1915 // device to device connection
1916 if (patchDesc != 0) {
1917 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1918 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1919 return BAD_VALUE;
1920 }
1921 }
1922
1923 sp<DeviceDescriptor> srcDeviceDesc =
1924 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1925 sp<DeviceDescriptor> sinkDeviceDesc =
1926 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1927 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1928 return BAD_VALUE;
1929 }
1930 //update source and sink with our own data as the data passed in the patch may
1931 // be incomplete.
1932 struct audio_patch newPatch = *patch;
1933 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1934 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1935
1936 // TODO: add support for devices on different HW modules
1937 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1938 return INVALID_OPERATION;
1939 }
1940 // TODO: check from routing capabilities in config file and other conflicting patches
1941
1942 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1943 if (index >= 0) {
1944 afPatchHandle = patchDesc->mAfPatchHandle;
1945 }
1946
1947 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1948 &afPatchHandle,
1949 0);
1950 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1951 status, afPatchHandle);
1952 if (status == NO_ERROR) {
1953 if (index < 0) {
1954 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1955 &newPatch, uid);
1956 addAudioPatch(patchDesc->mHandle, patchDesc);
1957 } else {
1958 patchDesc->mPatch = newPatch;
1959 }
1960 patchDesc->mAfPatchHandle = afPatchHandle;
1961 *handle = patchDesc->mHandle;
1962 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001963 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001964 } else {
1965 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1966 status);
1967 return INVALID_OPERATION;
1968 }
1969 } else {
1970 return BAD_VALUE;
1971 }
1972 } else {
1973 return BAD_VALUE;
1974 }
1975 return NO_ERROR;
1976}
1977
1978status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1979 uid_t uid)
1980{
1981 ALOGV("releaseAudioPatch() patch %d", handle);
1982
1983 ssize_t index = mAudioPatches.indexOfKey(handle);
1984
1985 if (index < 0) {
1986 return BAD_VALUE;
1987 }
1988 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1989 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1990 mUidCached, patchDesc->mUid, uid);
1991 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1992 return INVALID_OPERATION;
1993 }
1994
1995 struct audio_patch *patch = &patchDesc->mPatch;
1996 patchDesc->mUid = mUidCached;
1997 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001998 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001999 if (outputDesc == NULL) {
2000 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2001 return BAD_VALUE;
2002 }
2003
2004 setOutputDevice(outputDesc->mIoHandle,
2005 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2006 true,
2007 0,
2008 NULL);
2009 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2010 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002011 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002012 if (inputDesc == NULL) {
2013 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2014 return BAD_VALUE;
2015 }
2016 setInputDevice(inputDesc->mIoHandle,
2017 getNewInputDevice(inputDesc->mIoHandle),
2018 true,
2019 NULL);
2020 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2021 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2022 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2023 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2024 status, patchDesc->mAfPatchHandle);
2025 removeAudioPatch(patchDesc->mHandle);
2026 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002027 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002028 } else {
2029 return BAD_VALUE;
2030 }
2031 } else {
2032 return BAD_VALUE;
2033 }
2034 return NO_ERROR;
2035}
2036
2037status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2038 struct audio_patch *patches,
2039 unsigned int *generation)
2040{
2041 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2042 generation == NULL) {
2043 return BAD_VALUE;
2044 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002045 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002046 *num_patches, patches, mAudioPatches.size());
2047 if (patches == NULL) {
2048 *num_patches = 0;
2049 }
2050
2051 size_t patchesWritten = 0;
2052 size_t patchesMax = *num_patches;
2053 for (size_t i = 0;
2054 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2055 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2056 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002057 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002058 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2059 }
2060 *num_patches = mAudioPatches.size();
2061
2062 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002063 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002064 return NO_ERROR;
2065}
2066
Eric Laurente1715a42014-05-20 11:30:42 -07002067status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002068{
Eric Laurente1715a42014-05-20 11:30:42 -07002069 ALOGV("setAudioPortConfig()");
2070
2071 if (config == NULL) {
2072 return BAD_VALUE;
2073 }
2074 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2075 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002076 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2077 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002078 }
2079
Eric Laurenta121f902014-06-03 13:32:54 -07002080 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002081 if (config->type == AUDIO_PORT_TYPE_MIX) {
2082 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002083 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002084 if (outputDesc == NULL) {
2085 return BAD_VALUE;
2086 }
Eric Laurenta121f902014-06-03 13:32:54 -07002087 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002088 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002089 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002090 if (inputDesc == NULL) {
2091 return BAD_VALUE;
2092 }
Eric Laurenta121f902014-06-03 13:32:54 -07002093 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002094 } else {
2095 return BAD_VALUE;
2096 }
2097 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2098 sp<DeviceDescriptor> deviceDesc;
2099 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2100 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2101 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2102 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2103 } else {
2104 return BAD_VALUE;
2105 }
2106 if (deviceDesc == NULL) {
2107 return BAD_VALUE;
2108 }
Eric Laurenta121f902014-06-03 13:32:54 -07002109 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002110 } else {
2111 return BAD_VALUE;
2112 }
2113
Eric Laurenta121f902014-06-03 13:32:54 -07002114 struct audio_port_config backupConfig;
2115 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2116 if (status == NO_ERROR) {
2117 struct audio_port_config newConfig;
2118 audioPortConfig->toAudioPortConfig(&newConfig, config);
2119 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002120 }
Eric Laurenta121f902014-06-03 13:32:54 -07002121 if (status != NO_ERROR) {
2122 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002123 }
Eric Laurente1715a42014-05-20 11:30:42 -07002124
2125 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002126}
2127
2128void AudioPolicyManager::clearAudioPatches(uid_t uid)
2129{
2130 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2131 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2132 if (patchDesc->mUid == uid) {
2133 // releaseAudioPatch() removes the patch from mAudioPatches
2134 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2135 i--;
2136 }
2137 }
2138 }
2139}
2140
2141status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2142 const sp<AudioPatch>& patch)
2143{
2144 ssize_t index = mAudioPatches.indexOfKey(handle);
2145
2146 if (index >= 0) {
2147 ALOGW("addAudioPatch() patch %d already in", handle);
2148 return ALREADY_EXISTS;
2149 }
2150 mAudioPatches.add(handle, patch);
2151 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2152 "sink handle %d",
2153 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2154 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2155 return NO_ERROR;
2156}
2157
2158status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2159{
2160 ssize_t index = mAudioPatches.indexOfKey(handle);
2161
2162 if (index < 0) {
2163 ALOGW("removeAudioPatch() patch %d not in", handle);
2164 return ALREADY_EXISTS;
2165 }
2166 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2167 mAudioPatches.valueAt(index)->mAfPatchHandle);
2168 mAudioPatches.removeItemsAt(index);
2169 return NO_ERROR;
2170}
2171
Eric Laurente552edb2014-03-10 17:42:56 -07002172// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002173// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002174// ----------------------------------------------------------------------------
2175
Eric Laurent3a4311c2014-03-17 12:00:47 -07002176uint32_t AudioPolicyManager::nextUniqueId()
2177{
2178 return android_atomic_inc(&mNextUniqueId);
2179}
2180
Eric Laurent6a94d692014-05-20 11:18:06 -07002181uint32_t AudioPolicyManager::nextAudioPortGeneration()
2182{
2183 return android_atomic_inc(&mAudioPortGeneration);
2184}
2185
Eric Laurente0720872014-03-11 09:30:41 -07002186AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002187 :
2188#ifdef AUDIO_POLICY_TEST
2189 Thread(false),
2190#endif //AUDIO_POLICY_TEST
2191 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002192 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002193 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2194 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002195 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002196 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2197 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002198{
Eric Laurent6a94d692014-05-20 11:18:06 -07002199 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002200 mpClientInterface = clientInterface;
2201
Eric Laurent3b73df72014-03-11 09:06:29 -07002202 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2203 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002204 }
2205
Eric Laurent1afeecb2014-05-14 08:52:28 -07002206 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002207 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2208 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2209 ALOGE("could not load audio policy configuration file, setting defaults");
2210 defaultAudioPolicyConfig();
2211 }
2212 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002213 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002214
2215 // must be done after reading the policy
2216 initializeVolumeCurves();
2217
2218 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002219 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2220 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002221 for (size_t i = 0; i < mHwModules.size(); i++) {
2222 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2223 if (mHwModules[i]->mHandle == 0) {
2224 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2225 continue;
2226 }
2227 // open all output streams needed to access attached devices
2228 // except for direct output streams that are only opened when they are actually
2229 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002230 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002231 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2232 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002233 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002234
Eric Laurent3a4311c2014-03-17 12:00:47 -07002235 if (outProfile->mSupportedDevices.isEmpty()) {
2236 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2237 continue;
2238 }
2239
2240 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2241 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002242 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002243 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002244
Eric Laurent1c333e22014-05-20 10:48:17 -07002245 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002246 audio_io_handle_t output = mpClientInterface->openOutput(
2247 outProfile->mModule->mHandle,
2248 &outputDesc->mDevice,
2249 &outputDesc->mSamplingRate,
2250 &outputDesc->mFormat,
2251 &outputDesc->mChannelMask,
2252 &outputDesc->mLatency,
2253 outputDesc->mFlags);
2254 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002255 ALOGW("Cannot open output stream for device %08x on hw module %s",
2256 outputDesc->mDevice,
2257 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002258 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002259 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002260 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002261 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002262 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002263 // give a valid ID to an attached device once confirmed it is reachable
2264 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2265 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002266 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002267 }
2268 }
Eric Laurente552edb2014-03-10 17:42:56 -07002269 if (mPrimaryOutput == 0 &&
2270 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2271 mPrimaryOutput = output;
2272 }
2273 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002274 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002275 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002276 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002277 true);
2278 }
2279 }
2280 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002281 // open input streams needed to access attached devices to validate
2282 // mAvailableInputDevices list
2283 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2284 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002285 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002286
Eric Laurent3a4311c2014-03-17 12:00:47 -07002287 if (inProfile->mSupportedDevices.isEmpty()) {
2288 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2289 continue;
2290 }
2291
2292 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2293 if (profileTypes & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002294 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002295
2296 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002297 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002298 audio_io_handle_t input = mpClientInterface->openInput(
2299 inProfile->mModule->mHandle,
2300 &inputDesc->mDevice,
2301 &inputDesc->mSamplingRate,
2302 &inputDesc->mFormat,
2303 &inputDesc->mChannelMask);
2304
2305 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002306 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002307 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002308 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002309 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002310 // give a valid ID to an attached device once confirmed it is reachable
2311 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2312 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002313 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002314 }
2315 }
2316 mpClientInterface->closeInput(input);
2317 } else {
2318 ALOGW("Cannot open input stream for device %08x on hw module %s",
2319 inputDesc->mDevice,
2320 mHwModules[i]->mName);
2321 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002322 }
2323 }
2324 }
2325 // make sure all attached devices have been allocated a unique ID
2326 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2327 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002328 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002329 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2330 continue;
2331 }
2332 i++;
2333 }
2334 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2335 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002336 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002337 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2338 continue;
2339 }
2340 i++;
2341 }
2342 // make sure default device is reachable
2343 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002344 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002345 }
Eric Laurente552edb2014-03-10 17:42:56 -07002346
2347 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2348
2349 updateDevicesAndOutputs();
2350
2351#ifdef AUDIO_POLICY_TEST
2352 if (mPrimaryOutput != 0) {
2353 AudioParameter outputCmd = AudioParameter();
2354 outputCmd.addInt(String8("set_id"), 0);
2355 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2356
2357 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2358 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002359 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2360 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002361 mTestLatencyMs = 0;
2362 mCurOutput = 0;
2363 mDirectOutput = false;
2364 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2365 mTestOutputs[i] = 0;
2366 }
2367
2368 const size_t SIZE = 256;
2369 char buffer[SIZE];
2370 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2371 run(buffer, ANDROID_PRIORITY_AUDIO);
2372 }
2373#endif //AUDIO_POLICY_TEST
2374}
2375
Eric Laurente0720872014-03-11 09:30:41 -07002376AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002377{
2378#ifdef AUDIO_POLICY_TEST
2379 exit();
2380#endif //AUDIO_POLICY_TEST
2381 for (size_t i = 0; i < mOutputs.size(); i++) {
2382 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002383 }
2384 for (size_t i = 0; i < mInputs.size(); i++) {
2385 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002386 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002387 mAvailableOutputDevices.clear();
2388 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002389 mOutputs.clear();
2390 mInputs.clear();
2391 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002392}
2393
Eric Laurente0720872014-03-11 09:30:41 -07002394status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002395{
2396 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2397}
2398
2399#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002400bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002401{
2402 ALOGV("entering threadLoop()");
2403 while (!exitPending())
2404 {
2405 String8 command;
2406 int valueInt;
2407 String8 value;
2408
2409 Mutex::Autolock _l(mLock);
2410 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2411
2412 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2413 AudioParameter param = AudioParameter(command);
2414
2415 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2416 valueInt != 0) {
2417 ALOGV("Test command %s received", command.string());
2418 String8 target;
2419 if (param.get(String8("target"), target) != NO_ERROR) {
2420 target = "Manager";
2421 }
2422 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2423 param.remove(String8("test_cmd_policy_output"));
2424 mCurOutput = valueInt;
2425 }
2426 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2427 param.remove(String8("test_cmd_policy_direct"));
2428 if (value == "false") {
2429 mDirectOutput = false;
2430 } else if (value == "true") {
2431 mDirectOutput = true;
2432 }
2433 }
2434 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2435 param.remove(String8("test_cmd_policy_input"));
2436 mTestInput = valueInt;
2437 }
2438
2439 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2440 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002441 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002442 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002443 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002444 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002445 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002446 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002447 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002448 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002449 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002450 if (target == "Manager") {
2451 mTestFormat = format;
2452 } else if (mTestOutputs[mCurOutput] != 0) {
2453 AudioParameter outputParam = AudioParameter();
2454 outputParam.addInt(String8("format"), format);
2455 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2456 }
2457 }
2458 }
2459 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2460 param.remove(String8("test_cmd_policy_channels"));
2461 int channels = 0;
2462
2463 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002464 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002465 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002466 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002467 }
2468 if (channels != 0) {
2469 if (target == "Manager") {
2470 mTestChannels = channels;
2471 } else if (mTestOutputs[mCurOutput] != 0) {
2472 AudioParameter outputParam = AudioParameter();
2473 outputParam.addInt(String8("channels"), channels);
2474 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2475 }
2476 }
2477 }
2478 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2479 param.remove(String8("test_cmd_policy_sampleRate"));
2480 if (valueInt >= 0 && valueInt <= 96000) {
2481 int samplingRate = valueInt;
2482 if (target == "Manager") {
2483 mTestSamplingRate = samplingRate;
2484 } else if (mTestOutputs[mCurOutput] != 0) {
2485 AudioParameter outputParam = AudioParameter();
2486 outputParam.addInt(String8("sampling_rate"), samplingRate);
2487 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2488 }
2489 }
2490 }
2491
2492 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2493 param.remove(String8("test_cmd_policy_reopen"));
2494
Eric Laurent1f2f2232014-06-02 12:01:23 -07002495 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002496 mpClientInterface->closeOutput(mPrimaryOutput);
2497
2498 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2499
Eric Laurente552edb2014-03-10 17:42:56 -07002500 mOutputs.removeItem(mPrimaryOutput);
2501
Eric Laurent1f2f2232014-06-02 12:01:23 -07002502 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002503 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2504 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2505 &outputDesc->mDevice,
2506 &outputDesc->mSamplingRate,
2507 &outputDesc->mFormat,
2508 &outputDesc->mChannelMask,
2509 &outputDesc->mLatency,
2510 outputDesc->mFlags);
2511 if (mPrimaryOutput == 0) {
2512 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2513 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2514 } else {
2515 AudioParameter outputCmd = AudioParameter();
2516 outputCmd.addInt(String8("set_id"), 0);
2517 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2518 addOutput(mPrimaryOutput, outputDesc);
2519 }
2520 }
2521
2522
2523 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2524 }
2525 }
2526 return false;
2527}
2528
Eric Laurente0720872014-03-11 09:30:41 -07002529void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002530{
2531 {
2532 AutoMutex _l(mLock);
2533 requestExit();
2534 mWaitWorkCV.signal();
2535 }
2536 requestExitAndWait();
2537}
2538
Eric Laurente0720872014-03-11 09:30:41 -07002539int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002540{
2541 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2542 if (output == mTestOutputs[i]) return i;
2543 }
2544 return 0;
2545}
2546#endif //AUDIO_POLICY_TEST
2547
2548// ---
2549
Eric Laurent1f2f2232014-06-02 12:01:23 -07002550void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002551{
Eric Laurent1c333e22014-05-20 10:48:17 -07002552 outputDesc->mIoHandle = output;
2553 outputDesc->mId = nextUniqueId();
2554 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002555 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002556}
2557
Eric Laurent1f2f2232014-06-02 12:01:23 -07002558void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002559{
Eric Laurent1c333e22014-05-20 10:48:17 -07002560 inputDesc->mIoHandle = input;
2561 inputDesc->mId = nextUniqueId();
2562 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002563 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002564}
Eric Laurente552edb2014-03-10 17:42:56 -07002565
Eric Laurent3a4311c2014-03-17 12:00:47 -07002566String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2567{
2568 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2569 return String8("a2dp_sink_address=")+address;
2570 }
2571 return address;
2572}
2573
Eric Laurente0720872014-03-11 09:30:41 -07002574status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002575 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002576 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002577 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002578{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002579 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002580
Eric Laurent3b73df72014-03-11 09:06:29 -07002581 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002582 // first list already open outputs that can be routed to this device
2583 for (size_t i = 0; i < mOutputs.size(); i++) {
2584 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002585 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002586 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2587 outputs.add(mOutputs.keyAt(i));
2588 }
2589 }
2590 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002591 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002592 for (size_t i = 0; i < mHwModules.size(); i++)
2593 {
2594 if (mHwModules[i]->mHandle == 0) {
2595 continue;
2596 }
2597 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2598 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002599 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002600 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002601 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2602 }
2603 }
2604 }
2605
2606 if (profiles.isEmpty() && outputs.isEmpty()) {
2607 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2608 return BAD_VALUE;
2609 }
2610
2611 // open outputs for matching profiles if needed. Direct outputs are also opened to
2612 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2613 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002614 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002615
2616 // nothing to do if one output is already opened for this profile
2617 size_t j;
2618 for (j = 0; j < mOutputs.size(); j++) {
2619 desc = mOutputs.valueAt(j);
2620 if (!desc->isDuplicated() && desc->mProfile == profile) {
2621 break;
2622 }
2623 }
2624 if (j != mOutputs.size()) {
2625 continue;
2626 }
2627
Eric Laurent3a4311c2014-03-17 12:00:47 -07002628 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002629 desc = new AudioOutputDescriptor(profile);
2630 desc->mDevice = device;
2631 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2632 offloadInfo.sample_rate = desc->mSamplingRate;
2633 offloadInfo.format = desc->mFormat;
2634 offloadInfo.channel_mask = desc->mChannelMask;
2635
2636 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2637 &desc->mDevice,
2638 &desc->mSamplingRate,
2639 &desc->mFormat,
2640 &desc->mChannelMask,
2641 &desc->mLatency,
2642 desc->mFlags,
2643 &offloadInfo);
2644 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002645 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002646 if (!address.isEmpty()) {
2647 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002648 }
2649
Eric Laurentd4692962014-05-05 18:13:44 -07002650 // Here is where we step through and resolve any "dynamic" fields
2651 String8 reply;
2652 char *value;
2653 if (profile->mSamplingRates[0] == 0) {
2654 reply = mpClientInterface->getParameters(output,
2655 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2656 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2657 reply.string());
2658 value = strpbrk((char *)reply.string(), "=");
2659 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002660 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002661 }
Eric Laurentd4692962014-05-05 18:13:44 -07002662 }
2663 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2664 reply = mpClientInterface->getParameters(output,
2665 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2666 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2667 reply.string());
2668 value = strpbrk((char *)reply.string(), "=");
2669 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002670 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002671 }
Eric Laurentd4692962014-05-05 18:13:44 -07002672 }
2673 if (profile->mChannelMasks[0] == 0) {
2674 reply = mpClientInterface->getParameters(output,
2675 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2676 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2677 reply.string());
2678 value = strpbrk((char *)reply.string(), "=");
2679 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002680 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002681 }
Eric Laurentd4692962014-05-05 18:13:44 -07002682 }
2683 if (((profile->mSamplingRates[0] == 0) &&
2684 (profile->mSamplingRates.size() < 2)) ||
2685 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2686 (profile->mFormats.size() < 2)) ||
2687 ((profile->mChannelMasks[0] == 0) &&
2688 (profile->mChannelMasks.size() < 2))) {
2689 ALOGW("checkOutputsForDevice() direct output missing param");
2690 mpClientInterface->closeOutput(output);
2691 output = 0;
2692 } else if (profile->mSamplingRates[0] == 0) {
2693 mpClientInterface->closeOutput(output);
2694 desc->mSamplingRate = profile->mSamplingRates[1];
2695 offloadInfo.sample_rate = desc->mSamplingRate;
2696 output = mpClientInterface->openOutput(
2697 profile->mModule->mHandle,
2698 &desc->mDevice,
2699 &desc->mSamplingRate,
2700 &desc->mFormat,
2701 &desc->mChannelMask,
2702 &desc->mLatency,
2703 desc->mFlags,
2704 &offloadInfo);
2705 }
2706
2707 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002708 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002709 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2710 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002711
Eric Laurentd4692962014-05-05 18:13:44 -07002712 // set initial stream volume for device
2713 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002714
Eric Laurentd4692962014-05-05 18:13:44 -07002715 //TODO: configure audio effect output stage here
2716
2717 // open a duplicating output thread for the new output and the primary output
2718 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2719 mPrimaryOutput);
2720 if (duplicatedOutput != 0) {
2721 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002722 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002723 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2724 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2725 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2726 dupOutputDesc->mFormat = desc->mFormat;
2727 dupOutputDesc->mChannelMask = desc->mChannelMask;
2728 dupOutputDesc->mLatency = desc->mLatency;
2729 addOutput(duplicatedOutput, dupOutputDesc);
2730 applyStreamVolumes(duplicatedOutput, device, 0, true);
2731 } else {
2732 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2733 mPrimaryOutput, output);
2734 mpClientInterface->closeOutput(output);
2735 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002736 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002737 output = 0;
2738 }
Eric Laurente552edb2014-03-10 17:42:56 -07002739 }
2740 }
2741 }
2742 if (output == 0) {
2743 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002744 profiles.removeAt(profile_index);
2745 profile_index--;
2746 } else {
2747 outputs.add(output);
2748 ALOGV("checkOutputsForDevice(): adding output %d", output);
2749 }
2750 }
2751
2752 if (profiles.isEmpty()) {
2753 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2754 return BAD_VALUE;
2755 }
Eric Laurentd4692962014-05-05 18:13:44 -07002756 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002757 // check if one opened output is not needed any more after disconnecting one device
2758 for (size_t i = 0; i < mOutputs.size(); i++) {
2759 desc = mOutputs.valueAt(i);
2760 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002761 !(desc->mProfile->mSupportedDevices.types() &
2762 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002763 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2764 outputs.add(mOutputs.keyAt(i));
2765 }
2766 }
Eric Laurentd4692962014-05-05 18:13:44 -07002767 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002768 for (size_t i = 0; i < mHwModules.size(); i++)
2769 {
2770 if (mHwModules[i]->mHandle == 0) {
2771 continue;
2772 }
2773 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2774 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002775 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002776 if (profile->mSupportedDevices.types() & device) {
2777 ALOGV("checkOutputsForDevice(): "
2778 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002779 if (profile->mSamplingRates[0] == 0) {
2780 profile->mSamplingRates.clear();
2781 profile->mSamplingRates.add(0);
2782 }
2783 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2784 profile->mFormats.clear();
2785 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2786 }
2787 if (profile->mChannelMasks[0] == 0) {
2788 profile->mChannelMasks.clear();
2789 profile->mChannelMasks.add(0);
2790 }
2791 }
2792 }
2793 }
2794 }
2795 return NO_ERROR;
2796}
2797
Eric Laurentd4692962014-05-05 18:13:44 -07002798status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2799 audio_policy_dev_state_t state,
2800 SortedVector<audio_io_handle_t>& inputs,
2801 const String8 address)
2802{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002803 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002804 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2805 // first list already open inputs that can be routed to this device
2806 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2807 desc = mInputs.valueAt(input_index);
2808 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2809 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2810 inputs.add(mInputs.keyAt(input_index));
2811 }
2812 }
2813
2814 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002815 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002816 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2817 {
2818 if (mHwModules[module_idx]->mHandle == 0) {
2819 continue;
2820 }
2821 for (size_t profile_index = 0;
2822 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2823 profile_index++)
2824 {
2825 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2826 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002827 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002828 profile_index, module_idx);
2829 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2830 }
2831 }
2832 }
2833
2834 if (profiles.isEmpty() && inputs.isEmpty()) {
2835 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2836 return BAD_VALUE;
2837 }
2838
2839 // open inputs for matching profiles if needed. Direct inputs are also opened to
2840 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2841 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2842
Eric Laurent1c333e22014-05-20 10:48:17 -07002843 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002844 // nothing to do if one input is already opened for this profile
2845 size_t input_index;
2846 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2847 desc = mInputs.valueAt(input_index);
2848 if (desc->mProfile == profile) {
2849 break;
2850 }
2851 }
2852 if (input_index != mInputs.size()) {
2853 continue;
2854 }
2855
2856 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2857 desc = new AudioInputDescriptor(profile);
2858 desc->mDevice = device;
2859
2860 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2861 &desc->mDevice,
2862 &desc->mSamplingRate,
2863 &desc->mFormat,
2864 &desc->mChannelMask);
2865
2866 if (input != 0) {
2867 if (!address.isEmpty()) {
2868 mpClientInterface->setParameters(input, addressToParameter(device, address));
2869 }
2870
2871 // Here is where we step through and resolve any "dynamic" fields
2872 String8 reply;
2873 char *value;
2874 if (profile->mSamplingRates[0] == 0) {
2875 reply = mpClientInterface->getParameters(input,
2876 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2877 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2878 reply.string());
2879 value = strpbrk((char *)reply.string(), "=");
2880 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002881 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002882 }
2883 }
2884 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2885 reply = mpClientInterface->getParameters(input,
2886 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2887 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2888 value = strpbrk((char *)reply.string(), "=");
2889 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002890 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002891 }
2892 }
2893 if (profile->mChannelMasks[0] == 0) {
2894 reply = mpClientInterface->getParameters(input,
2895 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2896 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2897 reply.string());
2898 value = strpbrk((char *)reply.string(), "=");
2899 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002900 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002901 }
2902 }
2903 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2904 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2905 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2906 ALOGW("checkInputsForDevice() direct input missing param");
2907 mpClientInterface->closeInput(input);
2908 input = 0;
2909 }
2910
2911 if (input != 0) {
2912 addInput(input, desc);
2913 }
2914 } // endif input != 0
2915
2916 if (input == 0) {
2917 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07002918 profiles.removeAt(profile_index);
2919 profile_index--;
2920 } else {
2921 inputs.add(input);
2922 ALOGV("checkInputsForDevice(): adding input %d", input);
2923 }
2924 } // end scan profiles
2925
2926 if (profiles.isEmpty()) {
2927 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2928 return BAD_VALUE;
2929 }
2930 } else {
2931 // Disconnect
2932 // check if one opened input is not needed any more after disconnecting one device
2933 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2934 desc = mInputs.valueAt(input_index);
2935 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2936 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2937 mInputs.keyAt(input_index));
2938 inputs.add(mInputs.keyAt(input_index));
2939 }
2940 }
2941 // Clear any profiles associated with the disconnected device.
2942 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2943 if (mHwModules[module_index]->mHandle == 0) {
2944 continue;
2945 }
2946 for (size_t profile_index = 0;
2947 profile_index < mHwModules[module_index]->mInputProfiles.size();
2948 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002949 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002950 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002951 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002952 profile_index, module_index);
2953 if (profile->mSamplingRates[0] == 0) {
2954 profile->mSamplingRates.clear();
2955 profile->mSamplingRates.add(0);
2956 }
2957 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2958 profile->mFormats.clear();
2959 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2960 }
2961 if (profile->mChannelMasks[0] == 0) {
2962 profile->mChannelMasks.clear();
2963 profile->mChannelMasks.add(0);
2964 }
2965 }
2966 }
2967 }
2968 } // end disconnect
2969
2970 return NO_ERROR;
2971}
2972
2973
Eric Laurente0720872014-03-11 09:30:41 -07002974void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002975{
2976 ALOGV("closeOutput(%d)", output);
2977
Eric Laurent1f2f2232014-06-02 12:01:23 -07002978 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07002979 if (outputDesc == NULL) {
2980 ALOGW("closeOutput() unknown output %d", output);
2981 return;
2982 }
2983
2984 // look for duplicated outputs connected to the output being removed.
2985 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002986 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002987 if (dupOutputDesc->isDuplicated() &&
2988 (dupOutputDesc->mOutput1 == outputDesc ||
2989 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002990 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07002991 if (dupOutputDesc->mOutput1 == outputDesc) {
2992 outputDesc2 = dupOutputDesc->mOutput2;
2993 } else {
2994 outputDesc2 = dupOutputDesc->mOutput1;
2995 }
2996 // As all active tracks on duplicated output will be deleted,
2997 // and as they were also referenced on the other output, the reference
2998 // count for their stream type must be adjusted accordingly on
2999 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003000 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003001 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003002 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003003 }
3004 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3005 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3006
3007 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003008 mOutputs.removeItem(duplicatedOutput);
3009 }
3010 }
3011
3012 AudioParameter param;
3013 param.add(String8("closing"), String8("true"));
3014 mpClientInterface->setParameters(output, param.toString());
3015
3016 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003017 mOutputs.removeItem(output);
3018 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003019 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003020}
3021
Eric Laurente0720872014-03-11 09:30:41 -07003022SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003023 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003024{
3025 SortedVector<audio_io_handle_t> outputs;
3026
3027 ALOGVV("getOutputsForDevice() device %04x", device);
3028 for (size_t i = 0; i < openOutputs.size(); i++) {
3029 ALOGVV("output %d isDuplicated=%d device=%04x",
3030 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3031 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3032 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3033 outputs.add(openOutputs.keyAt(i));
3034 }
3035 }
3036 return outputs;
3037}
3038
Eric Laurente0720872014-03-11 09:30:41 -07003039bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003040 SortedVector<audio_io_handle_t>& outputs2)
3041{
3042 if (outputs1.size() != outputs2.size()) {
3043 return false;
3044 }
3045 for (size_t i = 0; i < outputs1.size(); i++) {
3046 if (outputs1[i] != outputs2[i]) {
3047 return false;
3048 }
3049 }
3050 return true;
3051}
3052
Eric Laurente0720872014-03-11 09:30:41 -07003053void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003054{
3055 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3056 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3057 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3058 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3059
3060 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3061 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3062 strategy, srcOutputs[0], dstOutputs[0]);
3063 // mute strategy while moving tracks from one output to another
3064 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003065 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003066 if (desc->isStrategyActive(strategy)) {
3067 setStrategyMute(strategy, true, srcOutputs[i]);
3068 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3069 }
3070 }
3071
3072 // Move effects associated to this strategy from previous output to new output
3073 if (strategy == STRATEGY_MEDIA) {
3074 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3075 SortedVector<audio_io_handle_t> moved;
3076 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003077 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3078 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3079 effectDesc->mIo != fxOutput) {
3080 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003081 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3082 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003083 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003084 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003085 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003086 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003087 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003088 }
3089 }
3090 }
3091 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003092 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3093 if (getStrategy((audio_stream_type_t)i) == strategy) {
3094 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003095 }
3096 }
3097 }
3098}
3099
Eric Laurente0720872014-03-11 09:30:41 -07003100void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003101{
3102 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3103 checkOutputForStrategy(STRATEGY_PHONE);
3104 checkOutputForStrategy(STRATEGY_SONIFICATION);
3105 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3106 checkOutputForStrategy(STRATEGY_MEDIA);
3107 checkOutputForStrategy(STRATEGY_DTMF);
3108}
3109
Eric Laurente0720872014-03-11 09:30:41 -07003110audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003111{
Eric Laurente552edb2014-03-10 17:42:56 -07003112 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003113 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003114 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3115 return mOutputs.keyAt(i);
3116 }
3117 }
3118
3119 return 0;
3120}
3121
Eric Laurente0720872014-03-11 09:30:41 -07003122void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003123{
Eric Laurente552edb2014-03-10 17:42:56 -07003124 audio_io_handle_t a2dpOutput = getA2dpOutput();
3125 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003126 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003127 return;
3128 }
3129
Eric Laurent3a4311c2014-03-17 12:00:47 -07003130 bool isScoConnected =
3131 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003132 // suspend A2DP output if:
3133 // (NOT already suspended) &&
3134 // ((SCO device is connected &&
3135 // (forced usage for communication || for record is SCO))) ||
3136 // (phone state is ringing || in call)
3137 //
3138 // restore A2DP output if:
3139 // (Already suspended) &&
3140 // ((SCO device is NOT connected ||
3141 // (forced usage NOT for communication && NOT for record is SCO))) &&
3142 // (phone state is NOT ringing && NOT in call)
3143 //
3144 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003145 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003146 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3147 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3148 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3149 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003150
3151 mpClientInterface->restoreOutput(a2dpOutput);
3152 mA2dpSuspended = false;
3153 }
3154 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003155 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003156 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3157 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3158 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3159 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003160
3161 mpClientInterface->suspendOutput(a2dpOutput);
3162 mA2dpSuspended = true;
3163 }
3164 }
3165}
3166
Eric Laurent1c333e22014-05-20 10:48:17 -07003167audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003168{
3169 audio_devices_t device = AUDIO_DEVICE_NONE;
3170
Eric Laurent1f2f2232014-06-02 12:01:23 -07003171 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003172
3173 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3174 if (index >= 0) {
3175 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3176 if (patchDesc->mUid != mUidCached) {
3177 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3178 outputDesc->device(), outputDesc->mPatchHandle);
3179 return outputDesc->device();
3180 }
3181 }
3182
Eric Laurente552edb2014-03-10 17:42:56 -07003183 // check the following by order of priority to request a routing change if necessary:
3184 // 1: the strategy enforced audible is active on the output:
3185 // use device for strategy enforced audible
3186 // 2: we are in call or the strategy phone is active on the output:
3187 // use device for strategy phone
3188 // 3: the strategy sonification is active on the output:
3189 // use device for strategy sonification
3190 // 4: the strategy "respectful" sonification is active on the output:
3191 // use device for strategy "respectful" sonification
3192 // 5: the strategy media is active on the output:
3193 // use device for strategy media
3194 // 6: the strategy DTMF is active on the output:
3195 // use device for strategy DTMF
3196 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3197 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3198 } else if (isInCall() ||
3199 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3200 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3201 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3202 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3203 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3204 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3205 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3206 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3207 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3208 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3209 }
3210
Eric Laurent1c333e22014-05-20 10:48:17 -07003211 ALOGV("getNewOutputDevice() selected device %x", device);
3212 return device;
3213}
3214
3215audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3216{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003217 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003218
3219 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3220 if (index >= 0) {
3221 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3222 if (patchDesc->mUid != mUidCached) {
3223 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3224 inputDesc->mDevice, inputDesc->mPatchHandle);
3225 return inputDesc->mDevice;
3226 }
3227 }
3228
Eric Laurent1c333e22014-05-20 10:48:17 -07003229 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3230
3231 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003232 return device;
3233}
3234
Eric Laurente0720872014-03-11 09:30:41 -07003235uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003236 return (uint32_t)getStrategy(stream);
3237}
3238
Eric Laurente0720872014-03-11 09:30:41 -07003239audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003240 // By checking the range of stream before calling getStrategy, we avoid
3241 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3242 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003243 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003244 return AUDIO_DEVICE_NONE;
3245 }
3246 audio_devices_t devices;
3247 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3248 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3249 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3250 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003251 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003252 if (outputDesc->isStrategyActive(strategy)) {
3253 devices = outputDesc->device();
3254 break;
3255 }
Eric Laurente552edb2014-03-10 17:42:56 -07003256 }
3257 return devices;
3258}
3259
Eric Laurente0720872014-03-11 09:30:41 -07003260AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003261 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003262 // stream to strategy mapping
3263 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003264 case AUDIO_STREAM_VOICE_CALL:
3265 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003266 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003267 case AUDIO_STREAM_RING:
3268 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003269 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003270 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003271 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003272 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003273 return STRATEGY_DTMF;
3274 default:
3275 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003276 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003277 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3278 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003279 case AUDIO_STREAM_TTS:
3280 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003281 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003282 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003283 return STRATEGY_ENFORCED_AUDIBLE;
3284 }
3285}
3286
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003287uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3288 // flags to strategy mapping
3289 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3290 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3291 }
3292
3293 // usage to strategy mapping
3294 switch (attr->usage) {
3295 case AUDIO_USAGE_MEDIA:
3296 case AUDIO_USAGE_GAME:
3297 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3298 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3299 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3300 return (uint32_t) STRATEGY_MEDIA;
3301
3302 case AUDIO_USAGE_VOICE_COMMUNICATION:
3303 return (uint32_t) STRATEGY_PHONE;
3304
3305 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3306 return (uint32_t) STRATEGY_DTMF;
3307
3308 case AUDIO_USAGE_ALARM:
3309 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3310 return (uint32_t) STRATEGY_SONIFICATION;
3311
3312 case AUDIO_USAGE_NOTIFICATION:
3313 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3314 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3315 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3316 case AUDIO_USAGE_NOTIFICATION_EVENT:
3317 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3318
3319 case AUDIO_USAGE_UNKNOWN:
3320 default:
3321 return (uint32_t) STRATEGY_MEDIA;
3322 }
3323}
3324
Eric Laurente0720872014-03-11 09:30:41 -07003325void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003326 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003327 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003328 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3329 updateDevicesAndOutputs();
3330 break;
3331 default:
3332 break;
3333 }
3334}
3335
Eric Laurente0720872014-03-11 09:30:41 -07003336audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003337 bool fromCache)
3338{
3339 uint32_t device = AUDIO_DEVICE_NONE;
3340
3341 if (fromCache) {
3342 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3343 strategy, mDeviceForStrategy[strategy]);
3344 return mDeviceForStrategy[strategy];
3345 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003346 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003347 switch (strategy) {
3348
3349 case STRATEGY_SONIFICATION_RESPECTFUL:
3350 if (isInCall()) {
3351 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003352 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003353 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3354 // while media is playing on a remote device, use the the sonification behavior.
3355 // Note that we test this usecase before testing if media is playing because
3356 // the isStreamActive() method only informs about the activity of a stream, not
3357 // if it's for local playback. Note also that we use the same delay between both tests
3358 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003359 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003360 // while media is playing (or has recently played), use the same device
3361 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3362 } else {
3363 // when media is not playing anymore, fall back on the sonification behavior
3364 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3365 }
3366
3367 break;
3368
3369 case STRATEGY_DTMF:
3370 if (!isInCall()) {
3371 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3372 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3373 break;
3374 }
3375 // when in call, DTMF and PHONE strategies follow the same rules
3376 // FALL THROUGH
3377
3378 case STRATEGY_PHONE:
3379 // for phone strategy, we first consider the forced use and then the available devices by order
3380 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003381 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3382 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003383 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003384 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003385 if (device) break;
3386 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003387 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003388 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003389 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003390 if (device) break;
3391 // if SCO device is requested but no SCO device is available, fall back to default case
3392 // FALL THROUGH
3393
3394 default: // FORCE_NONE
3395 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003396 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003397 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003398 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003399 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003400 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003401 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003402 if (device) break;
3403 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003404 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003405 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003406 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003407 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003408 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003409 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003410 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003411 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003412 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003413 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003414 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003415 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003416 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003417 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003418 if (device) break;
3419 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003420 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003421 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003422 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003423 if (device == AUDIO_DEVICE_NONE) {
3424 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3425 }
3426 break;
3427
Eric Laurent3b73df72014-03-11 09:06:29 -07003428 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003429 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3430 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003431 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003432 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003433 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003434 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003435 if (device) break;
3436 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003437 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003438 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003439 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003440 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003441 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003442 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003443 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003444 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003445 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003446 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003447 if (device) break;
3448 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003449 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003450 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003451 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003452 if (device == AUDIO_DEVICE_NONE) {
3453 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3454 }
3455 break;
3456 }
3457 break;
3458
3459 case STRATEGY_SONIFICATION:
3460
3461 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3462 // handleIncallSonification().
3463 if (isInCall()) {
3464 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3465 break;
3466 }
3467 // FALL THROUGH
3468
3469 case STRATEGY_ENFORCED_AUDIBLE:
3470 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3471 // except:
3472 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3473 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3474
3475 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003476 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003477 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003478 if (device == AUDIO_DEVICE_NONE) {
3479 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3480 }
3481 }
3482 // The second device used for sonification is the same as the device used by media strategy
3483 // FALL THROUGH
3484
3485 case STRATEGY_MEDIA: {
3486 uint32_t device2 = AUDIO_DEVICE_NONE;
3487 if (strategy != STRATEGY_SONIFICATION) {
3488 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003489 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003490 }
3491 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003492 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003493 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003494 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003495 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003496 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003497 }
3498 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003499 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003500 }
3501 }
3502 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003503 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003504 }
3505 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003506 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003507 }
3508 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003509 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003510 }
3511 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003512 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003513 }
3514 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003515 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003516 }
3517 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3518 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003519 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003520 }
3521 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003522 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003523 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003524 }
3525 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003526 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003527 }
3528
3529 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3530 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3531 device |= device2;
3532 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003533 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003534 if (device == AUDIO_DEVICE_NONE) {
3535 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3536 }
3537 } break;
3538
3539 default:
3540 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3541 break;
3542 }
3543
3544 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3545 return device;
3546}
3547
Eric Laurente0720872014-03-11 09:30:41 -07003548void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003549{
3550 for (int i = 0; i < NUM_STRATEGIES; i++) {
3551 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3552 }
3553 mPreviousOutputs = mOutputs;
3554}
3555
Eric Laurent1f2f2232014-06-02 12:01:23 -07003556uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003557 audio_devices_t prevDevice,
3558 uint32_t delayMs)
3559{
3560 // mute/unmute strategies using an incompatible device combination
3561 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3562 // if unmuting, unmute only after the specified delay
3563 if (outputDesc->isDuplicated()) {
3564 return 0;
3565 }
3566
3567 uint32_t muteWaitMs = 0;
3568 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003569 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003570
3571 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3572 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3573 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3574 bool doMute = false;
3575
3576 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3577 doMute = true;
3578 outputDesc->mStrategyMutedByDevice[i] = true;
3579 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3580 doMute = true;
3581 outputDesc->mStrategyMutedByDevice[i] = false;
3582 }
Eric Laurent99401132014-05-07 19:48:15 -07003583 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003584 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003585 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003586 // skip output if it does not share any device with current output
3587 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3588 == AUDIO_DEVICE_NONE) {
3589 continue;
3590 }
3591 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3592 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3593 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3594 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3595 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003596 if (mute) {
3597 // FIXME: should not need to double latency if volume could be applied
3598 // immediately by the audioflinger mixer. We must account for the delay
3599 // between now and the next time the audioflinger thread for this output
3600 // will process a buffer (which corresponds to one buffer size,
3601 // usually 1/2 or 1/4 of the latency).
3602 if (muteWaitMs < desc->latency() * 2) {
3603 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003604 }
3605 }
3606 }
3607 }
3608 }
3609 }
3610
Eric Laurent99401132014-05-07 19:48:15 -07003611 // temporary mute output if device selection changes to avoid volume bursts due to
3612 // different per device volumes
3613 if (outputDesc->isActive() && (device != prevDevice)) {
3614 if (muteWaitMs < outputDesc->latency() * 2) {
3615 muteWaitMs = outputDesc->latency() * 2;
3616 }
3617 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3618 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003619 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003620 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003621 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003622 muteWaitMs *2, device);
3623 }
3624 }
3625 }
3626
Eric Laurente552edb2014-03-10 17:42:56 -07003627 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3628 if (muteWaitMs > delayMs) {
3629 muteWaitMs -= delayMs;
3630 usleep(muteWaitMs * 1000);
3631 return muteWaitMs;
3632 }
3633 return 0;
3634}
3635
Eric Laurente0720872014-03-11 09:30:41 -07003636uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003637 audio_devices_t device,
3638 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003639 int delayMs,
3640 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003641{
3642 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003643 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003644 AudioParameter param;
3645 uint32_t muteWaitMs;
3646
3647 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003648 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3649 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003650 return muteWaitMs;
3651 }
3652 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3653 // output profile
3654 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003655 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003656 return 0;
3657 }
3658
3659 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003660 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003661
3662 audio_devices_t prevDevice = outputDesc->mDevice;
3663
3664 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3665
3666 if (device != AUDIO_DEVICE_NONE) {
3667 outputDesc->mDevice = device;
3668 }
3669 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3670
3671 // Do not change the routing if:
3672 // - the requested device is AUDIO_DEVICE_NONE
3673 // - the requested device is the same as current device and force is not specified.
3674 // Doing this check here allows the caller to call setOutputDevice() without conditions
3675 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3676 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3677 return muteWaitMs;
3678 }
3679
3680 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003681
Eric Laurente552edb2014-03-10 17:42:56 -07003682 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003683 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003684 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003685 } else {
3686 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3687 if (!deviceList.isEmpty()) {
3688 struct audio_patch patch;
3689 outputDesc->toAudioPortConfig(&patch.sources[0]);
3690 patch.num_sources = 1;
3691 patch.num_sinks = 0;
3692 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3693 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003694 patch.num_sinks++;
3695 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003696 ssize_t index;
3697 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3698 index = mAudioPatches.indexOfKey(*patchHandle);
3699 } else {
3700 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3701 }
3702 sp< AudioPatch> patchDesc;
3703 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3704 if (index >= 0) {
3705 patchDesc = mAudioPatches.valueAt(index);
3706 afPatchHandle = patchDesc->mAfPatchHandle;
3707 }
3708
Eric Laurent1c333e22014-05-20 10:48:17 -07003709 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003710 &afPatchHandle,
3711 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003712 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3713 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003714 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003715 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003716 if (index < 0) {
3717 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3718 &patch, mUidCached);
3719 addAudioPatch(patchDesc->mHandle, patchDesc);
3720 } else {
3721 patchDesc->mPatch = patch;
3722 }
3723 patchDesc->mAfPatchHandle = afPatchHandle;
3724 patchDesc->mUid = mUidCached;
3725 if (patchHandle) {
3726 *patchHandle = patchDesc->mHandle;
3727 }
3728 outputDesc->mPatchHandle = patchDesc->mHandle;
3729 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003730 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003731 }
3732 }
3733 }
Eric Laurente552edb2014-03-10 17:42:56 -07003734
3735 // update stream volumes according to new device
3736 applyStreamVolumes(output, device, delayMs);
3737
3738 return muteWaitMs;
3739}
3740
Eric Laurent1c333e22014-05-20 10:48:17 -07003741status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003742 int delayMs,
3743 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003744{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003745 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003746 ssize_t index;
3747 if (patchHandle) {
3748 index = mAudioPatches.indexOfKey(*patchHandle);
3749 } else {
3750 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3751 }
3752 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003753 return INVALID_OPERATION;
3754 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003755 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3756 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003757 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3758 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003759 removeAudioPatch(patchDesc->mHandle);
3760 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003761 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003762 return status;
3763}
3764
3765status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3766 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003767 bool force,
3768 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003769{
3770 status_t status = NO_ERROR;
3771
Eric Laurent1f2f2232014-06-02 12:01:23 -07003772 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003773 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3774 inputDesc->mDevice = device;
3775
3776 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3777 if (!deviceList.isEmpty()) {
3778 struct audio_patch patch;
3779 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3780 patch.num_sinks = 1;
3781 //only one input device for now
3782 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003783 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003784 ssize_t index;
3785 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3786 index = mAudioPatches.indexOfKey(*patchHandle);
3787 } else {
3788 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3789 }
3790 sp< AudioPatch> patchDesc;
3791 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3792 if (index >= 0) {
3793 patchDesc = mAudioPatches.valueAt(index);
3794 afPatchHandle = patchDesc->mAfPatchHandle;
3795 }
3796
Eric Laurent1c333e22014-05-20 10:48:17 -07003797 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003798 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003799 0);
3800 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003801 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003802 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003803 if (index < 0) {
3804 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3805 &patch, mUidCached);
3806 addAudioPatch(patchDesc->mHandle, patchDesc);
3807 } else {
3808 patchDesc->mPatch = patch;
3809 }
3810 patchDesc->mAfPatchHandle = afPatchHandle;
3811 patchDesc->mUid = mUidCached;
3812 if (patchHandle) {
3813 *patchHandle = patchDesc->mHandle;
3814 }
3815 inputDesc->mPatchHandle = patchDesc->mHandle;
3816 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003817 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003818 }
3819 }
3820 }
3821 return status;
3822}
3823
Eric Laurent6a94d692014-05-20 11:18:06 -07003824status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3825 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003826{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003827 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003828 ssize_t index;
3829 if (patchHandle) {
3830 index = mAudioPatches.indexOfKey(*patchHandle);
3831 } else {
3832 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3833 }
3834 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003835 return INVALID_OPERATION;
3836 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003837 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3838 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003839 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3840 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003841 removeAudioPatch(patchDesc->mHandle);
3842 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003843 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003844 return status;
3845}
3846
3847sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003848 uint32_t samplingRate,
3849 audio_format_t format,
3850 audio_channel_mask_t channelMask)
3851{
3852 // Choose an input profile based on the requested capture parameters: select the first available
3853 // profile supporting all requested parameters.
3854
3855 for (size_t i = 0; i < mHwModules.size(); i++)
3856 {
3857 if (mHwModules[i]->mHandle == 0) {
3858 continue;
3859 }
3860 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3861 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003862 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003863 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003864 if (profile->isCompatibleProfile(device, samplingRate, format,
3865 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3866 return profile;
3867 }
3868 }
3869 }
3870 return NULL;
3871}
3872
Eric Laurente0720872014-03-11 09:30:41 -07003873audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003874{
3875 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003876 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3877 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003878 switch (inputSource) {
3879 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003880 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003881 device = AUDIO_DEVICE_IN_VOICE_CALL;
3882 break;
3883 }
3884 // FALL THROUGH
3885
3886 case AUDIO_SOURCE_DEFAULT:
3887 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003888 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3889 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3890 break;
3891 }
3892 // FALL THROUGH
3893
Eric Laurente552edb2014-03-10 17:42:56 -07003894 case AUDIO_SOURCE_VOICE_RECOGNITION:
3895 case AUDIO_SOURCE_HOTWORD:
3896 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003897 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003898 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003899 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003900 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003901 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003902 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3903 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003904 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003905 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3906 }
3907 break;
3908 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003909 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003910 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003911 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003912 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3913 }
3914 break;
3915 case AUDIO_SOURCE_VOICE_DOWNLINK:
3916 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003917 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003918 device = AUDIO_DEVICE_IN_VOICE_CALL;
3919 }
3920 break;
3921 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003922 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003923 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3924 }
3925 break;
3926 default:
3927 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3928 break;
3929 }
3930 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3931 return device;
3932}
3933
Eric Laurente0720872014-03-11 09:30:41 -07003934bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003935{
3936 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3937 device &= ~AUDIO_DEVICE_BIT_IN;
3938 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3939 return true;
3940 }
3941 return false;
3942}
3943
Eric Laurente0720872014-03-11 09:30:41 -07003944audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003945{
3946 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003947 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003948 if ((input_descriptor->mRefCount > 0)
3949 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3950 return mInputs.keyAt(i);
3951 }
3952 }
3953 return 0;
3954}
3955
3956
Eric Laurente0720872014-03-11 09:30:41 -07003957audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003958{
3959 if (device == AUDIO_DEVICE_NONE) {
3960 // this happens when forcing a route update and no track is active on an output.
3961 // In this case the returned category is not important.
3962 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003963 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003964 // Multiple device selection is either:
3965 // - speaker + one other device: give priority to speaker in this case.
3966 // - one A2DP device + another device: happens with duplicated output. In this case
3967 // retain the device on the A2DP output as the other must not correspond to an active
3968 // selection if not the speaker.
3969 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3970 device = AUDIO_DEVICE_OUT_SPEAKER;
3971 } else {
3972 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3973 }
3974 }
3975
Eric Laurent3b73df72014-03-11 09:06:29 -07003976 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003977 "getDeviceForVolume() invalid device combination: %08x",
3978 device);
3979
3980 return device;
3981}
3982
Eric Laurente0720872014-03-11 09:30:41 -07003983AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003984{
3985 switch(getDeviceForVolume(device)) {
3986 case AUDIO_DEVICE_OUT_EARPIECE:
3987 return DEVICE_CATEGORY_EARPIECE;
3988 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3989 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3990 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3991 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3992 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3993 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3994 return DEVICE_CATEGORY_HEADSET;
3995 case AUDIO_DEVICE_OUT_SPEAKER:
3996 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3997 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3998 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3999 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4000 case AUDIO_DEVICE_OUT_USB_DEVICE:
4001 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4002 default:
4003 return DEVICE_CATEGORY_SPEAKER;
4004 }
4005}
4006
Eric Laurente0720872014-03-11 09:30:41 -07004007float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004008 int indexInUi)
4009{
4010 device_category deviceCategory = getDeviceCategory(device);
4011 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4012
4013 // the volume index in the UI is relative to the min and max volume indices for this stream type
4014 int nbSteps = 1 + curve[VOLMAX].mIndex -
4015 curve[VOLMIN].mIndex;
4016 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4017 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4018
4019 // find what part of the curve this index volume belongs to, or if it's out of bounds
4020 int segment = 0;
4021 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4022 return 0.0f;
4023 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4024 segment = 0;
4025 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4026 segment = 1;
4027 } else if (volIdx <= curve[VOLMAX].mIndex) {
4028 segment = 2;
4029 } else { // out of bounds
4030 return 1.0f;
4031 }
4032
4033 // linear interpolation in the attenuation table in dB
4034 float decibels = curve[segment].mDBAttenuation +
4035 ((float)(volIdx - curve[segment].mIndex)) *
4036 ( (curve[segment+1].mDBAttenuation -
4037 curve[segment].mDBAttenuation) /
4038 ((float)(curve[segment+1].mIndex -
4039 curve[segment].mIndex)) );
4040
4041 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4042
4043 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4044 curve[segment].mIndex, volIdx,
4045 curve[segment+1].mIndex,
4046 curve[segment].mDBAttenuation,
4047 decibels,
4048 curve[segment+1].mDBAttenuation,
4049 amplification);
4050
4051 return amplification;
4052}
4053
Eric Laurente0720872014-03-11 09:30:41 -07004054const AudioPolicyManager::VolumeCurvePoint
4055 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004056 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4057};
4058
Eric Laurente0720872014-03-11 09:30:41 -07004059const AudioPolicyManager::VolumeCurvePoint
4060 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004061 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4062};
4063
Eric Laurente0720872014-03-11 09:30:41 -07004064const AudioPolicyManager::VolumeCurvePoint
4065 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004066 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4067};
4068
Eric Laurente0720872014-03-11 09:30:41 -07004069const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004070 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
4071 {1, -56.0f}, {20, -34.0f}, {86, -10.0f}, {100, 0.0f}
4072};
4073
4074const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004075 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004076 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4077};
4078
Eric Laurente0720872014-03-11 09:30:41 -07004079const AudioPolicyManager::VolumeCurvePoint
4080 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004081 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4082};
4083
4084// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4085// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4086// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4087// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4088
Eric Laurente0720872014-03-11 09:30:41 -07004089const AudioPolicyManager::VolumeCurvePoint
4090 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004091 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4092};
4093
Eric Laurente0720872014-03-11 09:30:41 -07004094const AudioPolicyManager::VolumeCurvePoint
4095 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004096 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4097};
4098
Eric Laurente0720872014-03-11 09:30:41 -07004099const AudioPolicyManager::VolumeCurvePoint
4100 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004101 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4102};
4103
Eric Laurente0720872014-03-11 09:30:41 -07004104const AudioPolicyManager::VolumeCurvePoint
4105 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004106 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4107};
4108
Eric Laurente0720872014-03-11 09:30:41 -07004109const AudioPolicyManager::VolumeCurvePoint
4110 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004111 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4112};
4113
Eric Laurente0720872014-03-11 09:30:41 -07004114const AudioPolicyManager::VolumeCurvePoint
4115 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4116 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004117 { // AUDIO_STREAM_VOICE_CALL
4118 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4119 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4120 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4121 },
4122 { // AUDIO_STREAM_SYSTEM
4123 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4124 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4125 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4126 },
4127 { // AUDIO_STREAM_RING
4128 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4129 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4130 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4131 },
4132 { // AUDIO_STREAM_MUSIC
4133 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4134 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4135 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4136 },
4137 { // AUDIO_STREAM_ALARM
4138 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4139 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4140 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4141 },
4142 { // AUDIO_STREAM_NOTIFICATION
4143 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4144 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4145 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4146 },
4147 { // AUDIO_STREAM_BLUETOOTH_SCO
4148 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4149 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4150 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4151 },
4152 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4153 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4154 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4155 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4156 },
4157 { // AUDIO_STREAM_DTMF
4158 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4159 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4160 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4161 },
4162 { // AUDIO_STREAM_TTS
4163 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4164 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4165 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4166 },
4167};
4168
Eric Laurente0720872014-03-11 09:30:41 -07004169void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004170{
4171 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4172 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4173 mStreams[i].mVolumeCurve[j] =
4174 sVolumeProfiles[i][j];
4175 }
4176 }
4177
4178 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4179 if (mSpeakerDrcEnabled) {
4180 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4181 sDefaultSystemVolumeCurveDrc;
4182 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4183 sSpeakerSonificationVolumeCurveDrc;
4184 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4185 sSpeakerSonificationVolumeCurveDrc;
4186 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4187 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004188 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4189 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004190 }
4191}
4192
Eric Laurente0720872014-03-11 09:30:41 -07004193float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004194 int index,
4195 audio_io_handle_t output,
4196 audio_devices_t device)
4197{
4198 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004199 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004200 StreamDescriptor &streamDesc = mStreams[stream];
4201
4202 if (device == AUDIO_DEVICE_NONE) {
4203 device = outputDesc->device();
4204 }
4205
4206 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004207 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004208 index != mStreams[stream].mIndexMin &&
4209 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
4210 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
4211 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
4212 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
4213 return 1.0;
4214 }
4215
4216 volume = volIndexToAmpl(device, streamDesc, index);
4217
4218 // if a headset is connected, apply the following rules to ring tones and notifications
4219 // to avoid sound level bursts in user's ears:
4220 // - always attenuate ring tones and notifications volume by 6dB
4221 // - if music is playing, always limit the volume to current music volume,
4222 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004223 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004224 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4225 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4226 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4227 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4228 ((stream_strategy == STRATEGY_SONIFICATION)
4229 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004230 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004231 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004232 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004233 streamDesc.mCanBeMuted) {
4234 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4235 // when the phone is ringing we must consider that music could have been paused just before
4236 // by the music application and behave as if music was active if the last music track was
4237 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004238 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004239 mLimitRingtoneVolume) {
4240 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004241 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4242 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004243 output,
4244 musicDevice);
4245 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4246 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4247 if (volume > minVol) {
4248 volume = minVol;
4249 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4250 }
4251 }
4252 }
4253
4254 return volume;
4255}
4256
Eric Laurente0720872014-03-11 09:30:41 -07004257status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004258 int index,
4259 audio_io_handle_t output,
4260 audio_devices_t device,
4261 int delayMs,
4262 bool force)
4263{
4264
4265 // do not change actual stream volume if the stream is muted
4266 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4267 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4268 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4269 return NO_ERROR;
4270 }
4271
4272 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004273 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4274 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4275 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4276 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004277 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004278 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004279 return INVALID_OPERATION;
4280 }
4281
4282 float volume = computeVolume(stream, index, output, device);
4283 // We actually change the volume if:
4284 // - the float value returned by computeVolume() changed
4285 // - the force flag is set
4286 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4287 force) {
4288 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4289 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4290 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4291 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004292 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4293 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004294 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004295 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004296 }
4297
Eric Laurent3b73df72014-03-11 09:06:29 -07004298 if (stream == AUDIO_STREAM_VOICE_CALL ||
4299 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004300 float voiceVolume;
4301 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004302 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004303 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4304 } else {
4305 voiceVolume = 1.0;
4306 }
4307
4308 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4309 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4310 mLastVoiceVolume = voiceVolume;
4311 }
4312 }
4313
4314 return NO_ERROR;
4315}
4316
Eric Laurente0720872014-03-11 09:30:41 -07004317void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004318 audio_devices_t device,
4319 int delayMs,
4320 bool force)
4321{
4322 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4323
Eric Laurent3b73df72014-03-11 09:06:29 -07004324 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4325 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004326 mStreams[stream].getVolumeIndex(device),
4327 output,
4328 device,
4329 delayMs,
4330 force);
4331 }
4332}
4333
Eric Laurente0720872014-03-11 09:30:41 -07004334void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004335 bool on,
4336 audio_io_handle_t output,
4337 int delayMs,
4338 audio_devices_t device)
4339{
4340 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004341 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4342 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4343 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
4345 }
4346}
4347
Eric Laurente0720872014-03-11 09:30:41 -07004348void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004349 bool on,
4350 audio_io_handle_t output,
4351 int delayMs,
4352 audio_devices_t device)
4353{
4354 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004355 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004356 if (device == AUDIO_DEVICE_NONE) {
4357 device = outputDesc->device();
4358 }
4359
4360 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4361 stream, on, output, outputDesc->mMuteCount[stream], device);
4362
4363 if (on) {
4364 if (outputDesc->mMuteCount[stream] == 0) {
4365 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004366 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4367 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004368 checkAndSetVolume(stream, 0, output, device, delayMs);
4369 }
4370 }
4371 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4372 outputDesc->mMuteCount[stream]++;
4373 } else {
4374 if (outputDesc->mMuteCount[stream] == 0) {
4375 ALOGV("setStreamMute() unmuting non muted stream!");
4376 return;
4377 }
4378 if (--outputDesc->mMuteCount[stream] == 0) {
4379 checkAndSetVolume(stream,
4380 streamDesc.getVolumeIndex(device),
4381 output,
4382 device,
4383 delayMs);
4384 }
4385 }
4386}
4387
Eric Laurente0720872014-03-11 09:30:41 -07004388void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004389 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004390{
4391 // if the stream pertains to sonification strategy and we are in call we must
4392 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4393 // in the device used for phone strategy and play the tone if the selected device does not
4394 // interfere with the device used for phone strategy
4395 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4396 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004397 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004398 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4399 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004400 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004401 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4402 stream, starting, outputDesc->mDevice, stateChange);
4403 if (outputDesc->mRefCount[stream]) {
4404 int muteCount = 1;
4405 if (stateChange) {
4406 muteCount = outputDesc->mRefCount[stream];
4407 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004408 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004409 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4410 for (int i = 0; i < muteCount; i++) {
4411 setStreamMute(stream, starting, mPrimaryOutput);
4412 }
4413 } else {
4414 ALOGV("handleIncallSonification() high visibility");
4415 if (outputDesc->device() &
4416 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4417 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4418 for (int i = 0; i < muteCount; i++) {
4419 setStreamMute(stream, starting, mPrimaryOutput);
4420 }
4421 }
4422 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004423 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4424 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004425 } else {
4426 mpClientInterface->stopTone();
4427 }
4428 }
4429 }
4430 }
4431}
4432
Eric Laurente0720872014-03-11 09:30:41 -07004433bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004434{
4435 return isStateInCall(mPhoneState);
4436}
4437
Eric Laurente0720872014-03-11 09:30:41 -07004438bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004439 return ((state == AUDIO_MODE_IN_CALL) ||
4440 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004441}
4442
Eric Laurente0720872014-03-11 09:30:41 -07004443uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004444{
4445 return MAX_EFFECTS_CPU_LOAD;
4446}
4447
Eric Laurente0720872014-03-11 09:30:41 -07004448uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004449{
4450 return MAX_EFFECTS_MEMORY;
4451}
4452
Eric Laurent6a94d692014-05-20 11:18:06 -07004453
Eric Laurente552edb2014-03-10 17:42:56 -07004454// --- AudioOutputDescriptor class implementation
4455
Eric Laurente0720872014-03-11 09:30:41 -07004456AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004457 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004458 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004459 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004460 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4461{
4462 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004463 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004464 mRefCount[i] = 0;
4465 mCurVolume[i] = -1.0;
4466 mMuteCount[i] = 0;
4467 mStopTime[i] = 0;
4468 }
4469 for (int i = 0; i < NUM_STRATEGIES; i++) {
4470 mStrategyMutedByDevice[i] = false;
4471 }
4472 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004473 mAudioPort = profile;
Eric Laurente552edb2014-03-10 17:42:56 -07004474 mSamplingRate = profile->mSamplingRates[0];
4475 mFormat = profile->mFormats[0];
4476 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004477 if (profile->mGains.size() > 0) {
4478 profile->mGains[0]->getDefaultConfig(&mGain);
4479 }
Eric Laurente552edb2014-03-10 17:42:56 -07004480 mFlags = profile->mFlags;
4481 }
4482}
4483
Eric Laurente0720872014-03-11 09:30:41 -07004484audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004485{
4486 if (isDuplicated()) {
4487 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4488 } else {
4489 return mDevice;
4490 }
4491}
4492
Eric Laurente0720872014-03-11 09:30:41 -07004493uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004494{
4495 if (isDuplicated()) {
4496 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4497 } else {
4498 return mLatency;
4499 }
4500}
4501
Eric Laurente0720872014-03-11 09:30:41 -07004502bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004503 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004504{
4505 if (isDuplicated()) {
4506 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4507 } else if (outputDesc->isDuplicated()){
4508 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4509 } else {
4510 return (mProfile->mModule == outputDesc->mProfile->mModule);
4511 }
4512}
4513
Eric Laurente0720872014-03-11 09:30:41 -07004514void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004515 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004516{
4517 // forward usage count change to attached outputs
4518 if (isDuplicated()) {
4519 mOutput1->changeRefCount(stream, delta);
4520 mOutput2->changeRefCount(stream, delta);
4521 }
4522 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004523 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4524 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004525 mRefCount[stream] = 0;
4526 return;
4527 }
4528 mRefCount[stream] += delta;
4529 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4530}
4531
Eric Laurente0720872014-03-11 09:30:41 -07004532audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004533{
4534 if (isDuplicated()) {
4535 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4536 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004537 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004538 }
4539}
4540
Eric Laurente0720872014-03-11 09:30:41 -07004541bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004542{
4543 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4544}
4545
Eric Laurente0720872014-03-11 09:30:41 -07004546bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004547 uint32_t inPastMs,
4548 nsecs_t sysTime) const
4549{
4550 if ((sysTime == 0) && (inPastMs != 0)) {
4551 sysTime = systemTime();
4552 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004553 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4554 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004555 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004556 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004557 return true;
4558 }
4559 }
4560 return false;
4561}
4562
Eric Laurente0720872014-03-11 09:30:41 -07004563bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004564 uint32_t inPastMs,
4565 nsecs_t sysTime) const
4566{
4567 if (mRefCount[stream] != 0) {
4568 return true;
4569 }
4570 if (inPastMs == 0) {
4571 return false;
4572 }
4573 if (sysTime == 0) {
4574 sysTime = systemTime();
4575 }
4576 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4577 return true;
4578 }
4579 return false;
4580}
4581
Eric Laurent1c333e22014-05-20 10:48:17 -07004582void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004583 struct audio_port_config *dstConfig,
4584 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004585{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004586 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4587 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4588 if (srcConfig != NULL) {
4589 dstConfig->config_mask &= srcConfig->config_mask;
4590 }
4591 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4592
Eric Laurent6a94d692014-05-20 11:18:06 -07004593 dstConfig->id = mId;
4594 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4595 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4597 dstConfig->ext.mix.handle = mIoHandle;
4598 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004599}
4600
4601void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4602 struct audio_port *port) const
4603{
4604 mProfile->toAudioPort(port);
4605 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004606 toAudioPortConfig(&port->active_config);
4607 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004608 port->ext.mix.handle = mIoHandle;
4609 port->ext.mix.latency_class =
4610 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4611}
Eric Laurente552edb2014-03-10 17:42:56 -07004612
Eric Laurente0720872014-03-11 09:30:41 -07004613status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004614{
4615 const size_t SIZE = 256;
4616 char buffer[SIZE];
4617 String8 result;
4618
4619 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4620 result.append(buffer);
4621 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4622 result.append(buffer);
4623 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4624 result.append(buffer);
4625 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4626 result.append(buffer);
4627 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4628 result.append(buffer);
4629 snprintf(buffer, SIZE, " Devices %08x\n", device());
4630 result.append(buffer);
4631 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4632 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004633 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4634 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4635 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004636 result.append(buffer);
4637 }
4638 write(fd, result.string(), result.size());
4639
4640 return NO_ERROR;
4641}
4642
4643// --- AudioInputDescriptor class implementation
4644
Eric Laurent1c333e22014-05-20 10:48:17 -07004645AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004646 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004647 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004648 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004649{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004650 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004651 mAudioPort = profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004652 mSamplingRate = profile->mSamplingRates[0];
4653 mFormat = profile->mFormats[0];
4654 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004655 if (profile->mGains.size() > 0) {
4656 profile->mGains[0]->getDefaultConfig(&mGain);
4657 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004658 } else {
4659 mSamplingRate = 0;
4660 mFormat = AUDIO_FORMAT_DEFAULT;
4661 mChannelMask = 0;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004662 }
Eric Laurente552edb2014-03-10 17:42:56 -07004663}
4664
Eric Laurent1c333e22014-05-20 10:48:17 -07004665void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004666 struct audio_port_config *dstConfig,
4667 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004668{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004669 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4670 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4671 if (srcConfig != NULL) {
4672 dstConfig->config_mask &= srcConfig->config_mask;
4673 }
4674
4675 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4676
Eric Laurent6a94d692014-05-20 11:18:06 -07004677 dstConfig->id = mId;
4678 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4679 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004680 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4681 dstConfig->ext.mix.handle = mIoHandle;
4682 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004683}
4684
4685void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4686 struct audio_port *port) const
4687{
4688 mProfile->toAudioPort(port);
4689 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 toAudioPortConfig(&port->active_config);
4691 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004692 port->ext.mix.handle = mIoHandle;
4693 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4694}
4695
Eric Laurente0720872014-03-11 09:30:41 -07004696status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004697{
4698 const size_t SIZE = 256;
4699 char buffer[SIZE];
4700 String8 result;
4701
4702 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4703 result.append(buffer);
4704 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4705 result.append(buffer);
4706 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4707 result.append(buffer);
4708 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4709 result.append(buffer);
4710 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4711 result.append(buffer);
4712 write(fd, result.string(), result.size());
4713
4714 return NO_ERROR;
4715}
4716
4717// --- StreamDescriptor class implementation
4718
Eric Laurente0720872014-03-11 09:30:41 -07004719AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004720 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4721{
4722 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4723}
4724
Eric Laurente0720872014-03-11 09:30:41 -07004725int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004726{
Eric Laurente0720872014-03-11 09:30:41 -07004727 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004728 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4729 if (mIndexCur.indexOfKey(device) < 0) {
4730 device = AUDIO_DEVICE_OUT_DEFAULT;
4731 }
4732 return mIndexCur.valueFor(device);
4733}
4734
Eric Laurente0720872014-03-11 09:30:41 -07004735void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004736{
4737 const size_t SIZE = 256;
4738 char buffer[SIZE];
4739 String8 result;
4740
4741 snprintf(buffer, SIZE, "%s %02d %02d ",
4742 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4743 result.append(buffer);
4744 for (size_t i = 0; i < mIndexCur.size(); i++) {
4745 snprintf(buffer, SIZE, "%04x : %02d, ",
4746 mIndexCur.keyAt(i),
4747 mIndexCur.valueAt(i));
4748 result.append(buffer);
4749 }
4750 result.append("\n");
4751
4752 write(fd, result.string(), result.size());
4753}
4754
4755// --- EffectDescriptor class implementation
4756
Eric Laurente0720872014-03-11 09:30:41 -07004757status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004758{
4759 const size_t SIZE = 256;
4760 char buffer[SIZE];
4761 String8 result;
4762
4763 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4764 result.append(buffer);
4765 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4766 result.append(buffer);
4767 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4768 result.append(buffer);
4769 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4770 result.append(buffer);
4771 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4772 result.append(buffer);
4773 write(fd, result.string(), result.size());
4774
4775 return NO_ERROR;
4776}
4777
Eric Laurent1c333e22014-05-20 10:48:17 -07004778// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004779
Eric Laurente0720872014-03-11 09:30:41 -07004780AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004781 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4782 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004783{
4784}
4785
Eric Laurente0720872014-03-11 09:30:41 -07004786AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004787{
4788 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004789 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004790 }
4791 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004792 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004793 }
4794 free((void *)mName);
4795}
4796
Eric Laurent1afeecb2014-05-14 08:52:28 -07004797status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4798{
4799 cnode *node = root->first_child;
4800
4801 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4802
4803 while (node) {
4804 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4805 profile->loadSamplingRates((char *)node->value);
4806 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4807 profile->loadFormats((char *)node->value);
4808 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4809 profile->loadInChannels((char *)node->value);
4810 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4811 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4812 mDeclaredDevices);
4813 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4814 profile->loadGains(node);
4815 }
4816 node = node->next;
4817 }
4818 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4819 "loadInput() invalid supported devices");
4820 ALOGW_IF(profile->mChannelMasks.size() == 0,
4821 "loadInput() invalid supported channel masks");
4822 ALOGW_IF(profile->mSamplingRates.size() == 0,
4823 "loadInput() invalid supported sampling rates");
4824 ALOGW_IF(profile->mFormats.size() == 0,
4825 "loadInput() invalid supported formats");
4826 if (!profile->mSupportedDevices.isEmpty() &&
4827 (profile->mChannelMasks.size() != 0) &&
4828 (profile->mSamplingRates.size() != 0) &&
4829 (profile->mFormats.size() != 0)) {
4830
4831 ALOGV("loadInput() adding input Supported Devices %04x",
4832 profile->mSupportedDevices.types());
4833
4834 mInputProfiles.add(profile);
4835 return NO_ERROR;
4836 } else {
4837 return BAD_VALUE;
4838 }
4839}
4840
4841status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4842{
4843 cnode *node = root->first_child;
4844
4845 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4846
4847 while (node) {
4848 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4849 profile->loadSamplingRates((char *)node->value);
4850 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4851 profile->loadFormats((char *)node->value);
4852 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4853 profile->loadOutChannels((char *)node->value);
4854 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4855 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4856 mDeclaredDevices);
4857 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4858 profile->mFlags = parseFlagNames((char *)node->value);
4859 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4860 profile->loadGains(node);
4861 }
4862 node = node->next;
4863 }
4864 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4865 "loadOutput() invalid supported devices");
4866 ALOGW_IF(profile->mChannelMasks.size() == 0,
4867 "loadOutput() invalid supported channel masks");
4868 ALOGW_IF(profile->mSamplingRates.size() == 0,
4869 "loadOutput() invalid supported sampling rates");
4870 ALOGW_IF(profile->mFormats.size() == 0,
4871 "loadOutput() invalid supported formats");
4872 if (!profile->mSupportedDevices.isEmpty() &&
4873 (profile->mChannelMasks.size() != 0) &&
4874 (profile->mSamplingRates.size() != 0) &&
4875 (profile->mFormats.size() != 0)) {
4876
4877 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4878 profile->mSupportedDevices.types(), profile->mFlags);
4879
4880 mOutputProfiles.add(profile);
4881 return NO_ERROR;
4882 } else {
4883 return BAD_VALUE;
4884 }
4885}
4886
4887status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4888{
4889 cnode *node = root->first_child;
4890
4891 audio_devices_t type = AUDIO_DEVICE_NONE;
4892 while (node) {
4893 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4894 type = parseDeviceNames((char *)node->value);
4895 break;
4896 }
4897 node = node->next;
4898 }
4899 if (type == AUDIO_DEVICE_NONE ||
4900 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4901 ALOGW("loadDevice() bad type %08x", type);
4902 return BAD_VALUE;
4903 }
4904 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4905 deviceDesc->mModule = this;
4906
4907 node = root->first_child;
4908 while (node) {
4909 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4910 deviceDesc->mAddress = String8((char *)node->value);
4911 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4912 if (audio_is_input_device(type)) {
4913 deviceDesc->loadInChannels((char *)node->value);
4914 } else {
4915 deviceDesc->loadOutChannels((char *)node->value);
4916 }
4917 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4918 deviceDesc->loadGains(node);
4919 }
4920 node = node->next;
4921 }
4922
4923 ALOGV("loadDevice() adding device name %s type %08x address %s",
4924 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4925
4926 mDeclaredDevices.add(deviceDesc);
4927
4928 return NO_ERROR;
4929}
4930
Eric Laurente0720872014-03-11 09:30:41 -07004931void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004932{
4933 const size_t SIZE = 256;
4934 char buffer[SIZE];
4935 String8 result;
4936
4937 snprintf(buffer, SIZE, " - name: %s\n", mName);
4938 result.append(buffer);
4939 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4940 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07004941 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
4942 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07004943 write(fd, result.string(), result.size());
4944 if (mOutputProfiles.size()) {
4945 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4946 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004947 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004948 write(fd, buffer, strlen(buffer));
4949 mOutputProfiles[i]->dump(fd);
4950 }
4951 }
4952 if (mInputProfiles.size()) {
4953 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4954 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004955 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004956 write(fd, buffer, strlen(buffer));
4957 mInputProfiles[i]->dump(fd);
4958 }
4959 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07004960 if (mDeclaredDevices.size()) {
4961 write(fd, " - devices:\n", strlen(" - devices:\n"));
4962 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
4963 mDeclaredDevices[i]->dump(fd, 4, i);
4964 }
4965 }
Eric Laurente552edb2014-03-10 17:42:56 -07004966}
4967
Eric Laurent1c333e22014-05-20 10:48:17 -07004968// --- AudioPort class implementation
4969
Eric Laurenta121f902014-06-03 13:32:54 -07004970
4971AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
4972 audio_port_role_t role, const sp<HwModule>& module) :
4973 mName(name), mType(type), mRole(role), mModule(module)
4974{
4975 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
4976 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
4977}
4978
Eric Laurent1c333e22014-05-20 10:48:17 -07004979void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
4980{
4981 port->role = mRole;
4982 port->type = mType;
4983 unsigned int i;
4984 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
4985 port->sample_rates[i] = mSamplingRates[i];
4986 }
4987 port->num_sample_rates = i;
4988 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
4989 port->channel_masks[i] = mChannelMasks[i];
4990 }
4991 port->num_channel_masks = i;
4992 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
4993 port->formats[i] = mFormats[i];
4994 }
4995 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07004996
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004997 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07004998
4999 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5000 port->gains[i] = mGains[i]->mGain;
5001 }
5002 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005003}
5004
5005
5006void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5007{
5008 char *str = strtok(name, "|");
5009
5010 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5011 // rates should be read from the output stream after it is opened for the first time
5012 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5013 mSamplingRates.add(0);
5014 return;
5015 }
5016
5017 while (str != NULL) {
5018 uint32_t rate = atoi(str);
5019 if (rate != 0) {
5020 ALOGV("loadSamplingRates() adding rate %d", rate);
5021 mSamplingRates.add(rate);
5022 }
5023 str = strtok(NULL, "|");
5024 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005025}
5026
5027void AudioPolicyManager::AudioPort::loadFormats(char *name)
5028{
5029 char *str = strtok(name, "|");
5030
5031 // by convention, "0' in the first entry in mFormats indicates the supported formats
5032 // should be read from the output stream after it is opened for the first time
5033 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5034 mFormats.add(AUDIO_FORMAT_DEFAULT);
5035 return;
5036 }
5037
5038 while (str != NULL) {
5039 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5040 ARRAY_SIZE(sFormatNameToEnumTable),
5041 str);
5042 if (format != AUDIO_FORMAT_DEFAULT) {
5043 mFormats.add(format);
5044 }
5045 str = strtok(NULL, "|");
5046 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005047}
5048
5049void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5050{
5051 const char *str = strtok(name, "|");
5052
5053 ALOGV("loadInChannels() %s", name);
5054
5055 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5056 mChannelMasks.add(0);
5057 return;
5058 }
5059
5060 while (str != NULL) {
5061 audio_channel_mask_t channelMask =
5062 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5063 ARRAY_SIZE(sInChannelsNameToEnumTable),
5064 str);
5065 if (channelMask != 0) {
5066 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5067 mChannelMasks.add(channelMask);
5068 }
5069 str = strtok(NULL, "|");
5070 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005071}
5072
5073void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5074{
5075 const char *str = strtok(name, "|");
5076
5077 ALOGV("loadOutChannels() %s", name);
5078
5079 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5080 // masks should be read from the output stream after it is opened for the first time
5081 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5082 mChannelMasks.add(0);
5083 return;
5084 }
5085
5086 while (str != NULL) {
5087 audio_channel_mask_t channelMask =
5088 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5089 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5090 str);
5091 if (channelMask != 0) {
5092 mChannelMasks.add(channelMask);
5093 }
5094 str = strtok(NULL, "|");
5095 }
5096 return;
5097}
5098
Eric Laurent1afeecb2014-05-14 08:52:28 -07005099audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5100{
5101 const char *str = strtok(name, "|");
5102
5103 ALOGV("loadGainMode() %s", name);
5104 audio_gain_mode_t mode = 0;
5105 while (str != NULL) {
5106 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5107 ARRAY_SIZE(sGainModeNameToEnumTable),
5108 str);
5109 str = strtok(NULL, "|");
5110 }
5111 return mode;
5112}
5113
Eric Laurenta121f902014-06-03 13:32:54 -07005114void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005115{
5116 cnode *node = root->first_child;
5117
Eric Laurenta121f902014-06-03 13:32:54 -07005118 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005119
5120 while (node) {
5121 if (strcmp(node->name, GAIN_MODE) == 0) {
5122 gain->mGain.mode = loadGainMode((char *)node->value);
5123 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005124 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005125 gain->mGain.channel_mask =
5126 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5127 ARRAY_SIZE(sInChannelsNameToEnumTable),
5128 (char *)node->value);
5129 } else {
5130 gain->mGain.channel_mask =
5131 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5132 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5133 (char *)node->value);
5134 }
5135 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5136 gain->mGain.min_value = atoi((char *)node->value);
5137 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5138 gain->mGain.max_value = atoi((char *)node->value);
5139 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5140 gain->mGain.default_value = atoi((char *)node->value);
5141 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5142 gain->mGain.step_value = atoi((char *)node->value);
5143 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5144 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5145 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5146 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5147 }
5148 node = node->next;
5149 }
5150
5151 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5152 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5153
5154 if (gain->mGain.mode == 0) {
5155 return;
5156 }
5157 mGains.add(gain);
5158}
5159
5160void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5161{
5162 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005163 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005164 while (node) {
5165 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005166 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005167 node = node->next;
5168 }
5169}
5170
Eric Laurenta121f902014-06-03 13:32:54 -07005171status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const
5172{
5173 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5174 if (mSamplingRates[i] == samplingRate) {
5175 return NO_ERROR;
5176 }
5177 }
5178 return BAD_VALUE;
5179}
5180
5181status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const
5182{
5183 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5184 if (mChannelMasks[i] == channelMask) {
5185 return NO_ERROR;
5186 }
5187 }
5188 return BAD_VALUE;
5189}
5190
5191status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5192{
5193 for (size_t i = 0; i < mFormats.size(); i ++) {
5194 if (mFormats[i] == format) {
5195 return NO_ERROR;
5196 }
5197 }
5198 return BAD_VALUE;
5199}
5200
5201status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5202 int index) const
5203{
5204 if (index < 0 || (size_t)index >= mGains.size()) {
5205 return BAD_VALUE;
5206 }
5207 return mGains[index]->checkConfig(gainConfig);
5208}
5209
Eric Laurent1afeecb2014-05-14 08:52:28 -07005210void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5211{
5212 const size_t SIZE = 256;
5213 char buffer[SIZE];
5214 String8 result;
5215
5216 if (mName.size() != 0) {
5217 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5218 result.append(buffer);
5219 }
5220
5221 if (mSamplingRates.size() != 0) {
5222 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5223 result.append(buffer);
5224 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5225 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5226 result.append(buffer);
5227 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5228 }
5229 result.append("\n");
5230 }
5231
5232 if (mChannelMasks.size() != 0) {
5233 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5234 result.append(buffer);
5235 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5236 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5237 result.append(buffer);
5238 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5239 }
5240 result.append("\n");
5241 }
5242
5243 if (mFormats.size() != 0) {
5244 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5245 result.append(buffer);
5246 for (size_t i = 0; i < mFormats.size(); i++) {
5247 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5248 ARRAY_SIZE(sFormatNameToEnumTable),
5249 mFormats[i]));
5250 result.append(buffer);
5251 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5252 }
5253 result.append("\n");
5254 }
5255 write(fd, result.string(), result.size());
5256 if (mGains.size() != 0) {
5257 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5258 write(fd, buffer, strlen(buffer) + 1);
5259 result.append(buffer);
5260 for (size_t i = 0; i < mGains.size(); i++) {
5261 mGains[i]->dump(fd, spaces + 2, i);
5262 }
5263 }
5264}
5265
5266// --- AudioGain class implementation
5267
Eric Laurenta121f902014-06-03 13:32:54 -07005268AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005269{
Eric Laurenta121f902014-06-03 13:32:54 -07005270 mIndex = index;
5271 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005272 memset(&mGain, 0, sizeof(struct audio_gain));
5273}
5274
Eric Laurenta121f902014-06-03 13:32:54 -07005275void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5276{
5277 config->index = mIndex;
5278 config->mode = mGain.mode;
5279 config->channel_mask = mGain.channel_mask;
5280 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5281 config->values[0] = mGain.default_value;
5282 } else {
5283 uint32_t numValues;
5284 if (mUseInChannelMask) {
5285 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5286 } else {
5287 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5288 }
5289 for (size_t i = 0; i < numValues; i++) {
5290 config->values[i] = mGain.default_value;
5291 }
5292 }
5293 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5294 config->ramp_duration_ms = mGain.min_ramp_ms;
5295 }
5296}
5297
5298status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5299{
5300 if ((config->mode & ~mGain.mode) != 0) {
5301 return BAD_VALUE;
5302 }
5303 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5304 if ((config->values[0] < mGain.min_value) ||
5305 (config->values[0] > mGain.max_value)) {
5306 return BAD_VALUE;
5307 }
5308 } else {
5309 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5310 return BAD_VALUE;
5311 }
5312 uint32_t numValues;
5313 if (mUseInChannelMask) {
5314 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5315 } else {
5316 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5317 }
5318 for (size_t i = 0; i < numValues; i++) {
5319 if ((config->values[i] < mGain.min_value) ||
5320 (config->values[i] > mGain.max_value)) {
5321 return BAD_VALUE;
5322 }
5323 }
5324 }
5325 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5326 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5327 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5328 return BAD_VALUE;
5329 }
5330 }
5331 return NO_ERROR;
5332}
5333
Eric Laurent1afeecb2014-05-14 08:52:28 -07005334void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5335{
5336 const size_t SIZE = 256;
5337 char buffer[SIZE];
5338 String8 result;
5339
5340 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5341 result.append(buffer);
5342 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5343 result.append(buffer);
5344 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5345 result.append(buffer);
5346 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5347 result.append(buffer);
5348 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5349 result.append(buffer);
5350 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5351 result.append(buffer);
5352 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5353 result.append(buffer);
5354 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5355 result.append(buffer);
5356 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5357 result.append(buffer);
5358
5359 write(fd, result.string(), result.size());
5360}
5361
Eric Laurent1f2f2232014-06-02 12:01:23 -07005362// --- AudioPortConfig class implementation
5363
5364AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5365{
5366 mSamplingRate = 0;
5367 mChannelMask = AUDIO_CHANNEL_NONE;
5368 mFormat = AUDIO_FORMAT_INVALID;
5369 mGain.index = -1;
5370}
5371
Eric Laurenta121f902014-06-03 13:32:54 -07005372status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5373 const struct audio_port_config *config,
5374 struct audio_port_config *backupConfig)
5375{
5376 struct audio_port_config localBackupConfig;
5377 status_t status = NO_ERROR;
5378
5379 localBackupConfig.config_mask = config->config_mask;
5380 toAudioPortConfig(&localBackupConfig);
5381
5382 if (mAudioPort == 0) {
5383 status = NO_INIT;
5384 goto exit;
5385 }
5386 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5387 status = mAudioPort->checkSamplingRate(config->sample_rate);
5388 if (status != NO_ERROR) {
5389 goto exit;
5390 }
5391 mSamplingRate = config->sample_rate;
5392 }
5393 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5394 status = mAudioPort->checkChannelMask(config->channel_mask);
5395 if (status != NO_ERROR) {
5396 goto exit;
5397 }
5398 mChannelMask = config->channel_mask;
5399 }
5400 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5401 status = mAudioPort->checkFormat(config->format);
5402 if (status != NO_ERROR) {
5403 goto exit;
5404 }
5405 mFormat = config->format;
5406 }
5407 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5408 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5409 if (status != NO_ERROR) {
5410 goto exit;
5411 }
5412 mGain = config->gain;
5413 }
5414
5415exit:
5416 if (status != NO_ERROR) {
5417 applyAudioPortConfig(&localBackupConfig);
5418 }
5419 if (backupConfig != NULL) {
5420 *backupConfig = localBackupConfig;
5421 }
5422 return status;
5423}
5424
Eric Laurent1f2f2232014-06-02 12:01:23 -07005425void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5426 struct audio_port_config *dstConfig,
5427 const struct audio_port_config *srcConfig) const
5428{
5429 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5430 dstConfig->sample_rate = mSamplingRate;
5431 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5432 dstConfig->sample_rate = srcConfig->sample_rate;
5433 }
5434 } else {
5435 dstConfig->sample_rate = 0;
5436 }
5437 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5438 dstConfig->channel_mask = mChannelMask;
5439 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5440 dstConfig->channel_mask = srcConfig->channel_mask;
5441 }
5442 } else {
5443 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5444 }
5445 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5446 dstConfig->format = mFormat;
5447 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5448 dstConfig->format = srcConfig->format;
5449 }
5450 } else {
5451 dstConfig->format = AUDIO_FORMAT_INVALID;
5452 }
5453 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5454 dstConfig->gain = mGain;
5455 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5456 dstConfig->gain = srcConfig->gain;
5457 }
5458 } else {
5459 dstConfig->gain.index = -1;
5460 }
5461 if (dstConfig->gain.index != -1) {
5462 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5463 } else {
5464 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5465 }
5466}
5467
Eric Laurent1c333e22014-05-20 10:48:17 -07005468// --- IOProfile class implementation
5469
Eric Laurent1afeecb2014-05-14 08:52:28 -07005470AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005471 const sp<HwModule>& module)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005472 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005473{
5474}
5475
Eric Laurente0720872014-03-11 09:30:41 -07005476AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005477{
5478}
5479
5480// checks if the IO profile is compatible with specified parameters.
5481// Sampling rate, format and channel mask must be specified in order to
5482// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005483bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005484 uint32_t samplingRate,
5485 audio_format_t format,
5486 audio_channel_mask_t channelMask,
5487 audio_output_flags_t flags) const
5488{
5489 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5490 return false;
5491 }
5492
Eric Laurent3a4311c2014-03-17 12:00:47 -07005493 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005494 return false;
5495 }
5496 if ((mFlags & flags) != flags) {
5497 return false;
5498 }
Eric Laurenta121f902014-06-03 13:32:54 -07005499 if (checkSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005500 return false;
5501 }
Eric Laurenta121f902014-06-03 13:32:54 -07005502 if (checkChannelMask(channelMask) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005503 return false;
5504 }
Eric Laurenta121f902014-06-03 13:32:54 -07005505 if (checkFormat(format) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005506 return false;
5507 }
5508 return true;
5509}
5510
Eric Laurente0720872014-03-11 09:30:41 -07005511void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005512{
5513 const size_t SIZE = 256;
5514 char buffer[SIZE];
5515 String8 result;
5516
Eric Laurent1afeecb2014-05-14 08:52:28 -07005517 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005518
Eric Laurente552edb2014-03-10 17:42:56 -07005519 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5520 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005521 snprintf(buffer, SIZE, " - devices:\n");
5522 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005523 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005524 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5525 mSupportedDevices[i]->dump(fd, 6, i);
5526 }
Eric Laurente552edb2014-03-10 17:42:56 -07005527}
5528
Eric Laurentd4692962014-05-05 18:13:44 -07005529void AudioPolicyManager::IOProfile::log()
5530{
5531 const size_t SIZE = 256;
5532 char buffer[SIZE];
5533 String8 result;
5534
5535 ALOGV(" - sampling rates: ");
5536 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5537 ALOGV(" %d", mSamplingRates[i]);
5538 }
5539
5540 ALOGV(" - channel masks: ");
5541 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5542 ALOGV(" 0x%04x", mChannelMasks[i]);
5543 }
5544
5545 ALOGV(" - formats: ");
5546 for (size_t i = 0; i < mFormats.size(); i++) {
5547 ALOGV(" 0x%08x", mFormats[i]);
5548 }
5549
5550 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5551 ALOGV(" - flags: 0x%04x\n", mFlags);
5552}
5553
5554
Eric Laurent3a4311c2014-03-17 12:00:47 -07005555// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005556
Eric Laurent1f2f2232014-06-02 12:01:23 -07005557
5558AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5559 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5560 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5561 AUDIO_PORT_ROLE_SOURCE,
5562 NULL),
5563 mDeviceType(type), mAddress(""),
5564 mChannelMask(AUDIO_CHANNEL_NONE), mId(0)
5565{
5566 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005567 if (mGains.size() > 0) {
5568 mGains[0]->getDefaultConfig(&mGain);
5569 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005570}
5571
Eric Laurent3a4311c2014-03-17 12:00:47 -07005572bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005573{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005574 // Devices are considered equal if they:
5575 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5576 // - have the same address or one device does not specify the address
5577 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005578 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005579 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005580 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005581 mChannelMask == other->mChannelMask);
5582}
5583
5584void AudioPolicyManager::DeviceVector::refreshTypes()
5585{
Eric Laurent1c333e22014-05-20 10:48:17 -07005586 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005587 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005588 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005589 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005590 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005591}
5592
5593ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5594{
5595 for(size_t i = 0; i < size(); i++) {
5596 if (item->equals(itemAt(i))) {
5597 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005598 }
5599 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005600 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005601}
5602
Eric Laurent3a4311c2014-03-17 12:00:47 -07005603ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005604{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005605 ssize_t ret = indexOf(item);
5606
5607 if (ret < 0) {
5608 ret = SortedVector::add(item);
5609 if (ret >= 0) {
5610 refreshTypes();
5611 }
5612 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005613 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005614 ret = -1;
5615 }
5616 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005617}
5618
Eric Laurent3a4311c2014-03-17 12:00:47 -07005619ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5620{
5621 size_t i;
5622 ssize_t ret = indexOf(item);
5623
5624 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005625 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005626 } else {
5627 ret = SortedVector::removeAt(ret);
5628 if (ret >= 0) {
5629 refreshTypes();
5630 }
5631 }
5632 return ret;
5633}
5634
5635void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5636{
5637 DeviceVector deviceList;
5638
5639 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5640 types &= ~role_bit;
5641
5642 while (types) {
5643 uint32_t i = 31 - __builtin_clz(types);
5644 uint32_t type = 1 << i;
5645 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005646 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005647 }
5648}
5649
Eric Laurent1afeecb2014-05-14 08:52:28 -07005650void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5651 const DeviceVector& declaredDevices)
5652{
5653 char *devName = strtok(name, "|");
5654 while (devName != NULL) {
5655 if (strlen(devName) != 0) {
5656 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5657 ARRAY_SIZE(sDeviceNameToEnumTable),
5658 devName);
5659 if (type != AUDIO_DEVICE_NONE) {
5660 add(new DeviceDescriptor(String8(""), type));
5661 } else {
5662 sp<DeviceDescriptor> deviceDesc =
5663 declaredDevices.getDeviceFromName(String8(devName));
5664 if (deviceDesc != 0) {
5665 add(deviceDesc);
5666 }
5667 }
5668 }
5669 devName = strtok(NULL, "|");
5670 }
5671}
5672
Eric Laurent1c333e22014-05-20 10:48:17 -07005673sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5674 audio_devices_t type, String8 address) const
5675{
5676 sp<DeviceDescriptor> device;
5677 for (size_t i = 0; i < size(); i++) {
5678 if (itemAt(i)->mDeviceType == type) {
5679 device = itemAt(i);
5680 if (itemAt(i)->mAddress = address) {
5681 break;
5682 }
5683 }
5684 }
5685 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5686 type, address.string(), device.get());
5687 return device;
5688}
5689
Eric Laurent6a94d692014-05-20 11:18:06 -07005690sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5691 audio_port_handle_t id) const
5692{
5693 sp<DeviceDescriptor> device;
5694 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005695 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07005696 if (itemAt(i)->mId == id) {
5697 device = itemAt(i);
5698 break;
5699 }
5700 }
5701 return device;
5702}
5703
Eric Laurent1c333e22014-05-20 10:48:17 -07005704AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5705 audio_devices_t type) const
5706{
5707 DeviceVector devices;
5708 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5709 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5710 devices.add(itemAt(i));
5711 type &= ~itemAt(i)->mDeviceType;
5712 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5713 itemAt(i)->mDeviceType, itemAt(i).get());
5714 }
5715 }
5716 return devices;
5717}
5718
Eric Laurent1afeecb2014-05-14 08:52:28 -07005719sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5720 const String8& name) const
5721{
5722 sp<DeviceDescriptor> device;
5723 for (size_t i = 0; i < size(); i++) {
5724 if (itemAt(i)->mName == name) {
5725 device = itemAt(i);
5726 break;
5727 }
5728 }
5729 return device;
5730}
5731
Eric Laurent6a94d692014-05-20 11:18:06 -07005732void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5733 struct audio_port_config *dstConfig,
5734 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005735{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005736 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
5737 if (srcConfig != NULL) {
5738 dstConfig->config_mask &= srcConfig->config_mask;
5739 }
5740
5741 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5742
Eric Laurent6a94d692014-05-20 11:18:06 -07005743 dstConfig->id = mId;
5744 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005745 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005746 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005747 dstConfig->ext.device.type = mDeviceType;
5748 dstConfig->ext.device.hw_module = mModule->mHandle;
5749 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005750}
5751
5752void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5753{
Eric Laurente1715a42014-05-20 11:30:42 -07005754 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07005755 AudioPort::toAudioPort(port);
5756 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005757 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005758 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005759 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005760 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5761}
5762
Eric Laurent1afeecb2014-05-14 08:52:28 -07005763status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005764{
5765 const size_t SIZE = 256;
5766 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005767 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005768
Eric Laurent1afeecb2014-05-14 08:52:28 -07005769 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5770 result.append(buffer);
5771 if (mId != 0) {
5772 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5773 result.append(buffer);
5774 }
5775 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5776 enumToString(sDeviceNameToEnumTable,
5777 ARRAY_SIZE(sDeviceNameToEnumTable),
5778 mDeviceType));
5779 result.append(buffer);
5780 if (mAddress.size() != 0) {
5781 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5782 result.append(buffer);
5783 }
5784 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5785 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5786 result.append(buffer);
5787 }
5788 write(fd, result.string(), result.size());
5789 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005790
5791 return NO_ERROR;
5792}
5793
5794
5795// --- audio_policy.conf file parsing
5796
Eric Laurente0720872014-03-11 09:30:41 -07005797audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005798{
5799 uint32_t flag = 0;
5800
5801 // it is OK to cast name to non const here as we are not going to use it after
5802 // strtok() modifies it
5803 char *flagName = strtok(name, "|");
5804 while (flagName != NULL) {
5805 if (strlen(flagName) != 0) {
5806 flag |= stringToEnum(sFlagNameToEnumTable,
5807 ARRAY_SIZE(sFlagNameToEnumTable),
5808 flagName);
5809 }
5810 flagName = strtok(NULL, "|");
5811 }
5812 //force direct flag if offload flag is set: offloading implies a direct output stream
5813 // and all common behaviors are driven by checking only the direct flag
5814 // this should normally be set appropriately in the policy configuration file
5815 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5816 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5817 }
5818
5819 return (audio_output_flags_t)flag;
5820}
5821
Eric Laurente0720872014-03-11 09:30:41 -07005822audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005823{
5824 uint32_t device = 0;
5825
5826 char *devName = strtok(name, "|");
5827 while (devName != NULL) {
5828 if (strlen(devName) != 0) {
5829 device |= stringToEnum(sDeviceNameToEnumTable,
5830 ARRAY_SIZE(sDeviceNameToEnumTable),
5831 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005832 }
Eric Laurente552edb2014-03-10 17:42:56 -07005833 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005834 }
Eric Laurente552edb2014-03-10 17:42:56 -07005835 return device;
5836}
5837
Eric Laurente0720872014-03-11 09:30:41 -07005838void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005839{
Eric Laurente552edb2014-03-10 17:42:56 -07005840 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005841 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005842 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07005843
Eric Laurent1afeecb2014-05-14 08:52:28 -07005844 node = config_find(root, DEVICES_TAG);
5845 if (node != NULL) {
5846 node = node->first_child;
5847 while (node) {
5848 ALOGV("loadHwModule() loading device %s", node->name);
5849 status_t tmpStatus = module->loadDevice(node);
5850 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5851 status = tmpStatus;
5852 }
5853 node = node->next;
5854 }
5855 }
5856 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005857 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005858 node = node->first_child;
5859 while (node) {
5860 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005861 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005862 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5863 status = tmpStatus;
5864 }
5865 node = node->next;
5866 }
5867 }
5868 node = config_find(root, INPUTS_TAG);
5869 if (node != NULL) {
5870 node = node->first_child;
5871 while (node) {
5872 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005873 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005874 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5875 status = tmpStatus;
5876 }
5877 node = node->next;
5878 }
5879 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005880 loadGlobalConfig(root, module);
5881
Eric Laurente552edb2014-03-10 17:42:56 -07005882 if (status == NO_ERROR) {
5883 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07005884 }
5885}
5886
Eric Laurente0720872014-03-11 09:30:41 -07005887void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005888{
5889 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5890 if (node == NULL) {
5891 return;
5892 }
5893
5894 node = node->first_child;
5895 while (node) {
5896 ALOGV("loadHwModules() loading module %s", node->name);
5897 loadHwModule(node);
5898 node = node->next;
5899 }
5900}
5901
Eric Laurent1f2f2232014-06-02 12:01:23 -07005902void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07005903{
5904 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07005905
Eric Laurente552edb2014-03-10 17:42:56 -07005906 if (node == NULL) {
5907 return;
5908 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005909 DeviceVector declaredDevices;
5910 if (module != NULL) {
5911 declaredDevices = module->mDeclaredDevices;
5912 }
5913
Eric Laurente552edb2014-03-10 17:42:56 -07005914 node = node->first_child;
5915 while (node) {
5916 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005917 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5918 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005919 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5920 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005921 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005922 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005923 ARRAY_SIZE(sDeviceNameToEnumTable),
5924 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005925 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005926 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005927 } else {
5928 ALOGW("loadGlobalConfig() default device not specified");
5929 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005930 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005931 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005932 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5933 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005934 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005935 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5936 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5937 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07005938 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
5939 uint32_t major, minor;
5940 sscanf((char *)node->value, "%u.%u", &major, &minor);
5941 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
5942 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
5943 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07005944 }
5945 node = node->next;
5946 }
5947}
5948
Eric Laurente0720872014-03-11 09:30:41 -07005949status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005950{
5951 cnode *root;
5952 char *data;
5953
5954 data = (char *)load_file(path, NULL);
5955 if (data == NULL) {
5956 return -ENODEV;
5957 }
5958 root = config_node("", "");
5959 config_load(root, data);
5960
Eric Laurente552edb2014-03-10 17:42:56 -07005961 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005962 // legacy audio_policy.conf files have one global_configuration section
5963 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07005964 config_free(root);
5965 free(root);
5966 free(data);
5967
5968 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5969
5970 return NO_ERROR;
5971}
5972
Eric Laurente0720872014-03-11 09:30:41 -07005973void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07005974{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005975 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07005976 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005977 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
5978 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005979 mAvailableOutputDevices.add(mDefaultOutputDevice);
5980 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005981
5982 module = new HwModule("primary");
5983
Eric Laurent1afeecb2014-05-14 08:52:28 -07005984 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005985 profile->mSamplingRates.add(44100);
5986 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5987 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005988 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005989 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
5990 module->mOutputProfiles.add(profile);
5991
Eric Laurent1afeecb2014-05-14 08:52:28 -07005992 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005993 profile->mSamplingRates.add(8000);
5994 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5995 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005996 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005997 module->mInputProfiles.add(profile);
5998
5999 mHwModules.add(module);
6000}
6001
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006002audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6003{
6004 // flags to stream type mapping
6005 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6006 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6007 }
6008 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6009 return AUDIO_STREAM_BLUETOOTH_SCO;
6010 }
6011
6012 // usage to stream type mapping
6013 switch (attr->usage) {
6014 case AUDIO_USAGE_MEDIA:
6015 case AUDIO_USAGE_GAME:
6016 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6017 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6018 return AUDIO_STREAM_MUSIC;
6019 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6020 return AUDIO_STREAM_SYSTEM;
6021 case AUDIO_USAGE_VOICE_COMMUNICATION:
6022 return AUDIO_STREAM_VOICE_CALL;
6023
6024 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6025 return AUDIO_STREAM_DTMF;
6026
6027 case AUDIO_USAGE_ALARM:
6028 return AUDIO_STREAM_ALARM;
6029 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6030 return AUDIO_STREAM_RING;
6031
6032 case AUDIO_USAGE_NOTIFICATION:
6033 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6034 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6035 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6036 case AUDIO_USAGE_NOTIFICATION_EVENT:
6037 return AUDIO_STREAM_NOTIFICATION;
6038
6039 case AUDIO_USAGE_UNKNOWN:
6040 default:
6041 return AUDIO_STREAM_MUSIC;
6042 }
6043}
Eric Laurente552edb2014-03-10 17:42:56 -07006044}; // namespace android