blob: 95179b7369f0953f933fdc3da63c3c8e534e1882 [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 &&
Jungshik Jang839e4f32014-06-26 17:23:40 +0900519 config != AUDIO_POLICY_FORCE_NO_BT_A2DP &&
520 config != AUDIO_POLICY_FORCE_SYSTEM_AUDIO_HDMI_ARC &&
521 config != AUDIO_POLICY_FORCE_SYSTEM_AUDIO_SPDIF &&
522 config != AUDIO_POLICY_FORCE_SYSTEM_AUDIO_LINE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700523 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
524 return;
525 }
526 mForceUse[usage] = config;
527 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700528 case AUDIO_POLICY_FORCE_FOR_RECORD:
529 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
530 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700531 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
532 return;
533 }
534 mForceUse[usage] = config;
535 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700536 case AUDIO_POLICY_FORCE_FOR_DOCK:
537 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
538 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
539 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
540 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
541 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700542 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
543 }
544 forceVolumeReeval = true;
545 mForceUse[usage] = config;
546 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700547 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
548 if (config != AUDIO_POLICY_FORCE_NONE &&
549 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700550 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
551 }
552 forceVolumeReeval = true;
553 mForceUse[usage] = config;
554 break;
555 default:
556 ALOGW("setForceUse() invalid usage %d", usage);
557 break;
558 }
559
560 // check for device and output changes triggered by new force usage
561 checkA2dpSuspend();
562 checkOutputForAllStrategies();
563 updateDevicesAndOutputs();
564 for (size_t i = 0; i < mOutputs.size(); i++) {
565 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700566 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700567 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
568 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
569 applyStreamVolumes(output, newDevice, 0, true);
570 }
571 }
572
573 audio_io_handle_t activeInput = getActiveInput();
574 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700575 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700576 }
577
578}
579
Eric Laurente0720872014-03-11 09:30:41 -0700580audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700581{
582 return mForceUse[usage];
583}
584
Eric Laurente0720872014-03-11 09:30:41 -0700585void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700586{
587 ALOGV("setSystemProperty() property %s, value %s", property, value);
588}
589
590// Find a direct output profile compatible with the parameters passed, even if the input flags do
591// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700592sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700593 audio_devices_t device,
594 uint32_t samplingRate,
595 audio_format_t format,
596 audio_channel_mask_t channelMask,
597 audio_output_flags_t flags)
598{
599 for (size_t i = 0; i < mHwModules.size(); i++) {
600 if (mHwModules[i]->mHandle == 0) {
601 continue;
602 }
603 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700604 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700605 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700606 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
607 if (profile->isCompatibleProfile(device, samplingRate, format,
608 channelMask,
609 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700610 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700611 }
612 } else {
613 if (profile->isCompatibleProfile(device, samplingRate, format,
614 channelMask,
615 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700616 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700617 }
618 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700619 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
620 return profile;
621 }
Eric Laurente552edb2014-03-10 17:42:56 -0700622 }
623 }
624 return 0;
625}
626
Eric Laurente0720872014-03-11 09:30:41 -0700627audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700628 uint32_t samplingRate,
629 audio_format_t format,
630 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700631 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700632 const audio_offload_info_t *offloadInfo)
633{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700634
Eric Laurent3b73df72014-03-11 09:06:29 -0700635 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700636 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
637 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
638 device, stream, samplingRate, format, channelMask, flags);
639
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700640 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
641 offloadInfo);
642}
643
644audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
645 uint32_t samplingRate,
646 audio_format_t format,
647 audio_channel_mask_t channelMask,
648 audio_output_flags_t flags,
649 const audio_offload_info_t *offloadInfo)
650{
651 if (attr == NULL) {
652 ALOGE("getOutputForAttr() called with NULL audio attributes");
653 return 0;
654 }
655 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
656 attr->usage, attr->content_type, attr->tags);
657
658 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
659 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
660 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
661 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
662 device, samplingRate, format, channelMask, flags);
663
664 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
665 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
666 offloadInfo);
667}
668
669audio_io_handle_t AudioPolicyManager::getOutputForDevice(
670 audio_devices_t device,
671 audio_stream_type_t stream,
672 uint32_t samplingRate,
673 audio_format_t format,
674 audio_channel_mask_t channelMask,
675 audio_output_flags_t flags,
676 const audio_offload_info_t *offloadInfo)
677{
678 audio_io_handle_t output = 0;
679 uint32_t latency = 0;
680
Eric Laurente552edb2014-03-10 17:42:56 -0700681#ifdef AUDIO_POLICY_TEST
682 if (mCurOutput != 0) {
683 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
684 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
685
686 if (mTestOutputs[mCurOutput] == 0) {
687 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700688 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700689 outputDesc->mDevice = mTestDevice;
690 outputDesc->mSamplingRate = mTestSamplingRate;
691 outputDesc->mFormat = mTestFormat;
692 outputDesc->mChannelMask = mTestChannels;
693 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700694 outputDesc->mFlags =
695 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700696 outputDesc->mRefCount[stream] = 0;
697 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
698 &outputDesc->mSamplingRate,
699 &outputDesc->mFormat,
700 &outputDesc->mChannelMask,
701 &outputDesc->mLatency,
702 outputDesc->mFlags,
703 offloadInfo);
704 if (mTestOutputs[mCurOutput]) {
705 AudioParameter outputCmd = AudioParameter();
706 outputCmd.addInt(String8("set_id"),mCurOutput);
707 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
708 addOutput(mTestOutputs[mCurOutput], outputDesc);
709 }
710 }
711 return mTestOutputs[mCurOutput];
712 }
713#endif //AUDIO_POLICY_TEST
714
715 // open a direct output if required by specified parameters
716 //force direct flag if offload flag is set: offloading implies a direct output stream
717 // and all common behaviors are driven by checking only the direct flag
718 // this should normally be set appropriately in the policy configuration file
719 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700720 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700721 }
722
723 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
724 // creating an offloaded track and tearing it down immediately after start when audioflinger
725 // detects there is an active non offloadable effect.
726 // FIXME: We should check the audio session here but we do not have it in this context.
727 // This may prevent offloading in rare situations where effects are left active by apps
728 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700729 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700730 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
731 !isNonOffloadableEffectEnabled()) {
732 profile = getProfileForDirectOutput(device,
733 samplingRate,
734 format,
735 channelMask,
736 (audio_output_flags_t)flags);
737 }
738
Eric Laurent1c333e22014-05-20 10:48:17 -0700739 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700740 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700741
742 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700743 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700744 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
745 outputDesc = desc;
746 // reuse direct output if currently open and configured with same parameters
747 if ((samplingRate == outputDesc->mSamplingRate) &&
748 (format == outputDesc->mFormat) &&
749 (channelMask == outputDesc->mChannelMask)) {
750 outputDesc->mDirectOpenCount++;
751 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
752 return mOutputs.keyAt(i);
753 }
754 }
755 }
756 // close direct output if currently open and configured with different parameters
757 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700758 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700759 }
760 outputDesc = new AudioOutputDescriptor(profile);
761 outputDesc->mDevice = device;
762 outputDesc->mSamplingRate = samplingRate;
763 outputDesc->mFormat = format;
764 outputDesc->mChannelMask = channelMask;
765 outputDesc->mLatency = 0;
766 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
767 outputDesc->mRefCount[stream] = 0;
768 outputDesc->mStopTime[stream] = 0;
769 outputDesc->mDirectOpenCount = 1;
770 output = mpClientInterface->openOutput(profile->mModule->mHandle,
771 &outputDesc->mDevice,
772 &outputDesc->mSamplingRate,
773 &outputDesc->mFormat,
774 &outputDesc->mChannelMask,
775 &outputDesc->mLatency,
776 outputDesc->mFlags,
777 offloadInfo);
778
779 // only accept an output with the requested parameters
780 if (output == 0 ||
781 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
782 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
783 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
784 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
785 "format %d %d, channelMask %04x %04x", output, samplingRate,
786 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
787 outputDesc->mChannelMask);
788 if (output != 0) {
789 mpClientInterface->closeOutput(output);
790 }
Eric Laurente552edb2014-03-10 17:42:56 -0700791 return 0;
792 }
793 audio_io_handle_t srcOutput = getOutputForEffect();
794 addOutput(output, outputDesc);
795 audio_io_handle_t dstOutput = getOutputForEffect();
796 if (dstOutput == output) {
797 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
798 }
799 mPreviousOutputs = mOutputs;
800 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700801 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700802 return output;
803 }
804
805 // ignoring channel mask due to downmix capability in mixer
806
807 // open a non direct output
808
809 // for non direct outputs, only PCM is supported
810 if (audio_is_linear_pcm(format)) {
811 // get which output is suitable for the specified stream. The actual
812 // routing change will happen when startOutput() will be called
813 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
814
815 output = selectOutput(outputs, flags);
816 }
817 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
818 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
819
820 ALOGV("getOutput() returns output %d", output);
821
822 return output;
823}
824
Eric Laurente0720872014-03-11 09:30:41 -0700825audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700826 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700827{
828 // select one output among several that provide a path to a particular device or set of
829 // devices (the list was previously build by getOutputsForDevice()).
830 // The priority is as follows:
831 // 1: the output with the highest number of requested policy flags
832 // 2: the primary output
833 // 3: the first output in the list
834
835 if (outputs.size() == 0) {
836 return 0;
837 }
838 if (outputs.size() == 1) {
839 return outputs[0];
840 }
841
842 int maxCommonFlags = 0;
843 audio_io_handle_t outputFlags = 0;
844 audio_io_handle_t outputPrimary = 0;
845
846 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700847 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700848 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700849 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700850 if (commonFlags > maxCommonFlags) {
851 outputFlags = outputs[i];
852 maxCommonFlags = commonFlags;
853 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
854 }
855 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
856 outputPrimary = outputs[i];
857 }
858 }
859 }
860
861 if (outputFlags != 0) {
862 return outputFlags;
863 }
864 if (outputPrimary != 0) {
865 return outputPrimary;
866 }
867
868 return outputs[0];
869}
870
Eric Laurente0720872014-03-11 09:30:41 -0700871status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700872 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700873 int session)
874{
875 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
876 ssize_t index = mOutputs.indexOfKey(output);
877 if (index < 0) {
878 ALOGW("startOutput() unknown output %d", output);
879 return BAD_VALUE;
880 }
881
Eric Laurent1f2f2232014-06-02 12:01:23 -0700882 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700883
884 // increment usage count for this stream on the requested output:
885 // NOTE that the usage count is the same for duplicated output and hardware output which is
886 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
887 outputDesc->changeRefCount(stream, 1);
888
889 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700890 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700891 routing_strategy strategy = getStrategy(stream);
892 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
893 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
894 uint32_t waitMs = 0;
895 bool force = false;
896 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700897 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700898 if (desc != outputDesc) {
899 // force a device change if any other output is managed by the same hw
900 // module and has a current device selection that differs from selected device.
901 // In this case, the audio HAL must receive the new device selection so that it can
902 // change the device currently selected by the other active output.
903 if (outputDesc->sharesHwModuleWith(desc) &&
904 desc->device() != newDevice) {
905 force = true;
906 }
907 // wait for audio on other active outputs to be presented when starting
908 // a notification so that audio focus effect can propagate.
909 uint32_t latency = desc->latency();
910 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
911 waitMs = latency;
912 }
913 }
914 }
915 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
916
917 // handle special case for sonification while in call
918 if (isInCall()) {
919 handleIncallSonification(stream, true, false);
920 }
921
922 // apply volume rules for current stream and device if necessary
923 checkAndSetVolume(stream,
924 mStreams[stream].getVolumeIndex(newDevice),
925 output,
926 newDevice);
927
928 // update the outputs if starting an output with a stream that can affect notification
929 // routing
930 handleNotificationRoutingForStream(stream);
931 if (waitMs > muteWaitMs) {
932 usleep((waitMs - muteWaitMs) * 2 * 1000);
933 }
934 }
935 return NO_ERROR;
936}
937
938
Eric Laurente0720872014-03-11 09:30:41 -0700939status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700940 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700941 int session)
942{
943 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
944 ssize_t index = mOutputs.indexOfKey(output);
945 if (index < 0) {
946 ALOGW("stopOutput() unknown output %d", output);
947 return BAD_VALUE;
948 }
949
Eric Laurent1f2f2232014-06-02 12:01:23 -0700950 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700951
952 // handle special case for sonification while in call
953 if (isInCall()) {
954 handleIncallSonification(stream, false, false);
955 }
956
957 if (outputDesc->mRefCount[stream] > 0) {
958 // decrement usage count of this stream on the output
959 outputDesc->changeRefCount(stream, -1);
960 // store time at which the stream was stopped - see isStreamActive()
961 if (outputDesc->mRefCount[stream] == 0) {
962 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700963 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700964 // delay the device switch by twice the latency because stopOutput() is executed when
965 // the track stop() command is received and at that time the audio track buffer can
966 // still contain data that needs to be drained. The latency only covers the audio HAL
967 // and kernel buffers. Also the latency does not always include additional delay in the
968 // audio path (audio DSP, CODEC ...)
969 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
970
971 // force restoring the device selection on other active outputs if it differs from the
972 // one being selected for this output
973 for (size_t i = 0; i < mOutputs.size(); i++) {
974 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700975 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700976 if (curOutput != output &&
977 desc->isActive() &&
978 outputDesc->sharesHwModuleWith(desc) &&
979 (newDevice != desc->device())) {
980 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700981 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700982 true,
983 outputDesc->mLatency*2);
984 }
985 }
986 // update the outputs if stopping one with a stream that can affect notification routing
987 handleNotificationRoutingForStream(stream);
988 }
989 return NO_ERROR;
990 } else {
991 ALOGW("stopOutput() refcount is already 0 for output %d", output);
992 return INVALID_OPERATION;
993 }
994}
995
Eric Laurente0720872014-03-11 09:30:41 -0700996void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700997{
998 ALOGV("releaseOutput() %d", output);
999 ssize_t index = mOutputs.indexOfKey(output);
1000 if (index < 0) {
1001 ALOGW("releaseOutput() releasing unknown output %d", output);
1002 return;
1003 }
1004
1005#ifdef AUDIO_POLICY_TEST
1006 int testIndex = testOutputIndex(output);
1007 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001008 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001009 if (outputDesc->isActive()) {
1010 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001011 mOutputs.removeItem(output);
1012 mTestOutputs[testIndex] = 0;
1013 }
1014 return;
1015 }
1016#endif //AUDIO_POLICY_TEST
1017
Eric Laurent1f2f2232014-06-02 12:01:23 -07001018 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001019 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001020 if (desc->mDirectOpenCount <= 0) {
1021 ALOGW("releaseOutput() invalid open count %d for output %d",
1022 desc->mDirectOpenCount, output);
1023 return;
1024 }
1025 if (--desc->mDirectOpenCount == 0) {
1026 closeOutput(output);
1027 // If effects where present on the output, audioflinger moved them to the primary
1028 // output by default: move them back to the appropriate output.
1029 audio_io_handle_t dstOutput = getOutputForEffect();
1030 if (dstOutput != mPrimaryOutput) {
1031 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1032 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001033 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001034 }
1035 }
1036}
1037
1038
Eric Laurente0720872014-03-11 09:30:41 -07001039audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001040 uint32_t samplingRate,
1041 audio_format_t format,
1042 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001043 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001044{
1045 audio_io_handle_t input = 0;
1046 audio_devices_t device = getDeviceForInputSource(inputSource);
1047
1048 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1049 inputSource, samplingRate, format, channelMask, acoustics);
1050
1051 if (device == AUDIO_DEVICE_NONE) {
1052 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1053 return 0;
1054 }
1055
1056 // adapt channel selection to input source
1057 switch(inputSource) {
1058 case AUDIO_SOURCE_VOICE_UPLINK:
1059 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1060 break;
1061 case AUDIO_SOURCE_VOICE_DOWNLINK:
1062 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1063 break;
1064 case AUDIO_SOURCE_VOICE_CALL:
1065 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1066 break;
1067 default:
1068 break;
1069 }
1070
Eric Laurent1c333e22014-05-20 10:48:17 -07001071 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001072 samplingRate,
1073 format,
1074 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001075 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001076 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1077 "channelMask %04x",
1078 device, samplingRate, format, channelMask);
1079 return 0;
1080 }
1081
1082 if (profile->mModule->mHandle == 0) {
1083 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1084 return 0;
1085 }
1086
Eric Laurent1f2f2232014-06-02 12:01:23 -07001087 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001088
1089 inputDesc->mInputSource = inputSource;
1090 inputDesc->mDevice = device;
1091 inputDesc->mSamplingRate = samplingRate;
1092 inputDesc->mFormat = format;
1093 inputDesc->mChannelMask = channelMask;
1094 inputDesc->mRefCount = 0;
1095 input = mpClientInterface->openInput(profile->mModule->mHandle,
1096 &inputDesc->mDevice,
1097 &inputDesc->mSamplingRate,
1098 &inputDesc->mFormat,
1099 &inputDesc->mChannelMask);
1100
1101 // only accept input with the exact requested set of parameters
1102 if (input == 0 ||
1103 (samplingRate != inputDesc->mSamplingRate) ||
1104 (format != inputDesc->mFormat) ||
1105 (channelMask != inputDesc->mChannelMask)) {
1106 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1107 samplingRate, format, channelMask);
1108 if (input != 0) {
1109 mpClientInterface->closeInput(input);
1110 }
Eric Laurente552edb2014-03-10 17:42:56 -07001111 return 0;
1112 }
Eric Laurentd4692962014-05-05 18:13:44 -07001113 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001114 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001115 return input;
1116}
1117
Eric Laurente0720872014-03-11 09:30:41 -07001118status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001119{
1120 ALOGV("startInput() input %d", input);
1121 ssize_t index = mInputs.indexOfKey(input);
1122 if (index < 0) {
1123 ALOGW("startInput() unknown input %d", input);
1124 return BAD_VALUE;
1125 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001126 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001127
1128#ifdef AUDIO_POLICY_TEST
1129 if (mTestInput == 0)
1130#endif //AUDIO_POLICY_TEST
1131 {
1132 // refuse 2 active AudioRecord clients at the same time except if the active input
1133 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1134 audio_io_handle_t activeInput = getActiveInput();
1135 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001136 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001137 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1138 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1139 stopInput(activeInput);
1140 releaseInput(activeInput);
1141 } else {
1142 ALOGW("startInput() input %d failed: other input already started", input);
1143 return INVALID_OPERATION;
1144 }
1145 }
1146 }
1147
Eric Laurent1c333e22014-05-20 10:48:17 -07001148 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001149
1150 // automatically enable the remote submix output when input is started
1151 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1152 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001153 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001154 }
1155
Eric Laurente552edb2014-03-10 17:42:56 -07001156 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1157
Eric Laurente552edb2014-03-10 17:42:56 -07001158 inputDesc->mRefCount = 1;
1159 return NO_ERROR;
1160}
1161
Eric Laurente0720872014-03-11 09:30:41 -07001162status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001163{
1164 ALOGV("stopInput() input %d", input);
1165 ssize_t index = mInputs.indexOfKey(input);
1166 if (index < 0) {
1167 ALOGW("stopInput() unknown input %d", input);
1168 return BAD_VALUE;
1169 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001170 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001171
1172 if (inputDesc->mRefCount == 0) {
1173 ALOGW("stopInput() input %d already stopped", input);
1174 return INVALID_OPERATION;
1175 } else {
1176 // automatically disable the remote submix output when input is stopped
1177 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1178 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001179 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001180 }
1181
Eric Laurent1c333e22014-05-20 10:48:17 -07001182 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001183 inputDesc->mRefCount = 0;
1184 return NO_ERROR;
1185 }
1186}
1187
Eric Laurente0720872014-03-11 09:30:41 -07001188void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001189{
1190 ALOGV("releaseInput() %d", input);
1191 ssize_t index = mInputs.indexOfKey(input);
1192 if (index < 0) {
1193 ALOGW("releaseInput() releasing unknown input %d", input);
1194 return;
1195 }
1196 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001197 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001198 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001199 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001200 ALOGV("releaseInput() exit");
1201}
1202
Eric Laurentd4692962014-05-05 18:13:44 -07001203void AudioPolicyManager::closeAllInputs() {
1204 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1205 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1206 }
1207 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001208 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001209}
1210
Eric Laurente0720872014-03-11 09:30:41 -07001211void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001212 int indexMin,
1213 int indexMax)
1214{
1215 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1216 if (indexMin < 0 || indexMin >= indexMax) {
1217 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1218 return;
1219 }
1220 mStreams[stream].mIndexMin = indexMin;
1221 mStreams[stream].mIndexMax = indexMax;
1222}
1223
Eric Laurente0720872014-03-11 09:30:41 -07001224status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001225 int index,
1226 audio_devices_t device)
1227{
1228
1229 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1230 return BAD_VALUE;
1231 }
1232 if (!audio_is_output_device(device)) {
1233 return BAD_VALUE;
1234 }
1235
1236 // Force max volume if stream cannot be muted
1237 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1238
1239 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1240 stream, device, index);
1241
1242 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1243 // clear all device specific values
1244 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1245 mStreams[stream].mIndexCur.clear();
1246 }
1247 mStreams[stream].mIndexCur.add(device, index);
1248
1249 // compute and apply stream volume on all outputs according to connected device
1250 status_t status = NO_ERROR;
1251 for (size_t i = 0; i < mOutputs.size(); i++) {
1252 audio_devices_t curDevice =
1253 getDeviceForVolume(mOutputs.valueAt(i)->device());
1254 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1255 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1256 if (volStatus != NO_ERROR) {
1257 status = volStatus;
1258 }
1259 }
1260 }
1261 return status;
1262}
1263
Eric Laurente0720872014-03-11 09:30:41 -07001264status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001265 int *index,
1266 audio_devices_t device)
1267{
1268 if (index == NULL) {
1269 return BAD_VALUE;
1270 }
1271 if (!audio_is_output_device(device)) {
1272 return BAD_VALUE;
1273 }
1274 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1275 // the strategy the stream belongs to.
1276 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1277 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1278 }
1279 device = getDeviceForVolume(device);
1280
1281 *index = mStreams[stream].getVolumeIndex(device);
1282 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1283 return NO_ERROR;
1284}
1285
Eric Laurente0720872014-03-11 09:30:41 -07001286audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001287 const SortedVector<audio_io_handle_t>& outputs)
1288{
1289 // select one output among several suitable for global effects.
1290 // The priority is as follows:
1291 // 1: An offloaded output. If the effect ends up not being offloadable,
1292 // AudioFlinger will invalidate the track and the offloaded output
1293 // will be closed causing the effect to be moved to a PCM output.
1294 // 2: A deep buffer output
1295 // 3: the first output in the list
1296
1297 if (outputs.size() == 0) {
1298 return 0;
1299 }
1300
1301 audio_io_handle_t outputOffloaded = 0;
1302 audio_io_handle_t outputDeepBuffer = 0;
1303
1304 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001305 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001306 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001307 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1308 outputOffloaded = outputs[i];
1309 }
1310 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1311 outputDeepBuffer = outputs[i];
1312 }
1313 }
1314
1315 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1316 outputOffloaded, outputDeepBuffer);
1317 if (outputOffloaded != 0) {
1318 return outputOffloaded;
1319 }
1320 if (outputDeepBuffer != 0) {
1321 return outputDeepBuffer;
1322 }
1323
1324 return outputs[0];
1325}
1326
Eric Laurente0720872014-03-11 09:30:41 -07001327audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001328{
1329 // apply simple rule where global effects are attached to the same output as MUSIC streams
1330
Eric Laurent3b73df72014-03-11 09:06:29 -07001331 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001332 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1333 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1334
1335 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1336 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1337 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1338
1339 return output;
1340}
1341
Eric Laurente0720872014-03-11 09:30:41 -07001342status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001343 audio_io_handle_t io,
1344 uint32_t strategy,
1345 int session,
1346 int id)
1347{
1348 ssize_t index = mOutputs.indexOfKey(io);
1349 if (index < 0) {
1350 index = mInputs.indexOfKey(io);
1351 if (index < 0) {
1352 ALOGW("registerEffect() unknown io %d", io);
1353 return INVALID_OPERATION;
1354 }
1355 }
1356
1357 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1358 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1359 desc->name, desc->memoryUsage);
1360 return INVALID_OPERATION;
1361 }
1362 mTotalEffectsMemory += desc->memoryUsage;
1363 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1364 desc->name, io, strategy, session, id);
1365 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1366
Eric Laurent1f2f2232014-06-02 12:01:23 -07001367 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1368 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1369 effectDesc->mIo = io;
1370 effectDesc->mStrategy = (routing_strategy)strategy;
1371 effectDesc->mSession = session;
1372 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001373
Eric Laurent1f2f2232014-06-02 12:01:23 -07001374 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001375
1376 return NO_ERROR;
1377}
1378
Eric Laurente0720872014-03-11 09:30:41 -07001379status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001380{
1381 ssize_t index = mEffects.indexOfKey(id);
1382 if (index < 0) {
1383 ALOGW("unregisterEffect() unknown effect ID %d", id);
1384 return INVALID_OPERATION;
1385 }
1386
Eric Laurent1f2f2232014-06-02 12:01:23 -07001387 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001388
Eric Laurent1f2f2232014-06-02 12:01:23 -07001389 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001390
Eric Laurent1f2f2232014-06-02 12:01:23 -07001391 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001392 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001393 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1394 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001395 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001396 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001397 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001398 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001399
1400 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001401
1402 return NO_ERROR;
1403}
1404
Eric Laurente0720872014-03-11 09:30:41 -07001405status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001406{
1407 ssize_t index = mEffects.indexOfKey(id);
1408 if (index < 0) {
1409 ALOGW("unregisterEffect() unknown effect ID %d", id);
1410 return INVALID_OPERATION;
1411 }
1412
1413 return setEffectEnabled(mEffects.valueAt(index), enabled);
1414}
1415
Eric Laurent1f2f2232014-06-02 12:01:23 -07001416status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001417{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001418 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001419 ALOGV("setEffectEnabled(%s) effect already %s",
1420 enabled?"true":"false", enabled?"enabled":"disabled");
1421 return INVALID_OPERATION;
1422 }
1423
1424 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001425 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001426 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001427 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001428 return INVALID_OPERATION;
1429 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001430 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001431 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1432 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001433 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001434 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001435 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1436 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001437 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001438 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001439 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1440 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001441 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001442 return NO_ERROR;
1443}
1444
Eric Laurente0720872014-03-11 09:30:41 -07001445bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001446{
1447 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001448 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1449 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1450 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001451 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001452 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001453 return true;
1454 }
1455 }
1456 return false;
1457}
1458
Eric Laurente0720872014-03-11 09:30:41 -07001459bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001460{
1461 nsecs_t sysTime = systemTime();
1462 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001463 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001464 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001465 return true;
1466 }
1467 }
1468 return false;
1469}
1470
Eric Laurente0720872014-03-11 09:30:41 -07001471bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001472 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001473{
1474 nsecs_t sysTime = systemTime();
1475 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001476 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001477 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001478 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001479 return true;
1480 }
1481 }
1482 return false;
1483}
1484
Eric Laurente0720872014-03-11 09:30:41 -07001485bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001486{
1487 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001488 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001489 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001490 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001491 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1492 && (inputDescriptor->mRefCount > 0)) {
1493 return true;
1494 }
1495 }
1496 return false;
1497}
1498
1499
Eric Laurente0720872014-03-11 09:30:41 -07001500status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001501{
1502 const size_t SIZE = 256;
1503 char buffer[SIZE];
1504 String8 result;
1505
1506 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1507 result.append(buffer);
1508
1509 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1510 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001511 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1512 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001513 snprintf(buffer, SIZE, " Force use for communications %d\n",
1514 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001515 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001516 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001517 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001518 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001519 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001520 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001521 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001522 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001523 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001524
Eric Laurent3a4311c2014-03-17 12:00:47 -07001525 snprintf(buffer, SIZE, " Available output devices:\n");
1526 result.append(buffer);
1527 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001528 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001529 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001530 }
1531 snprintf(buffer, SIZE, "\n Available input devices:\n");
1532 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001533 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001534 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001535 }
Eric Laurente552edb2014-03-10 17:42:56 -07001536
1537 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1538 write(fd, buffer, strlen(buffer));
1539 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001540 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001541 write(fd, buffer, strlen(buffer));
1542 mHwModules[i]->dump(fd);
1543 }
1544
1545 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1546 write(fd, buffer, strlen(buffer));
1547 for (size_t i = 0; i < mOutputs.size(); i++) {
1548 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1549 write(fd, buffer, strlen(buffer));
1550 mOutputs.valueAt(i)->dump(fd);
1551 }
1552
1553 snprintf(buffer, SIZE, "\nInputs dump:\n");
1554 write(fd, buffer, strlen(buffer));
1555 for (size_t i = 0; i < mInputs.size(); i++) {
1556 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1557 write(fd, buffer, strlen(buffer));
1558 mInputs.valueAt(i)->dump(fd);
1559 }
1560
1561 snprintf(buffer, SIZE, "\nStreams dump:\n");
1562 write(fd, buffer, strlen(buffer));
1563 snprintf(buffer, SIZE,
1564 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1565 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001566 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001567 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001568 write(fd, buffer, strlen(buffer));
1569 mStreams[i].dump(fd);
1570 }
1571
1572 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1573 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1574 write(fd, buffer, strlen(buffer));
1575
1576 snprintf(buffer, SIZE, "Registered effects:\n");
1577 write(fd, buffer, strlen(buffer));
1578 for (size_t i = 0; i < mEffects.size(); i++) {
1579 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1580 write(fd, buffer, strlen(buffer));
1581 mEffects.valueAt(i)->dump(fd);
1582 }
1583
1584
1585 return NO_ERROR;
1586}
1587
1588// This function checks for the parameters which can be offloaded.
1589// This can be enhanced depending on the capability of the DSP and policy
1590// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001591bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001592{
1593 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001594 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001595 offloadInfo.sample_rate, offloadInfo.channel_mask,
1596 offloadInfo.format,
1597 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1598 offloadInfo.has_video);
1599
1600 // Check if offload has been disabled
1601 char propValue[PROPERTY_VALUE_MAX];
1602 if (property_get("audio.offload.disable", propValue, "0")) {
1603 if (atoi(propValue) != 0) {
1604 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1605 return false;
1606 }
1607 }
1608
1609 // Check if stream type is music, then only allow offload as of now.
1610 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1611 {
1612 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1613 return false;
1614 }
1615
1616 //TODO: enable audio offloading with video when ready
1617 if (offloadInfo.has_video)
1618 {
1619 ALOGV("isOffloadSupported: has_video == true, returning false");
1620 return false;
1621 }
1622
1623 //If duration is less than minimum value defined in property, return false
1624 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1625 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1626 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1627 return false;
1628 }
1629 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1630 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1631 return false;
1632 }
1633
1634 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1635 // creating an offloaded track and tearing it down immediately after start when audioflinger
1636 // detects there is an active non offloadable effect.
1637 // FIXME: We should check the audio session here but we do not have it in this context.
1638 // This may prevent offloading in rare situations where effects are left active by apps
1639 // in the background.
1640 if (isNonOffloadableEffectEnabled()) {
1641 return false;
1642 }
1643
1644 // See if there is a profile to support this.
1645 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001646 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001647 offloadInfo.sample_rate,
1648 offloadInfo.format,
1649 offloadInfo.channel_mask,
1650 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001651 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1652 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001653}
1654
Eric Laurent6a94d692014-05-20 11:18:06 -07001655status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1656 audio_port_type_t type,
1657 unsigned int *num_ports,
1658 struct audio_port *ports,
1659 unsigned int *generation)
1660{
1661 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1662 generation == NULL) {
1663 return BAD_VALUE;
1664 }
1665 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1666 if (ports == NULL) {
1667 *num_ports = 0;
1668 }
1669
1670 size_t portsWritten = 0;
1671 size_t portsMax = *num_ports;
1672 *num_ports = 0;
1673 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1674 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1675 for (size_t i = 0;
1676 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1677 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1678 }
1679 *num_ports += mAvailableOutputDevices.size();
1680 }
1681 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1682 for (size_t i = 0;
1683 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1684 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1685 }
1686 *num_ports += mAvailableInputDevices.size();
1687 }
1688 }
1689 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1690 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1691 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1692 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1693 }
1694 *num_ports += mInputs.size();
1695 }
1696 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001697 size_t numOutputs = 0;
1698 for (size_t i = 0; i < mOutputs.size(); i++) {
1699 if (!mOutputs[i]->isDuplicated()) {
1700 numOutputs++;
1701 if (portsWritten < portsMax) {
1702 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1703 }
1704 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001705 }
Eric Laurent84c70242014-06-23 08:46:27 -07001706 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001707 }
1708 }
1709 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001710 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001711 return NO_ERROR;
1712}
1713
1714status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1715{
1716 return NO_ERROR;
1717}
1718
Eric Laurent1f2f2232014-06-02 12:01:23 -07001719sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001720 audio_port_handle_t id) const
1721{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001722 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001723 for (size_t i = 0; i < mOutputs.size(); i++) {
1724 outputDesc = mOutputs.valueAt(i);
1725 if (outputDesc->mId == id) {
1726 break;
1727 }
1728 }
1729 return outputDesc;
1730}
1731
Eric Laurent1f2f2232014-06-02 12:01:23 -07001732sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001733 audio_port_handle_t id) const
1734{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001735 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001736 for (size_t i = 0; i < mInputs.size(); i++) {
1737 inputDesc = mInputs.valueAt(i);
1738 if (inputDesc->mId == id) {
1739 break;
1740 }
1741 }
1742 return inputDesc;
1743}
1744
Eric Laurent1f2f2232014-06-02 12:01:23 -07001745sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1746 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001747{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001748 sp <HwModule> module;
1749
Eric Laurent6a94d692014-05-20 11:18:06 -07001750 for (size_t i = 0; i < mHwModules.size(); i++) {
1751 if (mHwModules[i]->mHandle == 0) {
1752 continue;
1753 }
1754 if (audio_is_output_device(device)) {
1755 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1756 {
1757 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1758 return mHwModules[i];
1759 }
1760 }
1761 } else {
1762 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1763 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1764 device & ~AUDIO_DEVICE_BIT_IN) {
1765 return mHwModules[i];
1766 }
1767 }
1768 }
1769 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001770 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001771}
1772
Eric Laurent1f2f2232014-06-02 12:01:23 -07001773sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001774{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001775 sp <HwModule> module;
1776
Eric Laurent1afeecb2014-05-14 08:52:28 -07001777 for (size_t i = 0; i < mHwModules.size(); i++)
1778 {
1779 if (strcmp(mHwModules[i]->mName, name) == 0) {
1780 return mHwModules[i];
1781 }
1782 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001783 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001784}
1785
1786
Eric Laurent6a94d692014-05-20 11:18:06 -07001787status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1788 audio_patch_handle_t *handle,
1789 uid_t uid)
1790{
1791 ALOGV("createAudioPatch()");
1792
1793 if (handle == NULL || patch == NULL) {
1794 return BAD_VALUE;
1795 }
1796 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1797
1798 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1799 return INVALID_OPERATION;
1800 }
1801 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1802 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1803 return INVALID_OPERATION;
1804 }
1805
1806 sp<AudioPatch> patchDesc;
1807 ssize_t index = mAudioPatches.indexOfKey(*handle);
1808
1809 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1810 patch->sinks[0].type);
1811 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1812 patch->sources[0].role,
1813 patch->sources[0].type);
1814
1815 if (index >= 0) {
1816 patchDesc = mAudioPatches.valueAt(index);
1817 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1818 mUidCached, patchDesc->mUid, uid);
1819 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1820 return INVALID_OPERATION;
1821 }
1822 } else {
1823 *handle = 0;
1824 }
1825
1826 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1827 // TODO add support for mix to mix connection
1828 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1829 ALOGV("createAudioPatch() source mix sink not device");
1830 return BAD_VALUE;
1831 }
1832 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001833 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001834 if (outputDesc == NULL) {
1835 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1836 return BAD_VALUE;
1837 }
Eric Laurent84c70242014-06-23 08:46:27 -07001838 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1839 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001840 if (patchDesc != 0) {
1841 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1842 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1843 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1844 return BAD_VALUE;
1845 }
1846 }
1847 sp<DeviceDescriptor> devDesc =
1848 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1849 if (devDesc == 0) {
1850 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1851 return BAD_VALUE;
1852 }
1853
Eric Laurent84c70242014-06-23 08:46:27 -07001854 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001855 patch->sources[0].sample_rate,
1856 patch->sources[0].format,
1857 patch->sources[0].channel_mask,
1858 AUDIO_OUTPUT_FLAG_NONE)) {
1859 return INVALID_OPERATION;
1860 }
1861 // TODO: reconfigure output format and channels here
1862 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001863 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001864 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001865 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001866 true,
1867 0,
1868 handle);
1869 index = mAudioPatches.indexOfKey(*handle);
1870 if (index >= 0) {
1871 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1872 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1873 }
1874 patchDesc = mAudioPatches.valueAt(index);
1875 patchDesc->mUid = uid;
1876 ALOGV("createAudioPatch() success");
1877 } else {
1878 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1879 return INVALID_OPERATION;
1880 }
1881 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1882 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1883 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001884 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001885 if (inputDesc == NULL) {
1886 return BAD_VALUE;
1887 }
1888 if (patchDesc != 0) {
1889 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1890 return BAD_VALUE;
1891 }
1892 }
1893 sp<DeviceDescriptor> devDesc =
1894 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1895 if (devDesc == 0) {
1896 return BAD_VALUE;
1897 }
1898
Eric Laurent84c70242014-06-23 08:46:27 -07001899 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001900 patch->sinks[0].sample_rate,
1901 patch->sinks[0].format,
1902 patch->sinks[0].channel_mask,
1903 AUDIO_OUTPUT_FLAG_NONE)) {
1904 return INVALID_OPERATION;
1905 }
1906 // TODO: reconfigure output format and channels here
1907 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001908 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001909 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001910 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001911 true,
1912 handle);
1913 index = mAudioPatches.indexOfKey(*handle);
1914 if (index >= 0) {
1915 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1916 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1917 }
1918 patchDesc = mAudioPatches.valueAt(index);
1919 patchDesc->mUid = uid;
1920 ALOGV("createAudioPatch() success");
1921 } else {
1922 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1923 return INVALID_OPERATION;
1924 }
1925 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1926 // device to device connection
1927 if (patchDesc != 0) {
1928 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1929 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1930 return BAD_VALUE;
1931 }
1932 }
1933
1934 sp<DeviceDescriptor> srcDeviceDesc =
1935 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1936 sp<DeviceDescriptor> sinkDeviceDesc =
1937 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1938 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1939 return BAD_VALUE;
1940 }
1941 //update source and sink with our own data as the data passed in the patch may
1942 // be incomplete.
1943 struct audio_patch newPatch = *patch;
1944 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1945 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1946
1947 // TODO: add support for devices on different HW modules
1948 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1949 return INVALID_OPERATION;
1950 }
1951 // TODO: check from routing capabilities in config file and other conflicting patches
1952
1953 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1954 if (index >= 0) {
1955 afPatchHandle = patchDesc->mAfPatchHandle;
1956 }
1957
1958 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1959 &afPatchHandle,
1960 0);
1961 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1962 status, afPatchHandle);
1963 if (status == NO_ERROR) {
1964 if (index < 0) {
1965 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1966 &newPatch, uid);
1967 addAudioPatch(patchDesc->mHandle, patchDesc);
1968 } else {
1969 patchDesc->mPatch = newPatch;
1970 }
1971 patchDesc->mAfPatchHandle = afPatchHandle;
1972 *handle = patchDesc->mHandle;
1973 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001974 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001975 } else {
1976 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1977 status);
1978 return INVALID_OPERATION;
1979 }
1980 } else {
1981 return BAD_VALUE;
1982 }
1983 } else {
1984 return BAD_VALUE;
1985 }
1986 return NO_ERROR;
1987}
1988
1989status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1990 uid_t uid)
1991{
1992 ALOGV("releaseAudioPatch() patch %d", handle);
1993
1994 ssize_t index = mAudioPatches.indexOfKey(handle);
1995
1996 if (index < 0) {
1997 return BAD_VALUE;
1998 }
1999 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2000 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2001 mUidCached, patchDesc->mUid, uid);
2002 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2003 return INVALID_OPERATION;
2004 }
2005
2006 struct audio_patch *patch = &patchDesc->mPatch;
2007 patchDesc->mUid = mUidCached;
2008 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002009 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002010 if (outputDesc == NULL) {
2011 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2012 return BAD_VALUE;
2013 }
2014
2015 setOutputDevice(outputDesc->mIoHandle,
2016 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2017 true,
2018 0,
2019 NULL);
2020 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2021 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002022 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002023 if (inputDesc == NULL) {
2024 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2025 return BAD_VALUE;
2026 }
2027 setInputDevice(inputDesc->mIoHandle,
2028 getNewInputDevice(inputDesc->mIoHandle),
2029 true,
2030 NULL);
2031 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2032 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2033 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2034 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2035 status, patchDesc->mAfPatchHandle);
2036 removeAudioPatch(patchDesc->mHandle);
2037 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002038 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002039 } else {
2040 return BAD_VALUE;
2041 }
2042 } else {
2043 return BAD_VALUE;
2044 }
2045 return NO_ERROR;
2046}
2047
2048status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2049 struct audio_patch *patches,
2050 unsigned int *generation)
2051{
2052 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2053 generation == NULL) {
2054 return BAD_VALUE;
2055 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002056 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002057 *num_patches, patches, mAudioPatches.size());
2058 if (patches == NULL) {
2059 *num_patches = 0;
2060 }
2061
2062 size_t patchesWritten = 0;
2063 size_t patchesMax = *num_patches;
2064 for (size_t i = 0;
2065 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2066 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2067 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002068 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002069 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2070 }
2071 *num_patches = mAudioPatches.size();
2072
2073 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002074 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002075 return NO_ERROR;
2076}
2077
Eric Laurente1715a42014-05-20 11:30:42 -07002078status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002079{
Eric Laurente1715a42014-05-20 11:30:42 -07002080 ALOGV("setAudioPortConfig()");
2081
2082 if (config == NULL) {
2083 return BAD_VALUE;
2084 }
2085 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2086 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002087 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2088 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002089 }
2090
Eric Laurenta121f902014-06-03 13:32:54 -07002091 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002092 if (config->type == AUDIO_PORT_TYPE_MIX) {
2093 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002094 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002095 if (outputDesc == NULL) {
2096 return BAD_VALUE;
2097 }
Eric Laurent84c70242014-06-23 08:46:27 -07002098 ALOG_ASSERT(!outputDesc->isDuplicated(),
2099 "setAudioPortConfig() called on duplicated output %d",
2100 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002101 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002102 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002103 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002104 if (inputDesc == NULL) {
2105 return BAD_VALUE;
2106 }
Eric Laurenta121f902014-06-03 13:32:54 -07002107 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002108 } else {
2109 return BAD_VALUE;
2110 }
2111 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2112 sp<DeviceDescriptor> deviceDesc;
2113 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2114 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2115 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2116 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2117 } else {
2118 return BAD_VALUE;
2119 }
2120 if (deviceDesc == NULL) {
2121 return BAD_VALUE;
2122 }
Eric Laurenta121f902014-06-03 13:32:54 -07002123 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002124 } else {
2125 return BAD_VALUE;
2126 }
2127
Eric Laurenta121f902014-06-03 13:32:54 -07002128 struct audio_port_config backupConfig;
2129 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2130 if (status == NO_ERROR) {
2131 struct audio_port_config newConfig;
2132 audioPortConfig->toAudioPortConfig(&newConfig, config);
2133 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002134 }
Eric Laurenta121f902014-06-03 13:32:54 -07002135 if (status != NO_ERROR) {
2136 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002137 }
Eric Laurente1715a42014-05-20 11:30:42 -07002138
2139 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002140}
2141
2142void AudioPolicyManager::clearAudioPatches(uid_t uid)
2143{
2144 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2145 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2146 if (patchDesc->mUid == uid) {
2147 // releaseAudioPatch() removes the patch from mAudioPatches
2148 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2149 i--;
2150 }
2151 }
2152 }
2153}
2154
2155status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2156 const sp<AudioPatch>& patch)
2157{
2158 ssize_t index = mAudioPatches.indexOfKey(handle);
2159
2160 if (index >= 0) {
2161 ALOGW("addAudioPatch() patch %d already in", handle);
2162 return ALREADY_EXISTS;
2163 }
2164 mAudioPatches.add(handle, patch);
2165 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2166 "sink handle %d",
2167 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2168 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2169 return NO_ERROR;
2170}
2171
2172status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2173{
2174 ssize_t index = mAudioPatches.indexOfKey(handle);
2175
2176 if (index < 0) {
2177 ALOGW("removeAudioPatch() patch %d not in", handle);
2178 return ALREADY_EXISTS;
2179 }
2180 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2181 mAudioPatches.valueAt(index)->mAfPatchHandle);
2182 mAudioPatches.removeItemsAt(index);
2183 return NO_ERROR;
2184}
2185
Eric Laurente552edb2014-03-10 17:42:56 -07002186// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002187// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002188// ----------------------------------------------------------------------------
2189
Eric Laurent3a4311c2014-03-17 12:00:47 -07002190uint32_t AudioPolicyManager::nextUniqueId()
2191{
2192 return android_atomic_inc(&mNextUniqueId);
2193}
2194
Eric Laurent6a94d692014-05-20 11:18:06 -07002195uint32_t AudioPolicyManager::nextAudioPortGeneration()
2196{
2197 return android_atomic_inc(&mAudioPortGeneration);
2198}
2199
Eric Laurente0720872014-03-11 09:30:41 -07002200AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002201 :
2202#ifdef AUDIO_POLICY_TEST
2203 Thread(false),
2204#endif //AUDIO_POLICY_TEST
2205 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002206 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002207 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2208 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002209 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002210 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2211 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002212{
Eric Laurent6a94d692014-05-20 11:18:06 -07002213 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002214 mpClientInterface = clientInterface;
2215
Eric Laurent3b73df72014-03-11 09:06:29 -07002216 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2217 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002218 }
2219
Eric Laurent1afeecb2014-05-14 08:52:28 -07002220 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002221 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2222 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2223 ALOGE("could not load audio policy configuration file, setting defaults");
2224 defaultAudioPolicyConfig();
2225 }
2226 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002227 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002228
2229 // must be done after reading the policy
2230 initializeVolumeCurves();
2231
2232 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002233 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2234 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002235 for (size_t i = 0; i < mHwModules.size(); i++) {
2236 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2237 if (mHwModules[i]->mHandle == 0) {
2238 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2239 continue;
2240 }
2241 // open all output streams needed to access attached devices
2242 // except for direct output streams that are only opened when they are actually
2243 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002244 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002245 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2246 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002247 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002248
Eric Laurent3a4311c2014-03-17 12:00:47 -07002249 if (outProfile->mSupportedDevices.isEmpty()) {
2250 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2251 continue;
2252 }
2253
2254 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2255 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002256 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002257 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002258
Eric Laurent1c333e22014-05-20 10:48:17 -07002259 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002260 audio_io_handle_t output = mpClientInterface->openOutput(
2261 outProfile->mModule->mHandle,
2262 &outputDesc->mDevice,
2263 &outputDesc->mSamplingRate,
2264 &outputDesc->mFormat,
2265 &outputDesc->mChannelMask,
2266 &outputDesc->mLatency,
2267 outputDesc->mFlags);
2268 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002269 ALOGW("Cannot open output stream for device %08x on hw module %s",
2270 outputDesc->mDevice,
2271 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002272 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002273 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002274 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002275 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002276 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002277 // give a valid ID to an attached device once confirmed it is reachable
2278 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2279 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002280 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002281 }
2282 }
Eric Laurente552edb2014-03-10 17:42:56 -07002283 if (mPrimaryOutput == 0 &&
2284 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2285 mPrimaryOutput = output;
2286 }
2287 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002288 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002289 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002290 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002291 true);
2292 }
2293 }
2294 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002295 // open input streams needed to access attached devices to validate
2296 // mAvailableInputDevices list
2297 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2298 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002299 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002300
Eric Laurent3a4311c2014-03-17 12:00:47 -07002301 if (inProfile->mSupportedDevices.isEmpty()) {
2302 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2303 continue;
2304 }
2305
2306 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2307 if (profileTypes & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002308 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002309
2310 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002311 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002312 audio_io_handle_t input = mpClientInterface->openInput(
2313 inProfile->mModule->mHandle,
2314 &inputDesc->mDevice,
2315 &inputDesc->mSamplingRate,
2316 &inputDesc->mFormat,
2317 &inputDesc->mChannelMask);
2318
2319 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002320 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002321 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002322 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002323 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002324 // give a valid ID to an attached device once confirmed it is reachable
2325 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2326 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002327 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002328 }
2329 }
2330 mpClientInterface->closeInput(input);
2331 } else {
2332 ALOGW("Cannot open input stream for device %08x on hw module %s",
2333 inputDesc->mDevice,
2334 mHwModules[i]->mName);
2335 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002336 }
2337 }
2338 }
2339 // make sure all attached devices have been allocated a unique ID
2340 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2341 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002342 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002343 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2344 continue;
2345 }
2346 i++;
2347 }
2348 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2349 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002350 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002351 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2352 continue;
2353 }
2354 i++;
2355 }
2356 // make sure default device is reachable
2357 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002358 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002359 }
Eric Laurente552edb2014-03-10 17:42:56 -07002360
2361 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2362
2363 updateDevicesAndOutputs();
2364
2365#ifdef AUDIO_POLICY_TEST
2366 if (mPrimaryOutput != 0) {
2367 AudioParameter outputCmd = AudioParameter();
2368 outputCmd.addInt(String8("set_id"), 0);
2369 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2370
2371 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2372 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002373 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2374 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002375 mTestLatencyMs = 0;
2376 mCurOutput = 0;
2377 mDirectOutput = false;
2378 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2379 mTestOutputs[i] = 0;
2380 }
2381
2382 const size_t SIZE = 256;
2383 char buffer[SIZE];
2384 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2385 run(buffer, ANDROID_PRIORITY_AUDIO);
2386 }
2387#endif //AUDIO_POLICY_TEST
2388}
2389
Eric Laurente0720872014-03-11 09:30:41 -07002390AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002391{
2392#ifdef AUDIO_POLICY_TEST
2393 exit();
2394#endif //AUDIO_POLICY_TEST
2395 for (size_t i = 0; i < mOutputs.size(); i++) {
2396 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002397 }
2398 for (size_t i = 0; i < mInputs.size(); i++) {
2399 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002400 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002401 mAvailableOutputDevices.clear();
2402 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002403 mOutputs.clear();
2404 mInputs.clear();
2405 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002406}
2407
Eric Laurente0720872014-03-11 09:30:41 -07002408status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002409{
2410 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2411}
2412
2413#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002414bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002415{
2416 ALOGV("entering threadLoop()");
2417 while (!exitPending())
2418 {
2419 String8 command;
2420 int valueInt;
2421 String8 value;
2422
2423 Mutex::Autolock _l(mLock);
2424 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2425
2426 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2427 AudioParameter param = AudioParameter(command);
2428
2429 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2430 valueInt != 0) {
2431 ALOGV("Test command %s received", command.string());
2432 String8 target;
2433 if (param.get(String8("target"), target) != NO_ERROR) {
2434 target = "Manager";
2435 }
2436 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2437 param.remove(String8("test_cmd_policy_output"));
2438 mCurOutput = valueInt;
2439 }
2440 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2441 param.remove(String8("test_cmd_policy_direct"));
2442 if (value == "false") {
2443 mDirectOutput = false;
2444 } else if (value == "true") {
2445 mDirectOutput = true;
2446 }
2447 }
2448 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2449 param.remove(String8("test_cmd_policy_input"));
2450 mTestInput = valueInt;
2451 }
2452
2453 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2454 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002455 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002456 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002457 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002458 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002459 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002460 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002461 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002462 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002463 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002464 if (target == "Manager") {
2465 mTestFormat = format;
2466 } else if (mTestOutputs[mCurOutput] != 0) {
2467 AudioParameter outputParam = AudioParameter();
2468 outputParam.addInt(String8("format"), format);
2469 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2470 }
2471 }
2472 }
2473 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2474 param.remove(String8("test_cmd_policy_channels"));
2475 int channels = 0;
2476
2477 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002478 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002479 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002480 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002481 }
2482 if (channels != 0) {
2483 if (target == "Manager") {
2484 mTestChannels = channels;
2485 } else if (mTestOutputs[mCurOutput] != 0) {
2486 AudioParameter outputParam = AudioParameter();
2487 outputParam.addInt(String8("channels"), channels);
2488 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2489 }
2490 }
2491 }
2492 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2493 param.remove(String8("test_cmd_policy_sampleRate"));
2494 if (valueInt >= 0 && valueInt <= 96000) {
2495 int samplingRate = valueInt;
2496 if (target == "Manager") {
2497 mTestSamplingRate = samplingRate;
2498 } else if (mTestOutputs[mCurOutput] != 0) {
2499 AudioParameter outputParam = AudioParameter();
2500 outputParam.addInt(String8("sampling_rate"), samplingRate);
2501 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2502 }
2503 }
2504 }
2505
2506 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2507 param.remove(String8("test_cmd_policy_reopen"));
2508
Eric Laurent1f2f2232014-06-02 12:01:23 -07002509 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002510 mpClientInterface->closeOutput(mPrimaryOutput);
2511
2512 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2513
Eric Laurente552edb2014-03-10 17:42:56 -07002514 mOutputs.removeItem(mPrimaryOutput);
2515
Eric Laurent1f2f2232014-06-02 12:01:23 -07002516 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002517 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2518 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2519 &outputDesc->mDevice,
2520 &outputDesc->mSamplingRate,
2521 &outputDesc->mFormat,
2522 &outputDesc->mChannelMask,
2523 &outputDesc->mLatency,
2524 outputDesc->mFlags);
2525 if (mPrimaryOutput == 0) {
2526 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2527 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2528 } else {
2529 AudioParameter outputCmd = AudioParameter();
2530 outputCmd.addInt(String8("set_id"), 0);
2531 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2532 addOutput(mPrimaryOutput, outputDesc);
2533 }
2534 }
2535
2536
2537 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2538 }
2539 }
2540 return false;
2541}
2542
Eric Laurente0720872014-03-11 09:30:41 -07002543void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002544{
2545 {
2546 AutoMutex _l(mLock);
2547 requestExit();
2548 mWaitWorkCV.signal();
2549 }
2550 requestExitAndWait();
2551}
2552
Eric Laurente0720872014-03-11 09:30:41 -07002553int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002554{
2555 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2556 if (output == mTestOutputs[i]) return i;
2557 }
2558 return 0;
2559}
2560#endif //AUDIO_POLICY_TEST
2561
2562// ---
2563
Eric Laurent1f2f2232014-06-02 12:01:23 -07002564void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002565{
Eric Laurent1c333e22014-05-20 10:48:17 -07002566 outputDesc->mIoHandle = output;
2567 outputDesc->mId = nextUniqueId();
2568 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002569 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002570}
2571
Eric Laurent1f2f2232014-06-02 12:01:23 -07002572void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002573{
Eric Laurent1c333e22014-05-20 10:48:17 -07002574 inputDesc->mIoHandle = input;
2575 inputDesc->mId = nextUniqueId();
2576 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002577 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002578}
Eric Laurente552edb2014-03-10 17:42:56 -07002579
Eric Laurent3a4311c2014-03-17 12:00:47 -07002580String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2581{
2582 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2583 return String8("a2dp_sink_address=")+address;
2584 }
2585 return address;
2586}
2587
Eric Laurente0720872014-03-11 09:30:41 -07002588status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002589 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002590 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002591 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002592{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002593 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002594
Eric Laurent3b73df72014-03-11 09:06:29 -07002595 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002596 // first list already open outputs that can be routed to this device
2597 for (size_t i = 0; i < mOutputs.size(); i++) {
2598 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002599 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002600 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2601 outputs.add(mOutputs.keyAt(i));
2602 }
2603 }
2604 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002605 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002606 for (size_t i = 0; i < mHwModules.size(); i++)
2607 {
2608 if (mHwModules[i]->mHandle == 0) {
2609 continue;
2610 }
2611 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2612 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002613 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002614 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002615 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2616 }
2617 }
2618 }
2619
2620 if (profiles.isEmpty() && outputs.isEmpty()) {
2621 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2622 return BAD_VALUE;
2623 }
2624
2625 // open outputs for matching profiles if needed. Direct outputs are also opened to
2626 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2627 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002628 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002629
2630 // nothing to do if one output is already opened for this profile
2631 size_t j;
2632 for (j = 0; j < mOutputs.size(); j++) {
2633 desc = mOutputs.valueAt(j);
2634 if (!desc->isDuplicated() && desc->mProfile == profile) {
2635 break;
2636 }
2637 }
2638 if (j != mOutputs.size()) {
2639 continue;
2640 }
2641
Eric Laurent3a4311c2014-03-17 12:00:47 -07002642 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002643 desc = new AudioOutputDescriptor(profile);
2644 desc->mDevice = device;
2645 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2646 offloadInfo.sample_rate = desc->mSamplingRate;
2647 offloadInfo.format = desc->mFormat;
2648 offloadInfo.channel_mask = desc->mChannelMask;
2649
2650 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2651 &desc->mDevice,
2652 &desc->mSamplingRate,
2653 &desc->mFormat,
2654 &desc->mChannelMask,
2655 &desc->mLatency,
2656 desc->mFlags,
2657 &offloadInfo);
2658 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002659 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002660 if (!address.isEmpty()) {
2661 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002662 }
2663
Eric Laurentd4692962014-05-05 18:13:44 -07002664 // Here is where we step through and resolve any "dynamic" fields
2665 String8 reply;
2666 char *value;
2667 if (profile->mSamplingRates[0] == 0) {
2668 reply = mpClientInterface->getParameters(output,
2669 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2670 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2671 reply.string());
2672 value = strpbrk((char *)reply.string(), "=");
2673 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002674 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002675 }
Eric Laurentd4692962014-05-05 18:13:44 -07002676 }
2677 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2678 reply = mpClientInterface->getParameters(output,
2679 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2680 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2681 reply.string());
2682 value = strpbrk((char *)reply.string(), "=");
2683 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002684 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002685 }
Eric Laurentd4692962014-05-05 18:13:44 -07002686 }
2687 if (profile->mChannelMasks[0] == 0) {
2688 reply = mpClientInterface->getParameters(output,
2689 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2690 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2691 reply.string());
2692 value = strpbrk((char *)reply.string(), "=");
2693 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002694 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002695 }
Eric Laurentd4692962014-05-05 18:13:44 -07002696 }
2697 if (((profile->mSamplingRates[0] == 0) &&
2698 (profile->mSamplingRates.size() < 2)) ||
2699 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2700 (profile->mFormats.size() < 2)) ||
2701 ((profile->mChannelMasks[0] == 0) &&
2702 (profile->mChannelMasks.size() < 2))) {
2703 ALOGW("checkOutputsForDevice() direct output missing param");
2704 mpClientInterface->closeOutput(output);
2705 output = 0;
2706 } else if (profile->mSamplingRates[0] == 0) {
2707 mpClientInterface->closeOutput(output);
2708 desc->mSamplingRate = profile->mSamplingRates[1];
2709 offloadInfo.sample_rate = desc->mSamplingRate;
2710 output = mpClientInterface->openOutput(
2711 profile->mModule->mHandle,
2712 &desc->mDevice,
2713 &desc->mSamplingRate,
2714 &desc->mFormat,
2715 &desc->mChannelMask,
2716 &desc->mLatency,
2717 desc->mFlags,
2718 &offloadInfo);
2719 }
2720
2721 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002722 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002723 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2724 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002725
Eric Laurentd4692962014-05-05 18:13:44 -07002726 // set initial stream volume for device
2727 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002728
Eric Laurentd4692962014-05-05 18:13:44 -07002729 //TODO: configure audio effect output stage here
2730
2731 // open a duplicating output thread for the new output and the primary output
2732 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2733 mPrimaryOutput);
2734 if (duplicatedOutput != 0) {
2735 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002736 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002737 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2738 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2739 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2740 dupOutputDesc->mFormat = desc->mFormat;
2741 dupOutputDesc->mChannelMask = desc->mChannelMask;
2742 dupOutputDesc->mLatency = desc->mLatency;
2743 addOutput(duplicatedOutput, dupOutputDesc);
2744 applyStreamVolumes(duplicatedOutput, device, 0, true);
2745 } else {
2746 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2747 mPrimaryOutput, output);
2748 mpClientInterface->closeOutput(output);
2749 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002750 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002751 output = 0;
2752 }
Eric Laurente552edb2014-03-10 17:42:56 -07002753 }
2754 }
2755 }
2756 if (output == 0) {
2757 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002758 profiles.removeAt(profile_index);
2759 profile_index--;
2760 } else {
2761 outputs.add(output);
2762 ALOGV("checkOutputsForDevice(): adding output %d", output);
2763 }
2764 }
2765
2766 if (profiles.isEmpty()) {
2767 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2768 return BAD_VALUE;
2769 }
Eric Laurentd4692962014-05-05 18:13:44 -07002770 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002771 // check if one opened output is not needed any more after disconnecting one device
2772 for (size_t i = 0; i < mOutputs.size(); i++) {
2773 desc = mOutputs.valueAt(i);
2774 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002775 !(desc->mProfile->mSupportedDevices.types() &
2776 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002777 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2778 outputs.add(mOutputs.keyAt(i));
2779 }
2780 }
Eric Laurentd4692962014-05-05 18:13:44 -07002781 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002782 for (size_t i = 0; i < mHwModules.size(); i++)
2783 {
2784 if (mHwModules[i]->mHandle == 0) {
2785 continue;
2786 }
2787 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2788 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002789 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002790 if (profile->mSupportedDevices.types() & device) {
2791 ALOGV("checkOutputsForDevice(): "
2792 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002793 if (profile->mSamplingRates[0] == 0) {
2794 profile->mSamplingRates.clear();
2795 profile->mSamplingRates.add(0);
2796 }
2797 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2798 profile->mFormats.clear();
2799 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2800 }
2801 if (profile->mChannelMasks[0] == 0) {
2802 profile->mChannelMasks.clear();
2803 profile->mChannelMasks.add(0);
2804 }
2805 }
2806 }
2807 }
2808 }
2809 return NO_ERROR;
2810}
2811
Eric Laurentd4692962014-05-05 18:13:44 -07002812status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2813 audio_policy_dev_state_t state,
2814 SortedVector<audio_io_handle_t>& inputs,
2815 const String8 address)
2816{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002817 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002818 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2819 // first list already open inputs that can be routed to this device
2820 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2821 desc = mInputs.valueAt(input_index);
2822 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2823 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2824 inputs.add(mInputs.keyAt(input_index));
2825 }
2826 }
2827
2828 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002829 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002830 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2831 {
2832 if (mHwModules[module_idx]->mHandle == 0) {
2833 continue;
2834 }
2835 for (size_t profile_index = 0;
2836 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2837 profile_index++)
2838 {
2839 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2840 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002841 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002842 profile_index, module_idx);
2843 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2844 }
2845 }
2846 }
2847
2848 if (profiles.isEmpty() && inputs.isEmpty()) {
2849 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2850 return BAD_VALUE;
2851 }
2852
2853 // open inputs for matching profiles if needed. Direct inputs are also opened to
2854 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2855 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2856
Eric Laurent1c333e22014-05-20 10:48:17 -07002857 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002858 // nothing to do if one input is already opened for this profile
2859 size_t input_index;
2860 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2861 desc = mInputs.valueAt(input_index);
2862 if (desc->mProfile == profile) {
2863 break;
2864 }
2865 }
2866 if (input_index != mInputs.size()) {
2867 continue;
2868 }
2869
2870 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2871 desc = new AudioInputDescriptor(profile);
2872 desc->mDevice = device;
2873
2874 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2875 &desc->mDevice,
2876 &desc->mSamplingRate,
2877 &desc->mFormat,
2878 &desc->mChannelMask);
2879
2880 if (input != 0) {
2881 if (!address.isEmpty()) {
2882 mpClientInterface->setParameters(input, addressToParameter(device, address));
2883 }
2884
2885 // Here is where we step through and resolve any "dynamic" fields
2886 String8 reply;
2887 char *value;
2888 if (profile->mSamplingRates[0] == 0) {
2889 reply = mpClientInterface->getParameters(input,
2890 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2891 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2892 reply.string());
2893 value = strpbrk((char *)reply.string(), "=");
2894 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002895 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002896 }
2897 }
2898 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2899 reply = mpClientInterface->getParameters(input,
2900 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2901 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2902 value = strpbrk((char *)reply.string(), "=");
2903 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002904 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002905 }
2906 }
2907 if (profile->mChannelMasks[0] == 0) {
2908 reply = mpClientInterface->getParameters(input,
2909 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2910 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2911 reply.string());
2912 value = strpbrk((char *)reply.string(), "=");
2913 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002914 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002915 }
2916 }
2917 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2918 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2919 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2920 ALOGW("checkInputsForDevice() direct input missing param");
2921 mpClientInterface->closeInput(input);
2922 input = 0;
2923 }
2924
2925 if (input != 0) {
2926 addInput(input, desc);
2927 }
2928 } // endif input != 0
2929
2930 if (input == 0) {
2931 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07002932 profiles.removeAt(profile_index);
2933 profile_index--;
2934 } else {
2935 inputs.add(input);
2936 ALOGV("checkInputsForDevice(): adding input %d", input);
2937 }
2938 } // end scan profiles
2939
2940 if (profiles.isEmpty()) {
2941 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2942 return BAD_VALUE;
2943 }
2944 } else {
2945 // Disconnect
2946 // check if one opened input is not needed any more after disconnecting one device
2947 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2948 desc = mInputs.valueAt(input_index);
2949 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2950 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2951 mInputs.keyAt(input_index));
2952 inputs.add(mInputs.keyAt(input_index));
2953 }
2954 }
2955 // Clear any profiles associated with the disconnected device.
2956 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2957 if (mHwModules[module_index]->mHandle == 0) {
2958 continue;
2959 }
2960 for (size_t profile_index = 0;
2961 profile_index < mHwModules[module_index]->mInputProfiles.size();
2962 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002963 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002964 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002965 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002966 profile_index, module_index);
2967 if (profile->mSamplingRates[0] == 0) {
2968 profile->mSamplingRates.clear();
2969 profile->mSamplingRates.add(0);
2970 }
2971 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2972 profile->mFormats.clear();
2973 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2974 }
2975 if (profile->mChannelMasks[0] == 0) {
2976 profile->mChannelMasks.clear();
2977 profile->mChannelMasks.add(0);
2978 }
2979 }
2980 }
2981 }
2982 } // end disconnect
2983
2984 return NO_ERROR;
2985}
2986
2987
Eric Laurente0720872014-03-11 09:30:41 -07002988void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002989{
2990 ALOGV("closeOutput(%d)", output);
2991
Eric Laurent1f2f2232014-06-02 12:01:23 -07002992 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07002993 if (outputDesc == NULL) {
2994 ALOGW("closeOutput() unknown output %d", output);
2995 return;
2996 }
2997
2998 // look for duplicated outputs connected to the output being removed.
2999 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003000 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003001 if (dupOutputDesc->isDuplicated() &&
3002 (dupOutputDesc->mOutput1 == outputDesc ||
3003 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003004 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003005 if (dupOutputDesc->mOutput1 == outputDesc) {
3006 outputDesc2 = dupOutputDesc->mOutput2;
3007 } else {
3008 outputDesc2 = dupOutputDesc->mOutput1;
3009 }
3010 // As all active tracks on duplicated output will be deleted,
3011 // and as they were also referenced on the other output, the reference
3012 // count for their stream type must be adjusted accordingly on
3013 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003014 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003015 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003016 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003017 }
3018 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3019 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3020
3021 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003022 mOutputs.removeItem(duplicatedOutput);
3023 }
3024 }
3025
3026 AudioParameter param;
3027 param.add(String8("closing"), String8("true"));
3028 mpClientInterface->setParameters(output, param.toString());
3029
3030 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003031 mOutputs.removeItem(output);
3032 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003033 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003034}
3035
Eric Laurente0720872014-03-11 09:30:41 -07003036SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003037 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003038{
3039 SortedVector<audio_io_handle_t> outputs;
3040
3041 ALOGVV("getOutputsForDevice() device %04x", device);
3042 for (size_t i = 0; i < openOutputs.size(); i++) {
3043 ALOGVV("output %d isDuplicated=%d device=%04x",
3044 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3045 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3046 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3047 outputs.add(openOutputs.keyAt(i));
3048 }
3049 }
3050 return outputs;
3051}
3052
Eric Laurente0720872014-03-11 09:30:41 -07003053bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003054 SortedVector<audio_io_handle_t>& outputs2)
3055{
3056 if (outputs1.size() != outputs2.size()) {
3057 return false;
3058 }
3059 for (size_t i = 0; i < outputs1.size(); i++) {
3060 if (outputs1[i] != outputs2[i]) {
3061 return false;
3062 }
3063 }
3064 return true;
3065}
3066
Eric Laurente0720872014-03-11 09:30:41 -07003067void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003068{
3069 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3070 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3071 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3072 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3073
3074 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3075 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3076 strategy, srcOutputs[0], dstOutputs[0]);
3077 // mute strategy while moving tracks from one output to another
3078 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003079 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003080 if (desc->isStrategyActive(strategy)) {
3081 setStrategyMute(strategy, true, srcOutputs[i]);
3082 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3083 }
3084 }
3085
3086 // Move effects associated to this strategy from previous output to new output
3087 if (strategy == STRATEGY_MEDIA) {
3088 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3089 SortedVector<audio_io_handle_t> moved;
3090 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003091 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3092 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3093 effectDesc->mIo != fxOutput) {
3094 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003095 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3096 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003097 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003098 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003099 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003100 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003101 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003102 }
3103 }
3104 }
3105 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003106 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3107 if (getStrategy((audio_stream_type_t)i) == strategy) {
3108 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003109 }
3110 }
3111 }
3112}
3113
Eric Laurente0720872014-03-11 09:30:41 -07003114void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003115{
3116 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3117 checkOutputForStrategy(STRATEGY_PHONE);
3118 checkOutputForStrategy(STRATEGY_SONIFICATION);
3119 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3120 checkOutputForStrategy(STRATEGY_MEDIA);
3121 checkOutputForStrategy(STRATEGY_DTMF);
3122}
3123
Eric Laurente0720872014-03-11 09:30:41 -07003124audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003125{
Eric Laurente552edb2014-03-10 17:42:56 -07003126 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003127 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003128 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3129 return mOutputs.keyAt(i);
3130 }
3131 }
3132
3133 return 0;
3134}
3135
Eric Laurente0720872014-03-11 09:30:41 -07003136void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003137{
Eric Laurente552edb2014-03-10 17:42:56 -07003138 audio_io_handle_t a2dpOutput = getA2dpOutput();
3139 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003140 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003141 return;
3142 }
3143
Eric Laurent3a4311c2014-03-17 12:00:47 -07003144 bool isScoConnected =
3145 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003146 // suspend A2DP output if:
3147 // (NOT already suspended) &&
3148 // ((SCO device is connected &&
3149 // (forced usage for communication || for record is SCO))) ||
3150 // (phone state is ringing || in call)
3151 //
3152 // restore A2DP output if:
3153 // (Already suspended) &&
3154 // ((SCO device is NOT connected ||
3155 // (forced usage NOT for communication && NOT for record is SCO))) &&
3156 // (phone state is NOT ringing && NOT in call)
3157 //
3158 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003159 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003160 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3161 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3162 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3163 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003164
3165 mpClientInterface->restoreOutput(a2dpOutput);
3166 mA2dpSuspended = false;
3167 }
3168 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003169 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003170 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3171 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3172 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3173 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003174
3175 mpClientInterface->suspendOutput(a2dpOutput);
3176 mA2dpSuspended = true;
3177 }
3178 }
3179}
3180
Eric Laurent1c333e22014-05-20 10:48:17 -07003181audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003182{
3183 audio_devices_t device = AUDIO_DEVICE_NONE;
3184
Eric Laurent1f2f2232014-06-02 12:01:23 -07003185 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003186
3187 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3188 if (index >= 0) {
3189 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3190 if (patchDesc->mUid != mUidCached) {
3191 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3192 outputDesc->device(), outputDesc->mPatchHandle);
3193 return outputDesc->device();
3194 }
3195 }
3196
Eric Laurente552edb2014-03-10 17:42:56 -07003197 // check the following by order of priority to request a routing change if necessary:
3198 // 1: the strategy enforced audible is active on the output:
3199 // use device for strategy enforced audible
3200 // 2: we are in call or the strategy phone is active on the output:
3201 // use device for strategy phone
3202 // 3: the strategy sonification is active on the output:
3203 // use device for strategy sonification
3204 // 4: the strategy "respectful" sonification is active on the output:
3205 // use device for strategy "respectful" sonification
3206 // 5: the strategy media is active on the output:
3207 // use device for strategy media
3208 // 6: the strategy DTMF is active on the output:
3209 // use device for strategy DTMF
3210 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3211 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3212 } else if (isInCall() ||
3213 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3214 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3215 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3216 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3217 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3218 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3219 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3220 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3221 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3222 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3223 }
3224
Eric Laurent1c333e22014-05-20 10:48:17 -07003225 ALOGV("getNewOutputDevice() selected device %x", device);
3226 return device;
3227}
3228
3229audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3230{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003231 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003232
3233 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3234 if (index >= 0) {
3235 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3236 if (patchDesc->mUid != mUidCached) {
3237 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3238 inputDesc->mDevice, inputDesc->mPatchHandle);
3239 return inputDesc->mDevice;
3240 }
3241 }
3242
Eric Laurent1c333e22014-05-20 10:48:17 -07003243 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3244
3245 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003246 return device;
3247}
3248
Eric Laurente0720872014-03-11 09:30:41 -07003249uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003250 return (uint32_t)getStrategy(stream);
3251}
3252
Eric Laurente0720872014-03-11 09:30:41 -07003253audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003254 // By checking the range of stream before calling getStrategy, we avoid
3255 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3256 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003257 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003258 return AUDIO_DEVICE_NONE;
3259 }
3260 audio_devices_t devices;
3261 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3262 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3263 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3264 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003265 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003266 if (outputDesc->isStrategyActive(strategy)) {
3267 devices = outputDesc->device();
3268 break;
3269 }
Eric Laurente552edb2014-03-10 17:42:56 -07003270 }
3271 return devices;
3272}
3273
Eric Laurente0720872014-03-11 09:30:41 -07003274AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003275 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003276 // stream to strategy mapping
3277 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003278 case AUDIO_STREAM_VOICE_CALL:
3279 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003280 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003281 case AUDIO_STREAM_RING:
3282 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003283 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003284 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003285 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003286 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003287 return STRATEGY_DTMF;
3288 default:
3289 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003290 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003291 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3292 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003293 case AUDIO_STREAM_TTS:
3294 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003295 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003296 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003297 return STRATEGY_ENFORCED_AUDIBLE;
3298 }
3299}
3300
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003301uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3302 // flags to strategy mapping
3303 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3304 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3305 }
3306
3307 // usage to strategy mapping
3308 switch (attr->usage) {
3309 case AUDIO_USAGE_MEDIA:
3310 case AUDIO_USAGE_GAME:
3311 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3312 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3313 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3314 return (uint32_t) STRATEGY_MEDIA;
3315
3316 case AUDIO_USAGE_VOICE_COMMUNICATION:
3317 return (uint32_t) STRATEGY_PHONE;
3318
3319 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3320 return (uint32_t) STRATEGY_DTMF;
3321
3322 case AUDIO_USAGE_ALARM:
3323 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3324 return (uint32_t) STRATEGY_SONIFICATION;
3325
3326 case AUDIO_USAGE_NOTIFICATION:
3327 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3328 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3329 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3330 case AUDIO_USAGE_NOTIFICATION_EVENT:
3331 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3332
3333 case AUDIO_USAGE_UNKNOWN:
3334 default:
3335 return (uint32_t) STRATEGY_MEDIA;
3336 }
3337}
3338
Eric Laurente0720872014-03-11 09:30:41 -07003339void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003340 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003341 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003342 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3343 updateDevicesAndOutputs();
3344 break;
3345 default:
3346 break;
3347 }
3348}
3349
Eric Laurente0720872014-03-11 09:30:41 -07003350audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003351 bool fromCache)
3352{
3353 uint32_t device = AUDIO_DEVICE_NONE;
3354
3355 if (fromCache) {
3356 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3357 strategy, mDeviceForStrategy[strategy]);
3358 return mDeviceForStrategy[strategy];
3359 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003360 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003361 switch (strategy) {
3362
3363 case STRATEGY_SONIFICATION_RESPECTFUL:
3364 if (isInCall()) {
3365 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003366 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003367 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3368 // while media is playing on a remote device, use the the sonification behavior.
3369 // Note that we test this usecase before testing if media is playing because
3370 // the isStreamActive() method only informs about the activity of a stream, not
3371 // if it's for local playback. Note also that we use the same delay between both tests
3372 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003373 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003374 // while media is playing (or has recently played), use the same device
3375 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3376 } else {
3377 // when media is not playing anymore, fall back on the sonification behavior
3378 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3379 }
3380
3381 break;
3382
3383 case STRATEGY_DTMF:
3384 if (!isInCall()) {
3385 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3386 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3387 break;
3388 }
3389 // when in call, DTMF and PHONE strategies follow the same rules
3390 // FALL THROUGH
3391
3392 case STRATEGY_PHONE:
3393 // for phone strategy, we first consider the forced use and then the available devices by order
3394 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003395 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3396 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003397 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003398 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003399 if (device) break;
3400 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003401 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003402 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003403 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003404 if (device) break;
3405 // if SCO device is requested but no SCO device is available, fall back to default case
3406 // FALL THROUGH
3407
3408 default: // FORCE_NONE
3409 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003410 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003411 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003412 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003413 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003414 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003415 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003416 if (device) break;
3417 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003418 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003419 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003420 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003421 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003422 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003423 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003424 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003425 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003426 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003427 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003428 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003429 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003430 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003431 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003432 if (device) break;
3433 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003434 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003435 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003436 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003437 if (device == AUDIO_DEVICE_NONE) {
3438 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3439 }
3440 break;
3441
Eric Laurent3b73df72014-03-11 09:06:29 -07003442 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003443 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3444 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003445 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003446 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003447 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003448 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003449 if (device) break;
3450 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003451 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003452 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003453 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003454 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003455 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003456 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003457 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003458 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003459 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003460 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003461 if (device) break;
3462 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003463 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003464 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003465 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003466 if (device == AUDIO_DEVICE_NONE) {
3467 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3468 }
3469 break;
3470 }
3471 break;
3472
3473 case STRATEGY_SONIFICATION:
3474
3475 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3476 // handleIncallSonification().
3477 if (isInCall()) {
3478 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3479 break;
3480 }
3481 // FALL THROUGH
3482
3483 case STRATEGY_ENFORCED_AUDIBLE:
3484 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3485 // except:
3486 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3487 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3488
3489 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003490 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003491 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003492 if (device == AUDIO_DEVICE_NONE) {
3493 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3494 }
3495 }
3496 // The second device used for sonification is the same as the device used by media strategy
3497 // FALL THROUGH
3498
3499 case STRATEGY_MEDIA: {
3500 uint32_t device2 = AUDIO_DEVICE_NONE;
3501 if (strategy != STRATEGY_SONIFICATION) {
3502 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003503 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003504 }
3505 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003506 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003507 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003508 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003509 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003510 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003511 }
3512 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003513 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003514 }
3515 }
3516 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003517 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003518 }
3519 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003520 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003521 }
3522 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003523 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
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_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003527 }
3528 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003529 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003530 }
3531 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3532 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003533 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003534 }
3535 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003536 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003537 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003538 }
3539 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003540 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003541 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003542 int device3 = AUDIO_DEVICE_NONE;
3543 if (strategy == STRATEGY_MEDIA) {
3544 // Hdmi system audio should use manually configured device type.
3545 if (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]
3546 == AUDIO_POLICY_FORCE_SYSTEM_AUDIO_HDMI_ARC) {
3547 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3548 } else if (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]
3549 == AUDIO_POLICY_FORCE_SYSTEM_AUDIO_SPDIF) {
3550 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF;
3551 } else if (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]
3552 == AUDIO_POLICY_FORCE_SYSTEM_AUDIO_LINE) {
3553 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3554 }
3555 }
Eric Laurente552edb2014-03-10 17:42:56 -07003556
Jungshik Jang839e4f32014-06-26 17:23:40 +09003557 // Merge hdmi cec system audio and existing device for media. If system audio is on,
3558 // internal speaker will be muted but others are not.
3559 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003560 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3561 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3562 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003563
3564 // If system audio mode is on and proper audio out is set, remove speaker from device.
3565 if (device3 != AUDIO_DEVICE_NONE) {
3566 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3567 }
Eric Laurente552edb2014-03-10 17:42:56 -07003568 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003569 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003570 if (device == AUDIO_DEVICE_NONE) {
3571 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3572 }
3573 } break;
3574
3575 default:
3576 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3577 break;
3578 }
3579
3580 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3581 return device;
3582}
3583
Eric Laurente0720872014-03-11 09:30:41 -07003584void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003585{
3586 for (int i = 0; i < NUM_STRATEGIES; i++) {
3587 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3588 }
3589 mPreviousOutputs = mOutputs;
3590}
3591
Eric Laurent1f2f2232014-06-02 12:01:23 -07003592uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003593 audio_devices_t prevDevice,
3594 uint32_t delayMs)
3595{
3596 // mute/unmute strategies using an incompatible device combination
3597 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3598 // if unmuting, unmute only after the specified delay
3599 if (outputDesc->isDuplicated()) {
3600 return 0;
3601 }
3602
3603 uint32_t muteWaitMs = 0;
3604 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003605 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003606
3607 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3608 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3609 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3610 bool doMute = false;
3611
3612 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3613 doMute = true;
3614 outputDesc->mStrategyMutedByDevice[i] = true;
3615 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3616 doMute = true;
3617 outputDesc->mStrategyMutedByDevice[i] = false;
3618 }
Eric Laurent99401132014-05-07 19:48:15 -07003619 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003620 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003621 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003622 // skip output if it does not share any device with current output
3623 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3624 == AUDIO_DEVICE_NONE) {
3625 continue;
3626 }
3627 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3628 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3629 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3630 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3631 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003632 if (mute) {
3633 // FIXME: should not need to double latency if volume could be applied
3634 // immediately by the audioflinger mixer. We must account for the delay
3635 // between now and the next time the audioflinger thread for this output
3636 // will process a buffer (which corresponds to one buffer size,
3637 // usually 1/2 or 1/4 of the latency).
3638 if (muteWaitMs < desc->latency() * 2) {
3639 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003640 }
3641 }
3642 }
3643 }
3644 }
3645 }
3646
Eric Laurent99401132014-05-07 19:48:15 -07003647 // temporary mute output if device selection changes to avoid volume bursts due to
3648 // different per device volumes
3649 if (outputDesc->isActive() && (device != prevDevice)) {
3650 if (muteWaitMs < outputDesc->latency() * 2) {
3651 muteWaitMs = outputDesc->latency() * 2;
3652 }
3653 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3654 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003655 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003656 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003657 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003658 muteWaitMs *2, device);
3659 }
3660 }
3661 }
3662
Eric Laurente552edb2014-03-10 17:42:56 -07003663 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3664 if (muteWaitMs > delayMs) {
3665 muteWaitMs -= delayMs;
3666 usleep(muteWaitMs * 1000);
3667 return muteWaitMs;
3668 }
3669 return 0;
3670}
3671
Eric Laurente0720872014-03-11 09:30:41 -07003672uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003673 audio_devices_t device,
3674 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003675 int delayMs,
3676 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003677{
3678 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003679 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003680 AudioParameter param;
3681 uint32_t muteWaitMs;
3682
3683 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003684 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3685 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003686 return muteWaitMs;
3687 }
3688 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3689 // output profile
3690 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003691 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003692 return 0;
3693 }
3694
3695 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003696 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003697
3698 audio_devices_t prevDevice = outputDesc->mDevice;
3699
3700 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3701
3702 if (device != AUDIO_DEVICE_NONE) {
3703 outputDesc->mDevice = device;
3704 }
3705 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3706
3707 // Do not change the routing if:
3708 // - the requested device is AUDIO_DEVICE_NONE
3709 // - the requested device is the same as current device and force is not specified.
3710 // Doing this check here allows the caller to call setOutputDevice() without conditions
3711 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3712 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3713 return muteWaitMs;
3714 }
3715
3716 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003717
Eric Laurente552edb2014-03-10 17:42:56 -07003718 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003719 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003720 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003721 } else {
3722 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3723 if (!deviceList.isEmpty()) {
3724 struct audio_patch patch;
3725 outputDesc->toAudioPortConfig(&patch.sources[0]);
3726 patch.num_sources = 1;
3727 patch.num_sinks = 0;
3728 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3729 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003730 patch.num_sinks++;
3731 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003732 ssize_t index;
3733 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3734 index = mAudioPatches.indexOfKey(*patchHandle);
3735 } else {
3736 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3737 }
3738 sp< AudioPatch> patchDesc;
3739 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3740 if (index >= 0) {
3741 patchDesc = mAudioPatches.valueAt(index);
3742 afPatchHandle = patchDesc->mAfPatchHandle;
3743 }
3744
Eric Laurent1c333e22014-05-20 10:48:17 -07003745 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003746 &afPatchHandle,
3747 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003748 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3749 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003750 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003751 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003752 if (index < 0) {
3753 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3754 &patch, mUidCached);
3755 addAudioPatch(patchDesc->mHandle, patchDesc);
3756 } else {
3757 patchDesc->mPatch = patch;
3758 }
3759 patchDesc->mAfPatchHandle = afPatchHandle;
3760 patchDesc->mUid = mUidCached;
3761 if (patchHandle) {
3762 *patchHandle = patchDesc->mHandle;
3763 }
3764 outputDesc->mPatchHandle = patchDesc->mHandle;
3765 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003766 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003767 }
3768 }
3769 }
Eric Laurente552edb2014-03-10 17:42:56 -07003770
3771 // update stream volumes according to new device
3772 applyStreamVolumes(output, device, delayMs);
3773
3774 return muteWaitMs;
3775}
3776
Eric Laurent1c333e22014-05-20 10:48:17 -07003777status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003778 int delayMs,
3779 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003780{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003781 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003782 ssize_t index;
3783 if (patchHandle) {
3784 index = mAudioPatches.indexOfKey(*patchHandle);
3785 } else {
3786 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3787 }
3788 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003789 return INVALID_OPERATION;
3790 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003791 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3792 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003793 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3794 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003795 removeAudioPatch(patchDesc->mHandle);
3796 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003797 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003798 return status;
3799}
3800
3801status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3802 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003803 bool force,
3804 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003805{
3806 status_t status = NO_ERROR;
3807
Eric Laurent1f2f2232014-06-02 12:01:23 -07003808 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003809 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3810 inputDesc->mDevice = device;
3811
3812 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3813 if (!deviceList.isEmpty()) {
3814 struct audio_patch patch;
3815 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3816 patch.num_sinks = 1;
3817 //only one input device for now
3818 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003819 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003820 ssize_t index;
3821 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3822 index = mAudioPatches.indexOfKey(*patchHandle);
3823 } else {
3824 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3825 }
3826 sp< AudioPatch> patchDesc;
3827 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3828 if (index >= 0) {
3829 patchDesc = mAudioPatches.valueAt(index);
3830 afPatchHandle = patchDesc->mAfPatchHandle;
3831 }
3832
Eric Laurent1c333e22014-05-20 10:48:17 -07003833 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003834 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003835 0);
3836 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003837 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003838 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003839 if (index < 0) {
3840 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3841 &patch, mUidCached);
3842 addAudioPatch(patchDesc->mHandle, patchDesc);
3843 } else {
3844 patchDesc->mPatch = patch;
3845 }
3846 patchDesc->mAfPatchHandle = afPatchHandle;
3847 patchDesc->mUid = mUidCached;
3848 if (patchHandle) {
3849 *patchHandle = patchDesc->mHandle;
3850 }
3851 inputDesc->mPatchHandle = patchDesc->mHandle;
3852 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003853 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003854 }
3855 }
3856 }
3857 return status;
3858}
3859
Eric Laurent6a94d692014-05-20 11:18:06 -07003860status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3861 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003862{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003863 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003864 ssize_t index;
3865 if (patchHandle) {
3866 index = mAudioPatches.indexOfKey(*patchHandle);
3867 } else {
3868 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3869 }
3870 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003871 return INVALID_OPERATION;
3872 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003873 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3874 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003875 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3876 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003877 removeAudioPatch(patchDesc->mHandle);
3878 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003879 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003880 return status;
3881}
3882
3883sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003884 uint32_t samplingRate,
3885 audio_format_t format,
3886 audio_channel_mask_t channelMask)
3887{
3888 // Choose an input profile based on the requested capture parameters: select the first available
3889 // profile supporting all requested parameters.
3890
3891 for (size_t i = 0; i < mHwModules.size(); i++)
3892 {
3893 if (mHwModules[i]->mHandle == 0) {
3894 continue;
3895 }
3896 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3897 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003898 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003899 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003900 if (profile->isCompatibleProfile(device, samplingRate, format,
3901 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3902 return profile;
3903 }
3904 }
3905 }
3906 return NULL;
3907}
3908
Eric Laurente0720872014-03-11 09:30:41 -07003909audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003910{
3911 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003912 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3913 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003914 switch (inputSource) {
3915 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003916 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003917 device = AUDIO_DEVICE_IN_VOICE_CALL;
3918 break;
3919 }
3920 // FALL THROUGH
3921
3922 case AUDIO_SOURCE_DEFAULT:
3923 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003924 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3925 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3926 break;
3927 }
3928 // FALL THROUGH
3929
Eric Laurente552edb2014-03-10 17:42:56 -07003930 case AUDIO_SOURCE_VOICE_RECOGNITION:
3931 case AUDIO_SOURCE_HOTWORD:
3932 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003933 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003934 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003935 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003936 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003937 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003938 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3939 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003940 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003941 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3942 }
3943 break;
3944 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003945 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003946 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003947 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003948 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3949 }
3950 break;
3951 case AUDIO_SOURCE_VOICE_DOWNLINK:
3952 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003953 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003954 device = AUDIO_DEVICE_IN_VOICE_CALL;
3955 }
3956 break;
3957 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003958 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003959 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3960 }
3961 break;
3962 default:
3963 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3964 break;
3965 }
3966 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3967 return device;
3968}
3969
Eric Laurente0720872014-03-11 09:30:41 -07003970bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003971{
3972 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3973 device &= ~AUDIO_DEVICE_BIT_IN;
3974 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3975 return true;
3976 }
3977 return false;
3978}
3979
Eric Laurente0720872014-03-11 09:30:41 -07003980audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003981{
3982 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003983 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003984 if ((input_descriptor->mRefCount > 0)
3985 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3986 return mInputs.keyAt(i);
3987 }
3988 }
3989 return 0;
3990}
3991
3992
Eric Laurente0720872014-03-11 09:30:41 -07003993audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003994{
3995 if (device == AUDIO_DEVICE_NONE) {
3996 // this happens when forcing a route update and no track is active on an output.
3997 // In this case the returned category is not important.
3998 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003999 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004000 // Multiple device selection is either:
4001 // - speaker + one other device: give priority to speaker in this case.
4002 // - one A2DP device + another device: happens with duplicated output. In this case
4003 // retain the device on the A2DP output as the other must not correspond to an active
4004 // selection if not the speaker.
4005 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4006 device = AUDIO_DEVICE_OUT_SPEAKER;
4007 } else {
4008 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4009 }
4010 }
4011
Eric Laurent3b73df72014-03-11 09:06:29 -07004012 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004013 "getDeviceForVolume() invalid device combination: %08x",
4014 device);
4015
4016 return device;
4017}
4018
Eric Laurente0720872014-03-11 09:30:41 -07004019AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004020{
4021 switch(getDeviceForVolume(device)) {
4022 case AUDIO_DEVICE_OUT_EARPIECE:
4023 return DEVICE_CATEGORY_EARPIECE;
4024 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4025 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4026 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4027 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4028 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4029 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4030 return DEVICE_CATEGORY_HEADSET;
4031 case AUDIO_DEVICE_OUT_SPEAKER:
4032 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4033 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4034 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4035 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4036 case AUDIO_DEVICE_OUT_USB_DEVICE:
4037 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4038 default:
4039 return DEVICE_CATEGORY_SPEAKER;
4040 }
4041}
4042
Eric Laurente0720872014-03-11 09:30:41 -07004043float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004044 int indexInUi)
4045{
4046 device_category deviceCategory = getDeviceCategory(device);
4047 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4048
4049 // the volume index in the UI is relative to the min and max volume indices for this stream type
4050 int nbSteps = 1 + curve[VOLMAX].mIndex -
4051 curve[VOLMIN].mIndex;
4052 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4053 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4054
4055 // find what part of the curve this index volume belongs to, or if it's out of bounds
4056 int segment = 0;
4057 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4058 return 0.0f;
4059 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4060 segment = 0;
4061 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4062 segment = 1;
4063 } else if (volIdx <= curve[VOLMAX].mIndex) {
4064 segment = 2;
4065 } else { // out of bounds
4066 return 1.0f;
4067 }
4068
4069 // linear interpolation in the attenuation table in dB
4070 float decibels = curve[segment].mDBAttenuation +
4071 ((float)(volIdx - curve[segment].mIndex)) *
4072 ( (curve[segment+1].mDBAttenuation -
4073 curve[segment].mDBAttenuation) /
4074 ((float)(curve[segment+1].mIndex -
4075 curve[segment].mIndex)) );
4076
4077 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4078
4079 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4080 curve[segment].mIndex, volIdx,
4081 curve[segment+1].mIndex,
4082 curve[segment].mDBAttenuation,
4083 decibels,
4084 curve[segment+1].mDBAttenuation,
4085 amplification);
4086
4087 return amplification;
4088}
4089
Eric Laurente0720872014-03-11 09:30:41 -07004090const AudioPolicyManager::VolumeCurvePoint
4091 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004092 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4093};
4094
Eric Laurente0720872014-03-11 09:30:41 -07004095const AudioPolicyManager::VolumeCurvePoint
4096 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004097 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4098};
4099
Eric Laurente0720872014-03-11 09:30:41 -07004100const AudioPolicyManager::VolumeCurvePoint
4101 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004102 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4103};
4104
Eric Laurente0720872014-03-11 09:30:41 -07004105const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004106 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
4107 {1, -56.0f}, {20, -34.0f}, {86, -10.0f}, {100, 0.0f}
4108};
4109
4110const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004111 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004112 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4113};
4114
Eric Laurente0720872014-03-11 09:30:41 -07004115const AudioPolicyManager::VolumeCurvePoint
4116 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004117 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4118};
4119
4120// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4121// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4122// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4123// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4124
Eric Laurente0720872014-03-11 09:30:41 -07004125const AudioPolicyManager::VolumeCurvePoint
4126 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004127 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4128};
4129
Eric Laurente0720872014-03-11 09:30:41 -07004130const AudioPolicyManager::VolumeCurvePoint
4131 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004132 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4133};
4134
Eric Laurente0720872014-03-11 09:30:41 -07004135const AudioPolicyManager::VolumeCurvePoint
4136 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004137 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4138};
4139
Eric Laurente0720872014-03-11 09:30:41 -07004140const AudioPolicyManager::VolumeCurvePoint
4141 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004142 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4143};
4144
Eric Laurente0720872014-03-11 09:30:41 -07004145const AudioPolicyManager::VolumeCurvePoint
4146 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004147 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4148};
4149
Eric Laurente0720872014-03-11 09:30:41 -07004150const AudioPolicyManager::VolumeCurvePoint
4151 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4152 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004153 { // AUDIO_STREAM_VOICE_CALL
4154 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4155 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4156 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4157 },
4158 { // AUDIO_STREAM_SYSTEM
4159 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4160 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4161 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4162 },
4163 { // AUDIO_STREAM_RING
4164 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4165 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4166 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4167 },
4168 { // AUDIO_STREAM_MUSIC
4169 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4170 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4171 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4172 },
4173 { // AUDIO_STREAM_ALARM
4174 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4175 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4176 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4177 },
4178 { // AUDIO_STREAM_NOTIFICATION
4179 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4180 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4181 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4182 },
4183 { // AUDIO_STREAM_BLUETOOTH_SCO
4184 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4185 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4186 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4187 },
4188 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4189 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4190 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4191 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4192 },
4193 { // AUDIO_STREAM_DTMF
4194 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4195 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4196 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4197 },
4198 { // AUDIO_STREAM_TTS
4199 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4200 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4201 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4202 },
4203};
4204
Eric Laurente0720872014-03-11 09:30:41 -07004205void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004206{
4207 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4208 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4209 mStreams[i].mVolumeCurve[j] =
4210 sVolumeProfiles[i][j];
4211 }
4212 }
4213
4214 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4215 if (mSpeakerDrcEnabled) {
4216 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4217 sDefaultSystemVolumeCurveDrc;
4218 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4219 sSpeakerSonificationVolumeCurveDrc;
4220 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4221 sSpeakerSonificationVolumeCurveDrc;
4222 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4223 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004224 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4225 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004226 }
4227}
4228
Eric Laurente0720872014-03-11 09:30:41 -07004229float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004230 int index,
4231 audio_io_handle_t output,
4232 audio_devices_t device)
4233{
4234 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004235 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004236 StreamDescriptor &streamDesc = mStreams[stream];
4237
4238 if (device == AUDIO_DEVICE_NONE) {
4239 device = outputDesc->device();
4240 }
4241
4242 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004243 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004244 index != mStreams[stream].mIndexMin &&
4245 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
Paul McLeanb919dd32014-06-26 13:16:44 -07004246 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004247 return 1.0;
4248 }
4249
4250 volume = volIndexToAmpl(device, streamDesc, index);
4251
4252 // if a headset is connected, apply the following rules to ring tones and notifications
4253 // to avoid sound level bursts in user's ears:
4254 // - always attenuate ring tones and notifications volume by 6dB
4255 // - if music is playing, always limit the volume to current music volume,
4256 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004257 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004258 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4259 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4260 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4261 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4262 ((stream_strategy == STRATEGY_SONIFICATION)
4263 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004264 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004265 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004266 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004267 streamDesc.mCanBeMuted) {
4268 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4269 // when the phone is ringing we must consider that music could have been paused just before
4270 // by the music application and behave as if music was active if the last music track was
4271 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004272 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004273 mLimitRingtoneVolume) {
4274 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004275 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4276 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004277 output,
4278 musicDevice);
4279 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4280 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4281 if (volume > minVol) {
4282 volume = minVol;
4283 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4284 }
4285 }
4286 }
4287
4288 return volume;
4289}
4290
Eric Laurente0720872014-03-11 09:30:41 -07004291status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004292 int index,
4293 audio_io_handle_t output,
4294 audio_devices_t device,
4295 int delayMs,
4296 bool force)
4297{
4298
4299 // do not change actual stream volume if the stream is muted
4300 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4301 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4302 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4303 return NO_ERROR;
4304 }
4305
4306 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004307 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4308 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4309 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4310 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004311 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004312 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004313 return INVALID_OPERATION;
4314 }
4315
4316 float volume = computeVolume(stream, index, output, device);
4317 // We actually change the volume if:
4318 // - the float value returned by computeVolume() changed
4319 // - the force flag is set
4320 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4321 force) {
4322 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4323 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4324 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4325 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004326 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4327 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004328 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004329 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004330 }
4331
Eric Laurent3b73df72014-03-11 09:06:29 -07004332 if (stream == AUDIO_STREAM_VOICE_CALL ||
4333 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004334 float voiceVolume;
4335 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004336 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004337 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4338 } else {
4339 voiceVolume = 1.0;
4340 }
4341
4342 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4343 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4344 mLastVoiceVolume = voiceVolume;
4345 }
4346 }
4347
4348 return NO_ERROR;
4349}
4350
Eric Laurente0720872014-03-11 09:30:41 -07004351void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004352 audio_devices_t device,
4353 int delayMs,
4354 bool force)
4355{
4356 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4357
Eric Laurent3b73df72014-03-11 09:06:29 -07004358 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4359 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004360 mStreams[stream].getVolumeIndex(device),
4361 output,
4362 device,
4363 delayMs,
4364 force);
4365 }
4366}
4367
Eric Laurente0720872014-03-11 09:30:41 -07004368void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004369 bool on,
4370 audio_io_handle_t output,
4371 int delayMs,
4372 audio_devices_t device)
4373{
4374 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004375 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4376 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4377 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004378 }
4379 }
4380}
4381
Eric Laurente0720872014-03-11 09:30:41 -07004382void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004383 bool on,
4384 audio_io_handle_t output,
4385 int delayMs,
4386 audio_devices_t device)
4387{
4388 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004389 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004390 if (device == AUDIO_DEVICE_NONE) {
4391 device = outputDesc->device();
4392 }
4393
4394 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4395 stream, on, output, outputDesc->mMuteCount[stream], device);
4396
4397 if (on) {
4398 if (outputDesc->mMuteCount[stream] == 0) {
4399 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004400 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4401 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004402 checkAndSetVolume(stream, 0, output, device, delayMs);
4403 }
4404 }
4405 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4406 outputDesc->mMuteCount[stream]++;
4407 } else {
4408 if (outputDesc->mMuteCount[stream] == 0) {
4409 ALOGV("setStreamMute() unmuting non muted stream!");
4410 return;
4411 }
4412 if (--outputDesc->mMuteCount[stream] == 0) {
4413 checkAndSetVolume(stream,
4414 streamDesc.getVolumeIndex(device),
4415 output,
4416 device,
4417 delayMs);
4418 }
4419 }
4420}
4421
Eric Laurente0720872014-03-11 09:30:41 -07004422void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004423 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004424{
4425 // if the stream pertains to sonification strategy and we are in call we must
4426 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4427 // in the device used for phone strategy and play the tone if the selected device does not
4428 // interfere with the device used for phone strategy
4429 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4430 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004431 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004432 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4433 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004434 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004435 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4436 stream, starting, outputDesc->mDevice, stateChange);
4437 if (outputDesc->mRefCount[stream]) {
4438 int muteCount = 1;
4439 if (stateChange) {
4440 muteCount = outputDesc->mRefCount[stream];
4441 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004442 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004443 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4444 for (int i = 0; i < muteCount; i++) {
4445 setStreamMute(stream, starting, mPrimaryOutput);
4446 }
4447 } else {
4448 ALOGV("handleIncallSonification() high visibility");
4449 if (outputDesc->device() &
4450 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4451 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4452 for (int i = 0; i < muteCount; i++) {
4453 setStreamMute(stream, starting, mPrimaryOutput);
4454 }
4455 }
4456 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004457 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4458 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004459 } else {
4460 mpClientInterface->stopTone();
4461 }
4462 }
4463 }
4464 }
4465}
4466
Eric Laurente0720872014-03-11 09:30:41 -07004467bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004468{
4469 return isStateInCall(mPhoneState);
4470}
4471
Eric Laurente0720872014-03-11 09:30:41 -07004472bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004473 return ((state == AUDIO_MODE_IN_CALL) ||
4474 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004475}
4476
Eric Laurente0720872014-03-11 09:30:41 -07004477uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004478{
4479 return MAX_EFFECTS_CPU_LOAD;
4480}
4481
Eric Laurente0720872014-03-11 09:30:41 -07004482uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004483{
4484 return MAX_EFFECTS_MEMORY;
4485}
4486
Eric Laurent6a94d692014-05-20 11:18:06 -07004487
Eric Laurente552edb2014-03-10 17:42:56 -07004488// --- AudioOutputDescriptor class implementation
4489
Eric Laurente0720872014-03-11 09:30:41 -07004490AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004491 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004492 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004493 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004494 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4495{
4496 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004497 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004498 mRefCount[i] = 0;
4499 mCurVolume[i] = -1.0;
4500 mMuteCount[i] = 0;
4501 mStopTime[i] = 0;
4502 }
4503 for (int i = 0; i < NUM_STRATEGIES; i++) {
4504 mStrategyMutedByDevice[i] = false;
4505 }
4506 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004507 mAudioPort = profile;
Eric Laurente552edb2014-03-10 17:42:56 -07004508 mSamplingRate = profile->mSamplingRates[0];
4509 mFormat = profile->mFormats[0];
4510 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004511 if (profile->mGains.size() > 0) {
4512 profile->mGains[0]->getDefaultConfig(&mGain);
4513 }
Eric Laurente552edb2014-03-10 17:42:56 -07004514 mFlags = profile->mFlags;
4515 }
4516}
4517
Eric Laurente0720872014-03-11 09:30:41 -07004518audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004519{
4520 if (isDuplicated()) {
4521 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4522 } else {
4523 return mDevice;
4524 }
4525}
4526
Eric Laurente0720872014-03-11 09:30:41 -07004527uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004528{
4529 if (isDuplicated()) {
4530 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4531 } else {
4532 return mLatency;
4533 }
4534}
4535
Eric Laurente0720872014-03-11 09:30:41 -07004536bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004537 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004538{
4539 if (isDuplicated()) {
4540 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4541 } else if (outputDesc->isDuplicated()){
4542 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4543 } else {
4544 return (mProfile->mModule == outputDesc->mProfile->mModule);
4545 }
4546}
4547
Eric Laurente0720872014-03-11 09:30:41 -07004548void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004549 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004550{
4551 // forward usage count change to attached outputs
4552 if (isDuplicated()) {
4553 mOutput1->changeRefCount(stream, delta);
4554 mOutput2->changeRefCount(stream, delta);
4555 }
4556 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004557 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4558 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004559 mRefCount[stream] = 0;
4560 return;
4561 }
4562 mRefCount[stream] += delta;
4563 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4564}
4565
Eric Laurente0720872014-03-11 09:30:41 -07004566audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004567{
4568 if (isDuplicated()) {
4569 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4570 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004571 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004572 }
4573}
4574
Eric Laurente0720872014-03-11 09:30:41 -07004575bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004576{
4577 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4578}
4579
Eric Laurente0720872014-03-11 09:30:41 -07004580bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004581 uint32_t inPastMs,
4582 nsecs_t sysTime) const
4583{
4584 if ((sysTime == 0) && (inPastMs != 0)) {
4585 sysTime = systemTime();
4586 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004587 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4588 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004589 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004590 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004591 return true;
4592 }
4593 }
4594 return false;
4595}
4596
Eric Laurente0720872014-03-11 09:30:41 -07004597bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004598 uint32_t inPastMs,
4599 nsecs_t sysTime) const
4600{
4601 if (mRefCount[stream] != 0) {
4602 return true;
4603 }
4604 if (inPastMs == 0) {
4605 return false;
4606 }
4607 if (sysTime == 0) {
4608 sysTime = systemTime();
4609 }
4610 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4611 return true;
4612 }
4613 return false;
4614}
4615
Eric Laurent1c333e22014-05-20 10:48:17 -07004616void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004617 struct audio_port_config *dstConfig,
4618 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004619{
Eric Laurent84c70242014-06-23 08:46:27 -07004620 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4621
Eric Laurent1f2f2232014-06-02 12:01:23 -07004622 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4623 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4624 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004625 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004626 }
4627 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4628
Eric Laurent6a94d692014-05-20 11:18:06 -07004629 dstConfig->id = mId;
4630 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4631 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004632 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4633 dstConfig->ext.mix.handle = mIoHandle;
4634 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004635}
4636
4637void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4638 struct audio_port *port) const
4639{
Eric Laurent84c70242014-06-23 08:46:27 -07004640 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004641 mProfile->toAudioPort(port);
4642 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004643 toAudioPortConfig(&port->active_config);
4644 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004645 port->ext.mix.handle = mIoHandle;
4646 port->ext.mix.latency_class =
4647 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4648}
Eric Laurente552edb2014-03-10 17:42:56 -07004649
Eric Laurente0720872014-03-11 09:30:41 -07004650status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004651{
4652 const size_t SIZE = 256;
4653 char buffer[SIZE];
4654 String8 result;
4655
4656 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4657 result.append(buffer);
4658 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4659 result.append(buffer);
4660 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4661 result.append(buffer);
4662 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4663 result.append(buffer);
4664 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4665 result.append(buffer);
4666 snprintf(buffer, SIZE, " Devices %08x\n", device());
4667 result.append(buffer);
4668 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4669 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004670 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4671 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4672 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004673 result.append(buffer);
4674 }
4675 write(fd, result.string(), result.size());
4676
4677 return NO_ERROR;
4678}
4679
4680// --- AudioInputDescriptor class implementation
4681
Eric Laurent1c333e22014-05-20 10:48:17 -07004682AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004683 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004684 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004685 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004686{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004687 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004688 mAudioPort = profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004689 mSamplingRate = profile->mSamplingRates[0];
4690 mFormat = profile->mFormats[0];
4691 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004692 if (profile->mGains.size() > 0) {
4693 profile->mGains[0]->getDefaultConfig(&mGain);
4694 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004695 } else {
4696 mSamplingRate = 0;
4697 mFormat = AUDIO_FORMAT_DEFAULT;
4698 mChannelMask = 0;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004699 }
Eric Laurente552edb2014-03-10 17:42:56 -07004700}
4701
Eric Laurent1c333e22014-05-20 10:48:17 -07004702void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004703 struct audio_port_config *dstConfig,
4704 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004705{
Eric Laurent84c70242014-06-23 08:46:27 -07004706 ALOG_ASSERT(mProfile != 0,
4707 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004708 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4709 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4710 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004711 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004712 }
4713
4714 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4715
Eric Laurent6a94d692014-05-20 11:18:06 -07004716 dstConfig->id = mId;
4717 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4718 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004719 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4720 dstConfig->ext.mix.handle = mIoHandle;
4721 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004722}
4723
4724void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4725 struct audio_port *port) const
4726{
Eric Laurent84c70242014-06-23 08:46:27 -07004727 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4728
Eric Laurent1c333e22014-05-20 10:48:17 -07004729 mProfile->toAudioPort(port);
4730 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004731 toAudioPortConfig(&port->active_config);
4732 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004733 port->ext.mix.handle = mIoHandle;
4734 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4735}
4736
Eric Laurente0720872014-03-11 09:30:41 -07004737status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004738{
4739 const size_t SIZE = 256;
4740 char buffer[SIZE];
4741 String8 result;
4742
4743 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4744 result.append(buffer);
4745 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4746 result.append(buffer);
4747 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4748 result.append(buffer);
4749 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4750 result.append(buffer);
4751 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4752 result.append(buffer);
4753 write(fd, result.string(), result.size());
4754
4755 return NO_ERROR;
4756}
4757
4758// --- StreamDescriptor class implementation
4759
Eric Laurente0720872014-03-11 09:30:41 -07004760AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004761 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4762{
4763 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4764}
4765
Eric Laurente0720872014-03-11 09:30:41 -07004766int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004767{
Eric Laurente0720872014-03-11 09:30:41 -07004768 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004769 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4770 if (mIndexCur.indexOfKey(device) < 0) {
4771 device = AUDIO_DEVICE_OUT_DEFAULT;
4772 }
4773 return mIndexCur.valueFor(device);
4774}
4775
Eric Laurente0720872014-03-11 09:30:41 -07004776void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004777{
4778 const size_t SIZE = 256;
4779 char buffer[SIZE];
4780 String8 result;
4781
4782 snprintf(buffer, SIZE, "%s %02d %02d ",
4783 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4784 result.append(buffer);
4785 for (size_t i = 0; i < mIndexCur.size(); i++) {
4786 snprintf(buffer, SIZE, "%04x : %02d, ",
4787 mIndexCur.keyAt(i),
4788 mIndexCur.valueAt(i));
4789 result.append(buffer);
4790 }
4791 result.append("\n");
4792
4793 write(fd, result.string(), result.size());
4794}
4795
4796// --- EffectDescriptor class implementation
4797
Eric Laurente0720872014-03-11 09:30:41 -07004798status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004799{
4800 const size_t SIZE = 256;
4801 char buffer[SIZE];
4802 String8 result;
4803
4804 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4805 result.append(buffer);
4806 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4807 result.append(buffer);
4808 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4809 result.append(buffer);
4810 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4811 result.append(buffer);
4812 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4813 result.append(buffer);
4814 write(fd, result.string(), result.size());
4815
4816 return NO_ERROR;
4817}
4818
Eric Laurent1c333e22014-05-20 10:48:17 -07004819// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004820
Eric Laurente0720872014-03-11 09:30:41 -07004821AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004822 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4823 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004824{
4825}
4826
Eric Laurente0720872014-03-11 09:30:41 -07004827AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004828{
4829 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004830 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004831 }
4832 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004833 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004834 }
4835 free((void *)mName);
4836}
4837
Eric Laurent1afeecb2014-05-14 08:52:28 -07004838status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4839{
4840 cnode *node = root->first_child;
4841
4842 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4843
4844 while (node) {
4845 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4846 profile->loadSamplingRates((char *)node->value);
4847 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4848 profile->loadFormats((char *)node->value);
4849 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4850 profile->loadInChannels((char *)node->value);
4851 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4852 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4853 mDeclaredDevices);
4854 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4855 profile->loadGains(node);
4856 }
4857 node = node->next;
4858 }
4859 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4860 "loadInput() invalid supported devices");
4861 ALOGW_IF(profile->mChannelMasks.size() == 0,
4862 "loadInput() invalid supported channel masks");
4863 ALOGW_IF(profile->mSamplingRates.size() == 0,
4864 "loadInput() invalid supported sampling rates");
4865 ALOGW_IF(profile->mFormats.size() == 0,
4866 "loadInput() invalid supported formats");
4867 if (!profile->mSupportedDevices.isEmpty() &&
4868 (profile->mChannelMasks.size() != 0) &&
4869 (profile->mSamplingRates.size() != 0) &&
4870 (profile->mFormats.size() != 0)) {
4871
4872 ALOGV("loadInput() adding input Supported Devices %04x",
4873 profile->mSupportedDevices.types());
4874
4875 mInputProfiles.add(profile);
4876 return NO_ERROR;
4877 } else {
4878 return BAD_VALUE;
4879 }
4880}
4881
4882status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4883{
4884 cnode *node = root->first_child;
4885
4886 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4887
4888 while (node) {
4889 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4890 profile->loadSamplingRates((char *)node->value);
4891 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4892 profile->loadFormats((char *)node->value);
4893 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4894 profile->loadOutChannels((char *)node->value);
4895 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4896 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4897 mDeclaredDevices);
4898 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4899 profile->mFlags = parseFlagNames((char *)node->value);
4900 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4901 profile->loadGains(node);
4902 }
4903 node = node->next;
4904 }
4905 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4906 "loadOutput() invalid supported devices");
4907 ALOGW_IF(profile->mChannelMasks.size() == 0,
4908 "loadOutput() invalid supported channel masks");
4909 ALOGW_IF(profile->mSamplingRates.size() == 0,
4910 "loadOutput() invalid supported sampling rates");
4911 ALOGW_IF(profile->mFormats.size() == 0,
4912 "loadOutput() invalid supported formats");
4913 if (!profile->mSupportedDevices.isEmpty() &&
4914 (profile->mChannelMasks.size() != 0) &&
4915 (profile->mSamplingRates.size() != 0) &&
4916 (profile->mFormats.size() != 0)) {
4917
4918 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4919 profile->mSupportedDevices.types(), profile->mFlags);
4920
4921 mOutputProfiles.add(profile);
4922 return NO_ERROR;
4923 } else {
4924 return BAD_VALUE;
4925 }
4926}
4927
4928status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4929{
4930 cnode *node = root->first_child;
4931
4932 audio_devices_t type = AUDIO_DEVICE_NONE;
4933 while (node) {
4934 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4935 type = parseDeviceNames((char *)node->value);
4936 break;
4937 }
4938 node = node->next;
4939 }
4940 if (type == AUDIO_DEVICE_NONE ||
4941 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4942 ALOGW("loadDevice() bad type %08x", type);
4943 return BAD_VALUE;
4944 }
4945 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4946 deviceDesc->mModule = this;
4947
4948 node = root->first_child;
4949 while (node) {
4950 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4951 deviceDesc->mAddress = String8((char *)node->value);
4952 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4953 if (audio_is_input_device(type)) {
4954 deviceDesc->loadInChannels((char *)node->value);
4955 } else {
4956 deviceDesc->loadOutChannels((char *)node->value);
4957 }
4958 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4959 deviceDesc->loadGains(node);
4960 }
4961 node = node->next;
4962 }
4963
4964 ALOGV("loadDevice() adding device name %s type %08x address %s",
4965 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4966
4967 mDeclaredDevices.add(deviceDesc);
4968
4969 return NO_ERROR;
4970}
4971
Eric Laurente0720872014-03-11 09:30:41 -07004972void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004973{
4974 const size_t SIZE = 256;
4975 char buffer[SIZE];
4976 String8 result;
4977
4978 snprintf(buffer, SIZE, " - name: %s\n", mName);
4979 result.append(buffer);
4980 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4981 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07004982 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
4983 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07004984 write(fd, result.string(), result.size());
4985 if (mOutputProfiles.size()) {
4986 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4987 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004988 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004989 write(fd, buffer, strlen(buffer));
4990 mOutputProfiles[i]->dump(fd);
4991 }
4992 }
4993 if (mInputProfiles.size()) {
4994 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4995 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004996 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004997 write(fd, buffer, strlen(buffer));
4998 mInputProfiles[i]->dump(fd);
4999 }
5000 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005001 if (mDeclaredDevices.size()) {
5002 write(fd, " - devices:\n", strlen(" - devices:\n"));
5003 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5004 mDeclaredDevices[i]->dump(fd, 4, i);
5005 }
5006 }
Eric Laurente552edb2014-03-10 17:42:56 -07005007}
5008
Eric Laurent1c333e22014-05-20 10:48:17 -07005009// --- AudioPort class implementation
5010
Eric Laurenta121f902014-06-03 13:32:54 -07005011
5012AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5013 audio_port_role_t role, const sp<HwModule>& module) :
5014 mName(name), mType(type), mRole(role), mModule(module)
5015{
5016 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5017 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5018}
5019
Eric Laurent1c333e22014-05-20 10:48:17 -07005020void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5021{
5022 port->role = mRole;
5023 port->type = mType;
5024 unsigned int i;
5025 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5026 port->sample_rates[i] = mSamplingRates[i];
5027 }
5028 port->num_sample_rates = i;
5029 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5030 port->channel_masks[i] = mChannelMasks[i];
5031 }
5032 port->num_channel_masks = i;
5033 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5034 port->formats[i] = mFormats[i];
5035 }
5036 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005037
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005038 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005039
5040 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5041 port->gains[i] = mGains[i]->mGain;
5042 }
5043 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005044}
5045
5046
5047void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5048{
5049 char *str = strtok(name, "|");
5050
5051 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5052 // rates should be read from the output stream after it is opened for the first time
5053 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5054 mSamplingRates.add(0);
5055 return;
5056 }
5057
5058 while (str != NULL) {
5059 uint32_t rate = atoi(str);
5060 if (rate != 0) {
5061 ALOGV("loadSamplingRates() adding rate %d", rate);
5062 mSamplingRates.add(rate);
5063 }
5064 str = strtok(NULL, "|");
5065 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005066}
5067
5068void AudioPolicyManager::AudioPort::loadFormats(char *name)
5069{
5070 char *str = strtok(name, "|");
5071
5072 // by convention, "0' in the first entry in mFormats indicates the supported formats
5073 // should be read from the output stream after it is opened for the first time
5074 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5075 mFormats.add(AUDIO_FORMAT_DEFAULT);
5076 return;
5077 }
5078
5079 while (str != NULL) {
5080 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5081 ARRAY_SIZE(sFormatNameToEnumTable),
5082 str);
5083 if (format != AUDIO_FORMAT_DEFAULT) {
5084 mFormats.add(format);
5085 }
5086 str = strtok(NULL, "|");
5087 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005088}
5089
5090void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5091{
5092 const char *str = strtok(name, "|");
5093
5094 ALOGV("loadInChannels() %s", name);
5095
5096 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5097 mChannelMasks.add(0);
5098 return;
5099 }
5100
5101 while (str != NULL) {
5102 audio_channel_mask_t channelMask =
5103 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5104 ARRAY_SIZE(sInChannelsNameToEnumTable),
5105 str);
5106 if (channelMask != 0) {
5107 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5108 mChannelMasks.add(channelMask);
5109 }
5110 str = strtok(NULL, "|");
5111 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005112}
5113
5114void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5115{
5116 const char *str = strtok(name, "|");
5117
5118 ALOGV("loadOutChannels() %s", name);
5119
5120 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5121 // masks should be read from the output stream after it is opened for the first time
5122 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5123 mChannelMasks.add(0);
5124 return;
5125 }
5126
5127 while (str != NULL) {
5128 audio_channel_mask_t channelMask =
5129 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5130 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5131 str);
5132 if (channelMask != 0) {
5133 mChannelMasks.add(channelMask);
5134 }
5135 str = strtok(NULL, "|");
5136 }
5137 return;
5138}
5139
Eric Laurent1afeecb2014-05-14 08:52:28 -07005140audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5141{
5142 const char *str = strtok(name, "|");
5143
5144 ALOGV("loadGainMode() %s", name);
5145 audio_gain_mode_t mode = 0;
5146 while (str != NULL) {
5147 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5148 ARRAY_SIZE(sGainModeNameToEnumTable),
5149 str);
5150 str = strtok(NULL, "|");
5151 }
5152 return mode;
5153}
5154
Eric Laurenta121f902014-06-03 13:32:54 -07005155void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005156{
5157 cnode *node = root->first_child;
5158
Eric Laurenta121f902014-06-03 13:32:54 -07005159 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005160
5161 while (node) {
5162 if (strcmp(node->name, GAIN_MODE) == 0) {
5163 gain->mGain.mode = loadGainMode((char *)node->value);
5164 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005165 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005166 gain->mGain.channel_mask =
5167 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5168 ARRAY_SIZE(sInChannelsNameToEnumTable),
5169 (char *)node->value);
5170 } else {
5171 gain->mGain.channel_mask =
5172 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5173 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5174 (char *)node->value);
5175 }
5176 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5177 gain->mGain.min_value = atoi((char *)node->value);
5178 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5179 gain->mGain.max_value = atoi((char *)node->value);
5180 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5181 gain->mGain.default_value = atoi((char *)node->value);
5182 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5183 gain->mGain.step_value = atoi((char *)node->value);
5184 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5185 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5186 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5187 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5188 }
5189 node = node->next;
5190 }
5191
5192 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5193 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5194
5195 if (gain->mGain.mode == 0) {
5196 return;
5197 }
5198 mGains.add(gain);
5199}
5200
5201void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5202{
5203 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005204 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005205 while (node) {
5206 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005207 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005208 node = node->next;
5209 }
5210}
5211
Eric Laurenta121f902014-06-03 13:32:54 -07005212status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const
5213{
5214 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5215 if (mSamplingRates[i] == samplingRate) {
5216 return NO_ERROR;
5217 }
5218 }
5219 return BAD_VALUE;
5220}
5221
5222status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const
5223{
5224 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5225 if (mChannelMasks[i] == channelMask) {
5226 return NO_ERROR;
5227 }
5228 }
5229 return BAD_VALUE;
5230}
5231
5232status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5233{
5234 for (size_t i = 0; i < mFormats.size(); i ++) {
5235 if (mFormats[i] == format) {
5236 return NO_ERROR;
5237 }
5238 }
5239 return BAD_VALUE;
5240}
5241
5242status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5243 int index) const
5244{
5245 if (index < 0 || (size_t)index >= mGains.size()) {
5246 return BAD_VALUE;
5247 }
5248 return mGains[index]->checkConfig(gainConfig);
5249}
5250
Eric Laurent1afeecb2014-05-14 08:52:28 -07005251void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5252{
5253 const size_t SIZE = 256;
5254 char buffer[SIZE];
5255 String8 result;
5256
5257 if (mName.size() != 0) {
5258 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5259 result.append(buffer);
5260 }
5261
5262 if (mSamplingRates.size() != 0) {
5263 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5264 result.append(buffer);
5265 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5266 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5267 result.append(buffer);
5268 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5269 }
5270 result.append("\n");
5271 }
5272
5273 if (mChannelMasks.size() != 0) {
5274 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5275 result.append(buffer);
5276 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5277 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5278 result.append(buffer);
5279 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5280 }
5281 result.append("\n");
5282 }
5283
5284 if (mFormats.size() != 0) {
5285 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5286 result.append(buffer);
5287 for (size_t i = 0; i < mFormats.size(); i++) {
5288 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5289 ARRAY_SIZE(sFormatNameToEnumTable),
5290 mFormats[i]));
5291 result.append(buffer);
5292 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5293 }
5294 result.append("\n");
5295 }
5296 write(fd, result.string(), result.size());
5297 if (mGains.size() != 0) {
5298 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5299 write(fd, buffer, strlen(buffer) + 1);
5300 result.append(buffer);
5301 for (size_t i = 0; i < mGains.size(); i++) {
5302 mGains[i]->dump(fd, spaces + 2, i);
5303 }
5304 }
5305}
5306
5307// --- AudioGain class implementation
5308
Eric Laurenta121f902014-06-03 13:32:54 -07005309AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005310{
Eric Laurenta121f902014-06-03 13:32:54 -07005311 mIndex = index;
5312 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005313 memset(&mGain, 0, sizeof(struct audio_gain));
5314}
5315
Eric Laurenta121f902014-06-03 13:32:54 -07005316void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5317{
5318 config->index = mIndex;
5319 config->mode = mGain.mode;
5320 config->channel_mask = mGain.channel_mask;
5321 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5322 config->values[0] = mGain.default_value;
5323 } else {
5324 uint32_t numValues;
5325 if (mUseInChannelMask) {
5326 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5327 } else {
5328 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5329 }
5330 for (size_t i = 0; i < numValues; i++) {
5331 config->values[i] = mGain.default_value;
5332 }
5333 }
5334 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5335 config->ramp_duration_ms = mGain.min_ramp_ms;
5336 }
5337}
5338
5339status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5340{
5341 if ((config->mode & ~mGain.mode) != 0) {
5342 return BAD_VALUE;
5343 }
5344 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5345 if ((config->values[0] < mGain.min_value) ||
5346 (config->values[0] > mGain.max_value)) {
5347 return BAD_VALUE;
5348 }
5349 } else {
5350 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5351 return BAD_VALUE;
5352 }
5353 uint32_t numValues;
5354 if (mUseInChannelMask) {
5355 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5356 } else {
5357 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5358 }
5359 for (size_t i = 0; i < numValues; i++) {
5360 if ((config->values[i] < mGain.min_value) ||
5361 (config->values[i] > mGain.max_value)) {
5362 return BAD_VALUE;
5363 }
5364 }
5365 }
5366 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5367 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5368 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5369 return BAD_VALUE;
5370 }
5371 }
5372 return NO_ERROR;
5373}
5374
Eric Laurent1afeecb2014-05-14 08:52:28 -07005375void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5376{
5377 const size_t SIZE = 256;
5378 char buffer[SIZE];
5379 String8 result;
5380
5381 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5382 result.append(buffer);
5383 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5384 result.append(buffer);
5385 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5386 result.append(buffer);
5387 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5388 result.append(buffer);
5389 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5390 result.append(buffer);
5391 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5392 result.append(buffer);
5393 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5394 result.append(buffer);
5395 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5396 result.append(buffer);
5397 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5398 result.append(buffer);
5399
5400 write(fd, result.string(), result.size());
5401}
5402
Eric Laurent1f2f2232014-06-02 12:01:23 -07005403// --- AudioPortConfig class implementation
5404
5405AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5406{
5407 mSamplingRate = 0;
5408 mChannelMask = AUDIO_CHANNEL_NONE;
5409 mFormat = AUDIO_FORMAT_INVALID;
5410 mGain.index = -1;
5411}
5412
Eric Laurenta121f902014-06-03 13:32:54 -07005413status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5414 const struct audio_port_config *config,
5415 struct audio_port_config *backupConfig)
5416{
5417 struct audio_port_config localBackupConfig;
5418 status_t status = NO_ERROR;
5419
5420 localBackupConfig.config_mask = config->config_mask;
5421 toAudioPortConfig(&localBackupConfig);
5422
5423 if (mAudioPort == 0) {
5424 status = NO_INIT;
5425 goto exit;
5426 }
5427 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5428 status = mAudioPort->checkSamplingRate(config->sample_rate);
5429 if (status != NO_ERROR) {
5430 goto exit;
5431 }
5432 mSamplingRate = config->sample_rate;
5433 }
5434 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5435 status = mAudioPort->checkChannelMask(config->channel_mask);
5436 if (status != NO_ERROR) {
5437 goto exit;
5438 }
5439 mChannelMask = config->channel_mask;
5440 }
5441 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5442 status = mAudioPort->checkFormat(config->format);
5443 if (status != NO_ERROR) {
5444 goto exit;
5445 }
5446 mFormat = config->format;
5447 }
5448 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5449 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5450 if (status != NO_ERROR) {
5451 goto exit;
5452 }
5453 mGain = config->gain;
5454 }
5455
5456exit:
5457 if (status != NO_ERROR) {
5458 applyAudioPortConfig(&localBackupConfig);
5459 }
5460 if (backupConfig != NULL) {
5461 *backupConfig = localBackupConfig;
5462 }
5463 return status;
5464}
5465
Eric Laurent1f2f2232014-06-02 12:01:23 -07005466void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5467 struct audio_port_config *dstConfig,
5468 const struct audio_port_config *srcConfig) const
5469{
5470 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5471 dstConfig->sample_rate = mSamplingRate;
5472 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5473 dstConfig->sample_rate = srcConfig->sample_rate;
5474 }
5475 } else {
5476 dstConfig->sample_rate = 0;
5477 }
5478 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5479 dstConfig->channel_mask = mChannelMask;
5480 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5481 dstConfig->channel_mask = srcConfig->channel_mask;
5482 }
5483 } else {
5484 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5485 }
5486 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5487 dstConfig->format = mFormat;
5488 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5489 dstConfig->format = srcConfig->format;
5490 }
5491 } else {
5492 dstConfig->format = AUDIO_FORMAT_INVALID;
5493 }
5494 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5495 dstConfig->gain = mGain;
5496 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5497 dstConfig->gain = srcConfig->gain;
5498 }
5499 } else {
5500 dstConfig->gain.index = -1;
5501 }
5502 if (dstConfig->gain.index != -1) {
5503 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5504 } else {
5505 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5506 }
5507}
5508
Eric Laurent1c333e22014-05-20 10:48:17 -07005509// --- IOProfile class implementation
5510
Eric Laurent1afeecb2014-05-14 08:52:28 -07005511AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005512 const sp<HwModule>& module)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005513 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005514{
5515}
5516
Eric Laurente0720872014-03-11 09:30:41 -07005517AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005518{
5519}
5520
5521// checks if the IO profile is compatible with specified parameters.
5522// Sampling rate, format and channel mask must be specified in order to
5523// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005524bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005525 uint32_t samplingRate,
5526 audio_format_t format,
5527 audio_channel_mask_t channelMask,
5528 audio_output_flags_t flags) const
5529{
5530 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5531 return false;
5532 }
5533
Eric Laurent3a4311c2014-03-17 12:00:47 -07005534 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005535 return false;
5536 }
5537 if ((mFlags & flags) != flags) {
5538 return false;
5539 }
Eric Laurenta121f902014-06-03 13:32:54 -07005540 if (checkSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005541 return false;
5542 }
Eric Laurenta121f902014-06-03 13:32:54 -07005543 if (checkChannelMask(channelMask) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005544 return false;
5545 }
Eric Laurenta121f902014-06-03 13:32:54 -07005546 if (checkFormat(format) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005547 return false;
5548 }
5549 return true;
5550}
5551
Eric Laurente0720872014-03-11 09:30:41 -07005552void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005553{
5554 const size_t SIZE = 256;
5555 char buffer[SIZE];
5556 String8 result;
5557
Eric Laurent1afeecb2014-05-14 08:52:28 -07005558 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005559
Eric Laurente552edb2014-03-10 17:42:56 -07005560 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5561 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005562 snprintf(buffer, SIZE, " - devices:\n");
5563 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005564 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005565 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5566 mSupportedDevices[i]->dump(fd, 6, i);
5567 }
Eric Laurente552edb2014-03-10 17:42:56 -07005568}
5569
Eric Laurentd4692962014-05-05 18:13:44 -07005570void AudioPolicyManager::IOProfile::log()
5571{
5572 const size_t SIZE = 256;
5573 char buffer[SIZE];
5574 String8 result;
5575
5576 ALOGV(" - sampling rates: ");
5577 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5578 ALOGV(" %d", mSamplingRates[i]);
5579 }
5580
5581 ALOGV(" - channel masks: ");
5582 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5583 ALOGV(" 0x%04x", mChannelMasks[i]);
5584 }
5585
5586 ALOGV(" - formats: ");
5587 for (size_t i = 0; i < mFormats.size(); i++) {
5588 ALOGV(" 0x%08x", mFormats[i]);
5589 }
5590
5591 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5592 ALOGV(" - flags: 0x%04x\n", mFlags);
5593}
5594
5595
Eric Laurent3a4311c2014-03-17 12:00:47 -07005596// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005597
Eric Laurent1f2f2232014-06-02 12:01:23 -07005598
5599AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5600 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5601 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5602 AUDIO_PORT_ROLE_SOURCE,
5603 NULL),
5604 mDeviceType(type), mAddress(""),
5605 mChannelMask(AUDIO_CHANNEL_NONE), mId(0)
5606{
5607 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005608 if (mGains.size() > 0) {
5609 mGains[0]->getDefaultConfig(&mGain);
5610 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005611}
5612
Eric Laurent3a4311c2014-03-17 12:00:47 -07005613bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005614{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005615 // Devices are considered equal if they:
5616 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5617 // - have the same address or one device does not specify the address
5618 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005619 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005620 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005621 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005622 mChannelMask == other->mChannelMask);
5623}
5624
5625void AudioPolicyManager::DeviceVector::refreshTypes()
5626{
Eric Laurent1c333e22014-05-20 10:48:17 -07005627 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005628 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005629 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005630 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005631 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005632}
5633
5634ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5635{
5636 for(size_t i = 0; i < size(); i++) {
5637 if (item->equals(itemAt(i))) {
5638 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005639 }
5640 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005641 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005642}
5643
Eric Laurent3a4311c2014-03-17 12:00:47 -07005644ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005645{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005646 ssize_t ret = indexOf(item);
5647
5648 if (ret < 0) {
5649 ret = SortedVector::add(item);
5650 if (ret >= 0) {
5651 refreshTypes();
5652 }
5653 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005654 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005655 ret = -1;
5656 }
5657 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005658}
5659
Eric Laurent3a4311c2014-03-17 12:00:47 -07005660ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5661{
5662 size_t i;
5663 ssize_t ret = indexOf(item);
5664
5665 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005666 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005667 } else {
5668 ret = SortedVector::removeAt(ret);
5669 if (ret >= 0) {
5670 refreshTypes();
5671 }
5672 }
5673 return ret;
5674}
5675
5676void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5677{
5678 DeviceVector deviceList;
5679
5680 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5681 types &= ~role_bit;
5682
5683 while (types) {
5684 uint32_t i = 31 - __builtin_clz(types);
5685 uint32_t type = 1 << i;
5686 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005687 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005688 }
5689}
5690
Eric Laurent1afeecb2014-05-14 08:52:28 -07005691void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5692 const DeviceVector& declaredDevices)
5693{
5694 char *devName = strtok(name, "|");
5695 while (devName != NULL) {
5696 if (strlen(devName) != 0) {
5697 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5698 ARRAY_SIZE(sDeviceNameToEnumTable),
5699 devName);
5700 if (type != AUDIO_DEVICE_NONE) {
5701 add(new DeviceDescriptor(String8(""), type));
5702 } else {
5703 sp<DeviceDescriptor> deviceDesc =
5704 declaredDevices.getDeviceFromName(String8(devName));
5705 if (deviceDesc != 0) {
5706 add(deviceDesc);
5707 }
5708 }
5709 }
5710 devName = strtok(NULL, "|");
5711 }
5712}
5713
Eric Laurent1c333e22014-05-20 10:48:17 -07005714sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5715 audio_devices_t type, String8 address) const
5716{
5717 sp<DeviceDescriptor> device;
5718 for (size_t i = 0; i < size(); i++) {
5719 if (itemAt(i)->mDeviceType == type) {
5720 device = itemAt(i);
5721 if (itemAt(i)->mAddress = address) {
5722 break;
5723 }
5724 }
5725 }
5726 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5727 type, address.string(), device.get());
5728 return device;
5729}
5730
Eric Laurent6a94d692014-05-20 11:18:06 -07005731sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5732 audio_port_handle_t id) const
5733{
5734 sp<DeviceDescriptor> device;
5735 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005736 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07005737 if (itemAt(i)->mId == id) {
5738 device = itemAt(i);
5739 break;
5740 }
5741 }
5742 return device;
5743}
5744
Eric Laurent1c333e22014-05-20 10:48:17 -07005745AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5746 audio_devices_t type) const
5747{
5748 DeviceVector devices;
5749 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5750 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5751 devices.add(itemAt(i));
5752 type &= ~itemAt(i)->mDeviceType;
5753 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5754 itemAt(i)->mDeviceType, itemAt(i).get());
5755 }
5756 }
5757 return devices;
5758}
5759
Eric Laurent1afeecb2014-05-14 08:52:28 -07005760sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5761 const String8& name) const
5762{
5763 sp<DeviceDescriptor> device;
5764 for (size_t i = 0; i < size(); i++) {
5765 if (itemAt(i)->mName == name) {
5766 device = itemAt(i);
5767 break;
5768 }
5769 }
5770 return device;
5771}
5772
Eric Laurent6a94d692014-05-20 11:18:06 -07005773void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5774 struct audio_port_config *dstConfig,
5775 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005776{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005777 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
5778 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005779 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005780 }
5781
5782 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5783
Eric Laurent6a94d692014-05-20 11:18:06 -07005784 dstConfig->id = mId;
5785 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005786 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005787 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005788 dstConfig->ext.device.type = mDeviceType;
5789 dstConfig->ext.device.hw_module = mModule->mHandle;
5790 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005791}
5792
5793void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5794{
Eric Laurente1715a42014-05-20 11:30:42 -07005795 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07005796 AudioPort::toAudioPort(port);
5797 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005798 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005799 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005800 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005801 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5802}
5803
Eric Laurent1afeecb2014-05-14 08:52:28 -07005804status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005805{
5806 const size_t SIZE = 256;
5807 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005808 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005809
Eric Laurent1afeecb2014-05-14 08:52:28 -07005810 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5811 result.append(buffer);
5812 if (mId != 0) {
5813 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5814 result.append(buffer);
5815 }
5816 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5817 enumToString(sDeviceNameToEnumTable,
5818 ARRAY_SIZE(sDeviceNameToEnumTable),
5819 mDeviceType));
5820 result.append(buffer);
5821 if (mAddress.size() != 0) {
5822 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5823 result.append(buffer);
5824 }
5825 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5826 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5827 result.append(buffer);
5828 }
5829 write(fd, result.string(), result.size());
5830 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005831
5832 return NO_ERROR;
5833}
5834
5835
5836// --- audio_policy.conf file parsing
5837
Eric Laurente0720872014-03-11 09:30:41 -07005838audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005839{
5840 uint32_t flag = 0;
5841
5842 // it is OK to cast name to non const here as we are not going to use it after
5843 // strtok() modifies it
5844 char *flagName = strtok(name, "|");
5845 while (flagName != NULL) {
5846 if (strlen(flagName) != 0) {
5847 flag |= stringToEnum(sFlagNameToEnumTable,
5848 ARRAY_SIZE(sFlagNameToEnumTable),
5849 flagName);
5850 }
5851 flagName = strtok(NULL, "|");
5852 }
5853 //force direct flag if offload flag is set: offloading implies a direct output stream
5854 // and all common behaviors are driven by checking only the direct flag
5855 // this should normally be set appropriately in the policy configuration file
5856 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5857 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5858 }
5859
5860 return (audio_output_flags_t)flag;
5861}
5862
Eric Laurente0720872014-03-11 09:30:41 -07005863audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005864{
5865 uint32_t device = 0;
5866
5867 char *devName = strtok(name, "|");
5868 while (devName != NULL) {
5869 if (strlen(devName) != 0) {
5870 device |= stringToEnum(sDeviceNameToEnumTable,
5871 ARRAY_SIZE(sDeviceNameToEnumTable),
5872 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005873 }
Eric Laurente552edb2014-03-10 17:42:56 -07005874 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005875 }
Eric Laurente552edb2014-03-10 17:42:56 -07005876 return device;
5877}
5878
Eric Laurente0720872014-03-11 09:30:41 -07005879void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005880{
Eric Laurente552edb2014-03-10 17:42:56 -07005881 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005882 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005883 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07005884
Eric Laurent1afeecb2014-05-14 08:52:28 -07005885 node = config_find(root, DEVICES_TAG);
5886 if (node != NULL) {
5887 node = node->first_child;
5888 while (node) {
5889 ALOGV("loadHwModule() loading device %s", node->name);
5890 status_t tmpStatus = module->loadDevice(node);
5891 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5892 status = tmpStatus;
5893 }
5894 node = node->next;
5895 }
5896 }
5897 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005898 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005899 node = node->first_child;
5900 while (node) {
5901 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005902 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005903 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5904 status = tmpStatus;
5905 }
5906 node = node->next;
5907 }
5908 }
5909 node = config_find(root, INPUTS_TAG);
5910 if (node != NULL) {
5911 node = node->first_child;
5912 while (node) {
5913 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005914 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005915 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5916 status = tmpStatus;
5917 }
5918 node = node->next;
5919 }
5920 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005921 loadGlobalConfig(root, module);
5922
Eric Laurente552edb2014-03-10 17:42:56 -07005923 if (status == NO_ERROR) {
5924 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07005925 }
5926}
5927
Eric Laurente0720872014-03-11 09:30:41 -07005928void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005929{
5930 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5931 if (node == NULL) {
5932 return;
5933 }
5934
5935 node = node->first_child;
5936 while (node) {
5937 ALOGV("loadHwModules() loading module %s", node->name);
5938 loadHwModule(node);
5939 node = node->next;
5940 }
5941}
5942
Eric Laurent1f2f2232014-06-02 12:01:23 -07005943void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07005944{
5945 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07005946
Eric Laurente552edb2014-03-10 17:42:56 -07005947 if (node == NULL) {
5948 return;
5949 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005950 DeviceVector declaredDevices;
5951 if (module != NULL) {
5952 declaredDevices = module->mDeclaredDevices;
5953 }
5954
Eric Laurente552edb2014-03-10 17:42:56 -07005955 node = node->first_child;
5956 while (node) {
5957 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005958 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5959 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005960 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5961 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005962 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005963 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005964 ARRAY_SIZE(sDeviceNameToEnumTable),
5965 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005966 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005967 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005968 } else {
5969 ALOGW("loadGlobalConfig() default device not specified");
5970 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005971 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005972 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005973 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5974 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005975 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005976 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5977 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5978 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07005979 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
5980 uint32_t major, minor;
5981 sscanf((char *)node->value, "%u.%u", &major, &minor);
5982 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
5983 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
5984 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07005985 }
5986 node = node->next;
5987 }
5988}
5989
Eric Laurente0720872014-03-11 09:30:41 -07005990status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005991{
5992 cnode *root;
5993 char *data;
5994
5995 data = (char *)load_file(path, NULL);
5996 if (data == NULL) {
5997 return -ENODEV;
5998 }
5999 root = config_node("", "");
6000 config_load(root, data);
6001
Eric Laurente552edb2014-03-10 17:42:56 -07006002 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006003 // legacy audio_policy.conf files have one global_configuration section
6004 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006005 config_free(root);
6006 free(root);
6007 free(data);
6008
6009 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6010
6011 return NO_ERROR;
6012}
6013
Eric Laurente0720872014-03-11 09:30:41 -07006014void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006015{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006016 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006017 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006018 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6019 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006020 mAvailableOutputDevices.add(mDefaultOutputDevice);
6021 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006022
6023 module = new HwModule("primary");
6024
Eric Laurent1afeecb2014-05-14 08:52:28 -07006025 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006026 profile->mSamplingRates.add(44100);
6027 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6028 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006029 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006030 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6031 module->mOutputProfiles.add(profile);
6032
Eric Laurent1afeecb2014-05-14 08:52:28 -07006033 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006034 profile->mSamplingRates.add(8000);
6035 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6036 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006037 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006038 module->mInputProfiles.add(profile);
6039
6040 mHwModules.add(module);
6041}
6042
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006043audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6044{
6045 // flags to stream type mapping
6046 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6047 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6048 }
6049 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6050 return AUDIO_STREAM_BLUETOOTH_SCO;
6051 }
6052
6053 // usage to stream type mapping
6054 switch (attr->usage) {
6055 case AUDIO_USAGE_MEDIA:
6056 case AUDIO_USAGE_GAME:
6057 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6058 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6059 return AUDIO_STREAM_MUSIC;
6060 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6061 return AUDIO_STREAM_SYSTEM;
6062 case AUDIO_USAGE_VOICE_COMMUNICATION:
6063 return AUDIO_STREAM_VOICE_CALL;
6064
6065 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6066 return AUDIO_STREAM_DTMF;
6067
6068 case AUDIO_USAGE_ALARM:
6069 return AUDIO_STREAM_ALARM;
6070 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6071 return AUDIO_STREAM_RING;
6072
6073 case AUDIO_USAGE_NOTIFICATION:
6074 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6075 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6076 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6077 case AUDIO_USAGE_NOTIFICATION_EVENT:
6078 return AUDIO_STREAM_NOTIFICATION;
6079
6080 case AUDIO_USAGE_UNKNOWN:
6081 default:
6082 return AUDIO_STREAM_MUSIC;
6083 }
6084}
Eric Laurente552edb2014-03-10 17:42:56 -07006085}; // namespace android