blob: ee0251626cc6625968307eb519431258ab678fea [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
33
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
39#include <hardware/audio.h>
40#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070041#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070043#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070044
Eric Laurent3b73df72014-03-11 09:06:29 -070045namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070046
47// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070048// Definitions for audio_policy.conf file parsing
49// ----------------------------------------------------------------------------
50
51struct StringToEnum {
52 const char *name;
53 uint32_t value;
54};
55
56#define STRING_TO_ENUM(string) { #string, string }
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
59const StringToEnum sDeviceNameToEnumTable[] = {
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070073 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070074 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700104};
105
106const StringToEnum sFlagNameToEnumTable[] = {
107 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
113};
114
115const StringToEnum sFormatNameToEnumTable[] = {
116 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
122 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
123 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
124 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700125 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
126 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
127 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
128 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
129 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700130};
131
132const StringToEnum sOutChannelsNameToEnumTable[] = {
133 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
134 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
135 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
136 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
137};
138
139const StringToEnum sInChannelsNameToEnumTable[] = {
140 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
141 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
142 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
143};
144
Eric Laurent1afeecb2014-05-14 08:52:28 -0700145const StringToEnum sGainModeNameToEnumTable[] = {
146 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
147 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
148 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
149};
150
Eric Laurent3a4311c2014-03-17 12:00:47 -0700151
152uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
153 size_t size,
154 const char *name)
155{
156 for (size_t i = 0; i < size; i++) {
157 if (strcmp(table[i].name, name) == 0) {
158 ALOGV("stringToEnum() found %s", table[i].name);
159 return table[i].value;
160 }
161 }
162 return 0;
163}
164
165const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
166 size_t size,
167 uint32_t value)
168{
169 for (size_t i = 0; i < size; i++) {
170 if (table[i].value == value) {
171 return table[i].name;
172 }
173 }
174 return "";
175}
176
177bool AudioPolicyManager::stringToBool(const char *value)
178{
179 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
180}
181
182
183// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700184// AudioPolicyInterface implementation
185// ----------------------------------------------------------------------------
186
187
Eric Laurente0720872014-03-11 09:30:41 -0700188status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700189 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700190 const char *device_address)
191{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
194 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
195
196 // connect/disconnect only 1 device at a time
197 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 // handle output devices
200 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700201 SortedVector <audio_io_handle_t> outputs;
202
Eric Laurent1afeecb2014-05-14 08:52:28 -0700203 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
204 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700205 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
206
Eric Laurente552edb2014-03-10 17:42:56 -0700207 // save a copy of the opened output descriptors before any output is opened or closed
208 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
209 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700210 switch (state)
211 {
212 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700213 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700214 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700215 ALOGW("setDeviceConnectionState() device already connected: %x", device);
216 return INVALID_OPERATION;
217 }
218 ALOGV("setDeviceConnectionState() connecting device %x", device);
219
Eric Laurent3a4311c2014-03-17 12:00:47 -0700220 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700221 return INVALID_OPERATION;
222 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700223 // outputs should never be empty here
224 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
225 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700226 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700227 outputs.size());
228 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700229 index = mAvailableOutputDevices.add(devDesc);
230 if (index >= 0) {
231 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700232 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700233 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
234 "could not find HW module for device %08x", device);
235 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 } else {
237 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700238 }
239
240 break;
241 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700242 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700244 ALOGW("setDeviceConnectionState() device not connected: %x", device);
245 return INVALID_OPERATION;
246 }
247
248 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
249 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700253 // not currently handling multiple simultaneous submixes: ignoring remote submix
254 // case and address
255 } break;
256
257 default:
258 ALOGE("setDeviceConnectionState() invalid state: %x", state);
259 return BAD_VALUE;
260 }
261
Eric Laurent3a4311c2014-03-17 12:00:47 -0700262 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
263 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700264 checkA2dpSuspend();
265 checkOutputForAllStrategies();
266 // outputs must be closed after checkOutputForAllStrategies() is executed
267 if (!outputs.isEmpty()) {
268 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700269 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700270 // close unused outputs after device disconnection or direct outputs that have been
271 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700272 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700273 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
274 (desc->mDirectOpenCount == 0))) {
275 closeOutput(outputs[i]);
276 }
277 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 // check again after closing A2DP output to reset mA2dpSuspended if needed
279 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700280 }
281
282 updateDevicesAndOutputs();
283 for (size_t i = 0; i < mOutputs.size(); i++) {
284 // do not force device change on duplicated output because if device is 0, it will
285 // also force a device 0 for the two outputs it is duplicated to which may override
286 // a valid device selection on those outputs.
287 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700288 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700289 !mOutputs.valueAt(i)->isDuplicated(),
290 0);
291 }
292
Eric Laurent72aa32f2014-05-30 18:51:48 -0700293 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700294 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700295 } // end if is output device
296
Eric Laurente552edb2014-03-10 17:42:56 -0700297 // handle input devices
298 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700299 SortedVector <audio_io_handle_t> inputs;
300
Eric Laurent1afeecb2014-05-14 08:52:28 -0700301 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
302 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700304 switch (state)
305 {
306 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700307 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700308 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700309 ALOGW("setDeviceConnectionState() device already connected: %d", device);
310 return INVALID_OPERATION;
311 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700312 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700313 if (module == NULL) {
314 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
315 device);
316 return INVALID_OPERATION;
317 }
Eric Laurentd4692962014-05-05 18:13:44 -0700318 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
319 return INVALID_OPERATION;
320 }
321
Eric Laurent3a4311c2014-03-17 12:00:47 -0700322 index = mAvailableInputDevices.add(devDesc);
323 if (index >= 0) {
324 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700325 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 } else {
327 return NO_MEMORY;
328 }
Eric Laurentd4692962014-05-05 18:13:44 -0700329 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700330
331 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700332 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700334 ALOGW("setDeviceConnectionState() device not connected: %d", device);
335 return INVALID_OPERATION;
336 }
Eric Laurentd4692962014-05-05 18:13:44 -0700337 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700338 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700339 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700340
341 default:
342 ALOGE("setDeviceConnectionState() invalid state: %x", state);
343 return BAD_VALUE;
344 }
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700347
Eric Laurentb52c1522014-05-20 11:27:36 -0700348 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700349 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700350 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700351
352 ALOGW("setDeviceConnectionState() invalid device: %x", device);
353 return BAD_VALUE;
354}
355
Eric Laurente0720872014-03-11 09:30:41 -0700356audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700357 const char *device_address)
358{
Eric Laurent3b73df72014-03-11 09:06:29 -0700359 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700361 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
362 devDesc->mAddress = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700363 ssize_t index;
364 DeviceVector *deviceVector;
365
Eric Laurente552edb2014-03-10 17:42:56 -0700366 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700368 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700369 deviceVector = &mAvailableInputDevices;
370 } else {
371 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
372 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700373 }
374
Eric Laurent3a4311c2014-03-17 12:00:47 -0700375 index = deviceVector->indexOf(devDesc);
376 if (index >= 0) {
377 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
378 } else {
379 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
380 }
Eric Laurente552edb2014-03-10 17:42:56 -0700381}
382
Eric Laurente0720872014-03-11 09:30:41 -0700383void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700384{
385 ALOGV("setPhoneState() state %d", state);
386 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700388 ALOGW("setPhoneState() invalid state %d", state);
389 return;
390 }
391
392 if (state == mPhoneState ) {
393 ALOGW("setPhoneState() setting same state %d", state);
394 return;
395 }
396
397 // if leaving call state, handle special case of active streams
398 // pertaining to sonification strategy see handleIncallSonification()
399 if (isInCall()) {
400 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700401 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
402 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700403 }
404 }
405
406 // store previous phone state for management of sonification strategy below
407 int oldState = mPhoneState;
408 mPhoneState = state;
409 bool force = false;
410
411 // are we entering or starting a call
412 if (!isStateInCall(oldState) && isStateInCall(state)) {
413 ALOGV(" Entering call in setPhoneState()");
414 // force routing command to audio hardware when starting a call
415 // even if no device change is needed
416 force = true;
417 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
418 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
419 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
420 }
421 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
422 ALOGV(" Exiting call in setPhoneState()");
423 // force routing command to audio hardware when exiting a call
424 // even if no device change is needed
425 force = true;
426 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
427 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
428 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
429 }
430 } else if (isStateInCall(state) && (state != oldState)) {
431 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
432 // force routing command to audio hardware when switching between telephony and VoIP
433 // even if no device change is needed
434 force = true;
435 }
436
437 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700438 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700439 checkA2dpSuspend();
440 checkOutputForAllStrategies();
441 updateDevicesAndOutputs();
442
Eric Laurent1f2f2232014-06-02 12:01:23 -0700443 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700444
445 // force routing command to audio hardware when ending call
446 // even if no device change is needed
447 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
448 newDevice = hwOutputDesc->device();
449 }
450
451 int delayMs = 0;
452 if (isStateInCall(state)) {
453 nsecs_t sysTime = systemTime();
454 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700455 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700456 // mute media and sonification strategies and delay device switch by the largest
457 // latency of any output where either strategy is active.
458 // This avoid sending the ring tone or music tail into the earpiece or headset.
459 if ((desc->isStrategyActive(STRATEGY_MEDIA,
460 SONIFICATION_HEADSET_MUSIC_DELAY,
461 sysTime) ||
462 desc->isStrategyActive(STRATEGY_SONIFICATION,
463 SONIFICATION_HEADSET_MUSIC_DELAY,
464 sysTime)) &&
465 (delayMs < (int)desc->mLatency*2)) {
466 delayMs = desc->mLatency*2;
467 }
468 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
469 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
470 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
471 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
472 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
473 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
474 }
475 }
476
477 // change routing is necessary
478 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
479
480 // if entering in call state, handle special case of active streams
481 // pertaining to sonification strategy see handleIncallSonification()
482 if (isStateInCall(state)) {
483 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700484 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
485 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700486 }
487 }
488
489 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700490 if (state == AUDIO_MODE_RINGTONE &&
491 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700492 mLimitRingtoneVolume = true;
493 } else {
494 mLimitRingtoneVolume = false;
495 }
496}
497
Eric Laurente0720872014-03-11 09:30:41 -0700498void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700499 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700500{
501 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
502
503 bool forceVolumeReeval = false;
504 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700505 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
506 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
507 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700508 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
509 return;
510 }
511 forceVolumeReeval = true;
512 mForceUse[usage] = config;
513 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700514 case AUDIO_POLICY_FORCE_FOR_MEDIA:
515 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
516 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
517 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
518 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
519 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700520 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
521 return;
522 }
523 mForceUse[usage] = config;
524 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700525 case AUDIO_POLICY_FORCE_FOR_RECORD:
526 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
527 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700528 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
529 return;
530 }
531 mForceUse[usage] = config;
532 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700533 case AUDIO_POLICY_FORCE_FOR_DOCK:
534 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
535 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
536 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
537 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
538 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
540 }
541 forceVolumeReeval = true;
542 mForceUse[usage] = config;
543 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700544 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
545 if (config != AUDIO_POLICY_FORCE_NONE &&
546 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700547 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
548 }
549 forceVolumeReeval = true;
550 mForceUse[usage] = config;
551 break;
552 default:
553 ALOGW("setForceUse() invalid usage %d", usage);
554 break;
555 }
556
557 // check for device and output changes triggered by new force usage
558 checkA2dpSuspend();
559 checkOutputForAllStrategies();
560 updateDevicesAndOutputs();
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700563 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700564 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
565 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
566 applyStreamVolumes(output, newDevice, 0, true);
567 }
568 }
569
570 audio_io_handle_t activeInput = getActiveInput();
571 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700572 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700573 }
574
575}
576
Eric Laurente0720872014-03-11 09:30:41 -0700577audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700578{
579 return mForceUse[usage];
580}
581
Eric Laurente0720872014-03-11 09:30:41 -0700582void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700583{
584 ALOGV("setSystemProperty() property %s, value %s", property, value);
585}
586
587// Find a direct output profile compatible with the parameters passed, even if the input flags do
588// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700589sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700590 audio_devices_t device,
591 uint32_t samplingRate,
592 audio_format_t format,
593 audio_channel_mask_t channelMask,
594 audio_output_flags_t flags)
595{
596 for (size_t i = 0; i < mHwModules.size(); i++) {
597 if (mHwModules[i]->mHandle == 0) {
598 continue;
599 }
600 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700601 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700602 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700603 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
604 if (profile->isCompatibleProfile(device, samplingRate, format,
605 channelMask,
606 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700607 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700608 }
609 } else {
610 if (profile->isCompatibleProfile(device, samplingRate, format,
611 channelMask,
612 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700613 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700614 }
615 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700616 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
617 return profile;
618 }
Eric Laurente552edb2014-03-10 17:42:56 -0700619 }
620 }
621 return 0;
622}
623
Eric Laurente0720872014-03-11 09:30:41 -0700624audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700625 uint32_t samplingRate,
626 audio_format_t format,
627 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700628 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700629 const audio_offload_info_t *offloadInfo)
630{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700631
Eric Laurent3b73df72014-03-11 09:06:29 -0700632 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700633 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
634 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
635 device, stream, samplingRate, format, channelMask, flags);
636
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700637 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
638 offloadInfo);
639}
640
641audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
642 uint32_t samplingRate,
643 audio_format_t format,
644 audio_channel_mask_t channelMask,
645 audio_output_flags_t flags,
646 const audio_offload_info_t *offloadInfo)
647{
648 if (attr == NULL) {
649 ALOGE("getOutputForAttr() called with NULL audio attributes");
650 return 0;
651 }
652 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
653 attr->usage, attr->content_type, attr->tags);
654
655 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
656 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
657 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
658 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
659 device, samplingRate, format, channelMask, flags);
660
661 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
662 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
663 offloadInfo);
664}
665
666audio_io_handle_t AudioPolicyManager::getOutputForDevice(
667 audio_devices_t device,
668 audio_stream_type_t stream,
669 uint32_t samplingRate,
670 audio_format_t format,
671 audio_channel_mask_t channelMask,
672 audio_output_flags_t flags,
673 const audio_offload_info_t *offloadInfo)
674{
675 audio_io_handle_t output = 0;
676 uint32_t latency = 0;
677
Eric Laurente552edb2014-03-10 17:42:56 -0700678#ifdef AUDIO_POLICY_TEST
679 if (mCurOutput != 0) {
680 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
681 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
682
683 if (mTestOutputs[mCurOutput] == 0) {
684 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700685 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700686 outputDesc->mDevice = mTestDevice;
687 outputDesc->mSamplingRate = mTestSamplingRate;
688 outputDesc->mFormat = mTestFormat;
689 outputDesc->mChannelMask = mTestChannels;
690 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700691 outputDesc->mFlags =
692 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700693 outputDesc->mRefCount[stream] = 0;
694 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
695 &outputDesc->mSamplingRate,
696 &outputDesc->mFormat,
697 &outputDesc->mChannelMask,
698 &outputDesc->mLatency,
699 outputDesc->mFlags,
700 offloadInfo);
701 if (mTestOutputs[mCurOutput]) {
702 AudioParameter outputCmd = AudioParameter();
703 outputCmd.addInt(String8("set_id"),mCurOutput);
704 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
705 addOutput(mTestOutputs[mCurOutput], outputDesc);
706 }
707 }
708 return mTestOutputs[mCurOutput];
709 }
710#endif //AUDIO_POLICY_TEST
711
712 // open a direct output if required by specified parameters
713 //force direct flag if offload flag is set: offloading implies a direct output stream
714 // and all common behaviors are driven by checking only the direct flag
715 // this should normally be set appropriately in the policy configuration file
716 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700717 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700718 }
719
720 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
721 // creating an offloaded track and tearing it down immediately after start when audioflinger
722 // detects there is an active non offloadable effect.
723 // FIXME: We should check the audio session here but we do not have it in this context.
724 // This may prevent offloading in rare situations where effects are left active by apps
725 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700726 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700727 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
728 !isNonOffloadableEffectEnabled()) {
729 profile = getProfileForDirectOutput(device,
730 samplingRate,
731 format,
732 channelMask,
733 (audio_output_flags_t)flags);
734 }
735
Eric Laurent1c333e22014-05-20 10:48:17 -0700736 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700737 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700738
739 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700740 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700741 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
742 outputDesc = desc;
743 // reuse direct output if currently open and configured with same parameters
744 if ((samplingRate == outputDesc->mSamplingRate) &&
745 (format == outputDesc->mFormat) &&
746 (channelMask == outputDesc->mChannelMask)) {
747 outputDesc->mDirectOpenCount++;
748 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
749 return mOutputs.keyAt(i);
750 }
751 }
752 }
753 // close direct output if currently open and configured with different parameters
754 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700755 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700756 }
757 outputDesc = new AudioOutputDescriptor(profile);
758 outputDesc->mDevice = device;
759 outputDesc->mSamplingRate = samplingRate;
760 outputDesc->mFormat = format;
761 outputDesc->mChannelMask = channelMask;
762 outputDesc->mLatency = 0;
763 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
764 outputDesc->mRefCount[stream] = 0;
765 outputDesc->mStopTime[stream] = 0;
766 outputDesc->mDirectOpenCount = 1;
767 output = mpClientInterface->openOutput(profile->mModule->mHandle,
768 &outputDesc->mDevice,
769 &outputDesc->mSamplingRate,
770 &outputDesc->mFormat,
771 &outputDesc->mChannelMask,
772 &outputDesc->mLatency,
773 outputDesc->mFlags,
774 offloadInfo);
775
776 // only accept an output with the requested parameters
777 if (output == 0 ||
778 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
779 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
780 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
781 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
782 "format %d %d, channelMask %04x %04x", output, samplingRate,
783 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
784 outputDesc->mChannelMask);
785 if (output != 0) {
786 mpClientInterface->closeOutput(output);
787 }
Eric Laurente552edb2014-03-10 17:42:56 -0700788 return 0;
789 }
790 audio_io_handle_t srcOutput = getOutputForEffect();
791 addOutput(output, outputDesc);
792 audio_io_handle_t dstOutput = getOutputForEffect();
793 if (dstOutput == output) {
794 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
795 }
796 mPreviousOutputs = mOutputs;
797 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700798 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700799 return output;
800 }
801
802 // ignoring channel mask due to downmix capability in mixer
803
804 // open a non direct output
805
806 // for non direct outputs, only PCM is supported
807 if (audio_is_linear_pcm(format)) {
808 // get which output is suitable for the specified stream. The actual
809 // routing change will happen when startOutput() will be called
810 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
811
812 output = selectOutput(outputs, flags);
813 }
814 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
815 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
816
817 ALOGV("getOutput() returns output %d", output);
818
819 return output;
820}
821
Eric Laurente0720872014-03-11 09:30:41 -0700822audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700823 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700824{
825 // select one output among several that provide a path to a particular device or set of
826 // devices (the list was previously build by getOutputsForDevice()).
827 // The priority is as follows:
828 // 1: the output with the highest number of requested policy flags
829 // 2: the primary output
830 // 3: the first output in the list
831
832 if (outputs.size() == 0) {
833 return 0;
834 }
835 if (outputs.size() == 1) {
836 return outputs[0];
837 }
838
839 int maxCommonFlags = 0;
840 audio_io_handle_t outputFlags = 0;
841 audio_io_handle_t outputPrimary = 0;
842
843 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700844 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700845 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700846 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 if (commonFlags > maxCommonFlags) {
848 outputFlags = outputs[i];
849 maxCommonFlags = commonFlags;
850 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
851 }
852 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
853 outputPrimary = outputs[i];
854 }
855 }
856 }
857
858 if (outputFlags != 0) {
859 return outputFlags;
860 }
861 if (outputPrimary != 0) {
862 return outputPrimary;
863 }
864
865 return outputs[0];
866}
867
Eric Laurente0720872014-03-11 09:30:41 -0700868status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700869 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700870 int session)
871{
872 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
873 ssize_t index = mOutputs.indexOfKey(output);
874 if (index < 0) {
875 ALOGW("startOutput() unknown output %d", output);
876 return BAD_VALUE;
877 }
878
Eric Laurent1f2f2232014-06-02 12:01:23 -0700879 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700880
881 // increment usage count for this stream on the requested output:
882 // NOTE that the usage count is the same for duplicated output and hardware output which is
883 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
884 outputDesc->changeRefCount(stream, 1);
885
886 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700887 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700888 routing_strategy strategy = getStrategy(stream);
889 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
890 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
891 uint32_t waitMs = 0;
892 bool force = false;
893 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700894 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700895 if (desc != outputDesc) {
896 // force a device change if any other output is managed by the same hw
897 // module and has a current device selection that differs from selected device.
898 // In this case, the audio HAL must receive the new device selection so that it can
899 // change the device currently selected by the other active output.
900 if (outputDesc->sharesHwModuleWith(desc) &&
901 desc->device() != newDevice) {
902 force = true;
903 }
904 // wait for audio on other active outputs to be presented when starting
905 // a notification so that audio focus effect can propagate.
906 uint32_t latency = desc->latency();
907 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
908 waitMs = latency;
909 }
910 }
911 }
912 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
913
914 // handle special case for sonification while in call
915 if (isInCall()) {
916 handleIncallSonification(stream, true, false);
917 }
918
919 // apply volume rules for current stream and device if necessary
920 checkAndSetVolume(stream,
921 mStreams[stream].getVolumeIndex(newDevice),
922 output,
923 newDevice);
924
925 // update the outputs if starting an output with a stream that can affect notification
926 // routing
927 handleNotificationRoutingForStream(stream);
928 if (waitMs > muteWaitMs) {
929 usleep((waitMs - muteWaitMs) * 2 * 1000);
930 }
931 }
932 return NO_ERROR;
933}
934
935
Eric Laurente0720872014-03-11 09:30:41 -0700936status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700937 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700938 int session)
939{
940 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
941 ssize_t index = mOutputs.indexOfKey(output);
942 if (index < 0) {
943 ALOGW("stopOutput() unknown output %d", output);
944 return BAD_VALUE;
945 }
946
Eric Laurent1f2f2232014-06-02 12:01:23 -0700947 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700948
949 // handle special case for sonification while in call
950 if (isInCall()) {
951 handleIncallSonification(stream, false, false);
952 }
953
954 if (outputDesc->mRefCount[stream] > 0) {
955 // decrement usage count of this stream on the output
956 outputDesc->changeRefCount(stream, -1);
957 // store time at which the stream was stopped - see isStreamActive()
958 if (outputDesc->mRefCount[stream] == 0) {
959 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700960 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700961 // delay the device switch by twice the latency because stopOutput() is executed when
962 // the track stop() command is received and at that time the audio track buffer can
963 // still contain data that needs to be drained. The latency only covers the audio HAL
964 // and kernel buffers. Also the latency does not always include additional delay in the
965 // audio path (audio DSP, CODEC ...)
966 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
967
968 // force restoring the device selection on other active outputs if it differs from the
969 // one being selected for this output
970 for (size_t i = 0; i < mOutputs.size(); i++) {
971 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700972 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700973 if (curOutput != output &&
974 desc->isActive() &&
975 outputDesc->sharesHwModuleWith(desc) &&
976 (newDevice != desc->device())) {
977 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700978 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700979 true,
980 outputDesc->mLatency*2);
981 }
982 }
983 // update the outputs if stopping one with a stream that can affect notification routing
984 handleNotificationRoutingForStream(stream);
985 }
986 return NO_ERROR;
987 } else {
988 ALOGW("stopOutput() refcount is already 0 for output %d", output);
989 return INVALID_OPERATION;
990 }
991}
992
Eric Laurente0720872014-03-11 09:30:41 -0700993void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700994{
995 ALOGV("releaseOutput() %d", output);
996 ssize_t index = mOutputs.indexOfKey(output);
997 if (index < 0) {
998 ALOGW("releaseOutput() releasing unknown output %d", output);
999 return;
1000 }
1001
1002#ifdef AUDIO_POLICY_TEST
1003 int testIndex = testOutputIndex(output);
1004 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001005 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001006 if (outputDesc->isActive()) {
1007 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001008 mOutputs.removeItem(output);
1009 mTestOutputs[testIndex] = 0;
1010 }
1011 return;
1012 }
1013#endif //AUDIO_POLICY_TEST
1014
Eric Laurent1f2f2232014-06-02 12:01:23 -07001015 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001016 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001017 if (desc->mDirectOpenCount <= 0) {
1018 ALOGW("releaseOutput() invalid open count %d for output %d",
1019 desc->mDirectOpenCount, output);
1020 return;
1021 }
1022 if (--desc->mDirectOpenCount == 0) {
1023 closeOutput(output);
1024 // If effects where present on the output, audioflinger moved them to the primary
1025 // output by default: move them back to the appropriate output.
1026 audio_io_handle_t dstOutput = getOutputForEffect();
1027 if (dstOutput != mPrimaryOutput) {
1028 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1029 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001030 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001031 }
1032 }
1033}
1034
1035
Eric Laurente0720872014-03-11 09:30:41 -07001036audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001037 uint32_t samplingRate,
1038 audio_format_t format,
1039 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001040 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001041{
1042 audio_io_handle_t input = 0;
1043 audio_devices_t device = getDeviceForInputSource(inputSource);
1044
1045 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1046 inputSource, samplingRate, format, channelMask, acoustics);
1047
1048 if (device == AUDIO_DEVICE_NONE) {
1049 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1050 return 0;
1051 }
1052
1053 // adapt channel selection to input source
1054 switch(inputSource) {
1055 case AUDIO_SOURCE_VOICE_UPLINK:
1056 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1057 break;
1058 case AUDIO_SOURCE_VOICE_DOWNLINK:
1059 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1060 break;
1061 case AUDIO_SOURCE_VOICE_CALL:
1062 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1063 break;
1064 default:
1065 break;
1066 }
1067
Eric Laurent1c333e22014-05-20 10:48:17 -07001068 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001069 samplingRate,
1070 format,
1071 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001072 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001073 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1074 "channelMask %04x",
1075 device, samplingRate, format, channelMask);
1076 return 0;
1077 }
1078
1079 if (profile->mModule->mHandle == 0) {
1080 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1081 return 0;
1082 }
1083
Eric Laurent1f2f2232014-06-02 12:01:23 -07001084 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001085
1086 inputDesc->mInputSource = inputSource;
1087 inputDesc->mDevice = device;
1088 inputDesc->mSamplingRate = samplingRate;
1089 inputDesc->mFormat = format;
1090 inputDesc->mChannelMask = channelMask;
1091 inputDesc->mRefCount = 0;
1092 input = mpClientInterface->openInput(profile->mModule->mHandle,
1093 &inputDesc->mDevice,
1094 &inputDesc->mSamplingRate,
1095 &inputDesc->mFormat,
1096 &inputDesc->mChannelMask);
1097
1098 // only accept input with the exact requested set of parameters
1099 if (input == 0 ||
1100 (samplingRate != inputDesc->mSamplingRate) ||
1101 (format != inputDesc->mFormat) ||
1102 (channelMask != inputDesc->mChannelMask)) {
1103 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1104 samplingRate, format, channelMask);
1105 if (input != 0) {
1106 mpClientInterface->closeInput(input);
1107 }
Eric Laurente552edb2014-03-10 17:42:56 -07001108 return 0;
1109 }
Eric Laurentd4692962014-05-05 18:13:44 -07001110 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001111 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001112 return input;
1113}
1114
Eric Laurente0720872014-03-11 09:30:41 -07001115status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001116{
1117 ALOGV("startInput() input %d", input);
1118 ssize_t index = mInputs.indexOfKey(input);
1119 if (index < 0) {
1120 ALOGW("startInput() unknown input %d", input);
1121 return BAD_VALUE;
1122 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001123 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001124
1125#ifdef AUDIO_POLICY_TEST
1126 if (mTestInput == 0)
1127#endif //AUDIO_POLICY_TEST
1128 {
1129 // refuse 2 active AudioRecord clients at the same time except if the active input
1130 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1131 audio_io_handle_t activeInput = getActiveInput();
1132 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001133 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001134 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1135 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1136 stopInput(activeInput);
1137 releaseInput(activeInput);
1138 } else {
1139 ALOGW("startInput() input %d failed: other input already started", input);
1140 return INVALID_OPERATION;
1141 }
1142 }
1143 }
1144
Eric Laurent1c333e22014-05-20 10:48:17 -07001145 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001146
1147 // automatically enable the remote submix output when input is started
1148 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1149 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001150 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001151 }
1152
Eric Laurente552edb2014-03-10 17:42:56 -07001153 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1154
Eric Laurente552edb2014-03-10 17:42:56 -07001155 inputDesc->mRefCount = 1;
1156 return NO_ERROR;
1157}
1158
Eric Laurente0720872014-03-11 09:30:41 -07001159status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001160{
1161 ALOGV("stopInput() input %d", input);
1162 ssize_t index = mInputs.indexOfKey(input);
1163 if (index < 0) {
1164 ALOGW("stopInput() unknown input %d", input);
1165 return BAD_VALUE;
1166 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001167 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001168
1169 if (inputDesc->mRefCount == 0) {
1170 ALOGW("stopInput() input %d already stopped", input);
1171 return INVALID_OPERATION;
1172 } else {
1173 // automatically disable the remote submix output when input is stopped
1174 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1175 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001176 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001177 }
1178
Eric Laurent1c333e22014-05-20 10:48:17 -07001179 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001180 inputDesc->mRefCount = 0;
1181 return NO_ERROR;
1182 }
1183}
1184
Eric Laurente0720872014-03-11 09:30:41 -07001185void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
1187 ALOGV("releaseInput() %d", input);
1188 ssize_t index = mInputs.indexOfKey(input);
1189 if (index < 0) {
1190 ALOGW("releaseInput() releasing unknown input %d", input);
1191 return;
1192 }
1193 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001194 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001195 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001196 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001197 ALOGV("releaseInput() exit");
1198}
1199
Eric Laurentd4692962014-05-05 18:13:44 -07001200void AudioPolicyManager::closeAllInputs() {
1201 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1202 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1203 }
1204 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001205 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001206}
1207
Eric Laurente0720872014-03-11 09:30:41 -07001208void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001209 int indexMin,
1210 int indexMax)
1211{
1212 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1213 if (indexMin < 0 || indexMin >= indexMax) {
1214 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1215 return;
1216 }
1217 mStreams[stream].mIndexMin = indexMin;
1218 mStreams[stream].mIndexMax = indexMax;
1219}
1220
Eric Laurente0720872014-03-11 09:30:41 -07001221status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001222 int index,
1223 audio_devices_t device)
1224{
1225
1226 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1227 return BAD_VALUE;
1228 }
1229 if (!audio_is_output_device(device)) {
1230 return BAD_VALUE;
1231 }
1232
1233 // Force max volume if stream cannot be muted
1234 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1235
1236 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1237 stream, device, index);
1238
1239 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1240 // clear all device specific values
1241 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1242 mStreams[stream].mIndexCur.clear();
1243 }
1244 mStreams[stream].mIndexCur.add(device, index);
1245
1246 // compute and apply stream volume on all outputs according to connected device
1247 status_t status = NO_ERROR;
1248 for (size_t i = 0; i < mOutputs.size(); i++) {
1249 audio_devices_t curDevice =
1250 getDeviceForVolume(mOutputs.valueAt(i)->device());
1251 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1252 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1253 if (volStatus != NO_ERROR) {
1254 status = volStatus;
1255 }
1256 }
1257 }
1258 return status;
1259}
1260
Eric Laurente0720872014-03-11 09:30:41 -07001261status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001262 int *index,
1263 audio_devices_t device)
1264{
1265 if (index == NULL) {
1266 return BAD_VALUE;
1267 }
1268 if (!audio_is_output_device(device)) {
1269 return BAD_VALUE;
1270 }
1271 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1272 // the strategy the stream belongs to.
1273 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1274 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1275 }
1276 device = getDeviceForVolume(device);
1277
1278 *index = mStreams[stream].getVolumeIndex(device);
1279 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1280 return NO_ERROR;
1281}
1282
Eric Laurente0720872014-03-11 09:30:41 -07001283audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001284 const SortedVector<audio_io_handle_t>& outputs)
1285{
1286 // select one output among several suitable for global effects.
1287 // The priority is as follows:
1288 // 1: An offloaded output. If the effect ends up not being offloadable,
1289 // AudioFlinger will invalidate the track and the offloaded output
1290 // will be closed causing the effect to be moved to a PCM output.
1291 // 2: A deep buffer output
1292 // 3: the first output in the list
1293
1294 if (outputs.size() == 0) {
1295 return 0;
1296 }
1297
1298 audio_io_handle_t outputOffloaded = 0;
1299 audio_io_handle_t outputDeepBuffer = 0;
1300
1301 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001302 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001303 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001304 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1305 outputOffloaded = outputs[i];
1306 }
1307 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1308 outputDeepBuffer = outputs[i];
1309 }
1310 }
1311
1312 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1313 outputOffloaded, outputDeepBuffer);
1314 if (outputOffloaded != 0) {
1315 return outputOffloaded;
1316 }
1317 if (outputDeepBuffer != 0) {
1318 return outputDeepBuffer;
1319 }
1320
1321 return outputs[0];
1322}
1323
Eric Laurente0720872014-03-11 09:30:41 -07001324audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001325{
1326 // apply simple rule where global effects are attached to the same output as MUSIC streams
1327
Eric Laurent3b73df72014-03-11 09:06:29 -07001328 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001329 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1330 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1331
1332 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1333 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1334 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1335
1336 return output;
1337}
1338
Eric Laurente0720872014-03-11 09:30:41 -07001339status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001340 audio_io_handle_t io,
1341 uint32_t strategy,
1342 int session,
1343 int id)
1344{
1345 ssize_t index = mOutputs.indexOfKey(io);
1346 if (index < 0) {
1347 index = mInputs.indexOfKey(io);
1348 if (index < 0) {
1349 ALOGW("registerEffect() unknown io %d", io);
1350 return INVALID_OPERATION;
1351 }
1352 }
1353
1354 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1355 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1356 desc->name, desc->memoryUsage);
1357 return INVALID_OPERATION;
1358 }
1359 mTotalEffectsMemory += desc->memoryUsage;
1360 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1361 desc->name, io, strategy, session, id);
1362 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1363
Eric Laurent1f2f2232014-06-02 12:01:23 -07001364 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1365 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1366 effectDesc->mIo = io;
1367 effectDesc->mStrategy = (routing_strategy)strategy;
1368 effectDesc->mSession = session;
1369 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001370
Eric Laurent1f2f2232014-06-02 12:01:23 -07001371 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001372
1373 return NO_ERROR;
1374}
1375
Eric Laurente0720872014-03-11 09:30:41 -07001376status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001377{
1378 ssize_t index = mEffects.indexOfKey(id);
1379 if (index < 0) {
1380 ALOGW("unregisterEffect() unknown effect ID %d", id);
1381 return INVALID_OPERATION;
1382 }
1383
Eric Laurent1f2f2232014-06-02 12:01:23 -07001384 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001385
Eric Laurent1f2f2232014-06-02 12:01:23 -07001386 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001387
Eric Laurent1f2f2232014-06-02 12:01:23 -07001388 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001389 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001390 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1391 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001392 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001393 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001394 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001395 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001396
1397 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001398
1399 return NO_ERROR;
1400}
1401
Eric Laurente0720872014-03-11 09:30:41 -07001402status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001403{
1404 ssize_t index = mEffects.indexOfKey(id);
1405 if (index < 0) {
1406 ALOGW("unregisterEffect() unknown effect ID %d", id);
1407 return INVALID_OPERATION;
1408 }
1409
1410 return setEffectEnabled(mEffects.valueAt(index), enabled);
1411}
1412
Eric Laurent1f2f2232014-06-02 12:01:23 -07001413status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001414{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001415 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001416 ALOGV("setEffectEnabled(%s) effect already %s",
1417 enabled?"true":"false", enabled?"enabled":"disabled");
1418 return INVALID_OPERATION;
1419 }
1420
1421 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001423 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001424 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001425 return INVALID_OPERATION;
1426 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001427 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001428 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1429 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001430 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001431 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001432 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1433 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001434 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001435 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001436 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1437 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001438 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001439 return NO_ERROR;
1440}
1441
Eric Laurente0720872014-03-11 09:30:41 -07001442bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001443{
1444 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001445 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1446 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1447 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001448 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001449 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001450 return true;
1451 }
1452 }
1453 return false;
1454}
1455
Eric Laurente0720872014-03-11 09:30:41 -07001456bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001457{
1458 nsecs_t sysTime = systemTime();
1459 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001460 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001461 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001462 return true;
1463 }
1464 }
1465 return false;
1466}
1467
Eric Laurente0720872014-03-11 09:30:41 -07001468bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001469 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001470{
1471 nsecs_t sysTime = systemTime();
1472 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001473 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001474 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001475 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001476 return true;
1477 }
1478 }
1479 return false;
1480}
1481
Eric Laurente0720872014-03-11 09:30:41 -07001482bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001483{
1484 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001485 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001486 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001487 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001488 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1489 && (inputDescriptor->mRefCount > 0)) {
1490 return true;
1491 }
1492 }
1493 return false;
1494}
1495
1496
Eric Laurente0720872014-03-11 09:30:41 -07001497status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001498{
1499 const size_t SIZE = 256;
1500 char buffer[SIZE];
1501 String8 result;
1502
1503 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1504 result.append(buffer);
1505
1506 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1507 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001508 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1509 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001510 snprintf(buffer, SIZE, " Force use for communications %d\n",
1511 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001512 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001513 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001514 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001515 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001516 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001517 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001518 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001519 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001520 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001521
Eric Laurent3a4311c2014-03-17 12:00:47 -07001522 snprintf(buffer, SIZE, " Available output devices:\n");
1523 result.append(buffer);
1524 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001525 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001526 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001527 }
1528 snprintf(buffer, SIZE, "\n Available input devices:\n");
1529 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001530 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001531 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001532 }
Eric Laurente552edb2014-03-10 17:42:56 -07001533
1534 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1535 write(fd, buffer, strlen(buffer));
1536 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001537 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001538 write(fd, buffer, strlen(buffer));
1539 mHwModules[i]->dump(fd);
1540 }
1541
1542 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1543 write(fd, buffer, strlen(buffer));
1544 for (size_t i = 0; i < mOutputs.size(); i++) {
1545 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1546 write(fd, buffer, strlen(buffer));
1547 mOutputs.valueAt(i)->dump(fd);
1548 }
1549
1550 snprintf(buffer, SIZE, "\nInputs dump:\n");
1551 write(fd, buffer, strlen(buffer));
1552 for (size_t i = 0; i < mInputs.size(); i++) {
1553 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1554 write(fd, buffer, strlen(buffer));
1555 mInputs.valueAt(i)->dump(fd);
1556 }
1557
1558 snprintf(buffer, SIZE, "\nStreams dump:\n");
1559 write(fd, buffer, strlen(buffer));
1560 snprintf(buffer, SIZE,
1561 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1562 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001563 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001564 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 write(fd, buffer, strlen(buffer));
1566 mStreams[i].dump(fd);
1567 }
1568
1569 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1570 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1571 write(fd, buffer, strlen(buffer));
1572
1573 snprintf(buffer, SIZE, "Registered effects:\n");
1574 write(fd, buffer, strlen(buffer));
1575 for (size_t i = 0; i < mEffects.size(); i++) {
1576 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1577 write(fd, buffer, strlen(buffer));
1578 mEffects.valueAt(i)->dump(fd);
1579 }
1580
1581
1582 return NO_ERROR;
1583}
1584
1585// This function checks for the parameters which can be offloaded.
1586// This can be enhanced depending on the capability of the DSP and policy
1587// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001588bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001589{
1590 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001591 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001592 offloadInfo.sample_rate, offloadInfo.channel_mask,
1593 offloadInfo.format,
1594 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1595 offloadInfo.has_video);
1596
1597 // Check if offload has been disabled
1598 char propValue[PROPERTY_VALUE_MAX];
1599 if (property_get("audio.offload.disable", propValue, "0")) {
1600 if (atoi(propValue) != 0) {
1601 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1602 return false;
1603 }
1604 }
1605
1606 // Check if stream type is music, then only allow offload as of now.
1607 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1608 {
1609 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1610 return false;
1611 }
1612
1613 //TODO: enable audio offloading with video when ready
1614 if (offloadInfo.has_video)
1615 {
1616 ALOGV("isOffloadSupported: has_video == true, returning false");
1617 return false;
1618 }
1619
1620 //If duration is less than minimum value defined in property, return false
1621 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1622 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1623 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1624 return false;
1625 }
1626 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1627 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1628 return false;
1629 }
1630
1631 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1632 // creating an offloaded track and tearing it down immediately after start when audioflinger
1633 // detects there is an active non offloadable effect.
1634 // FIXME: We should check the audio session here but we do not have it in this context.
1635 // This may prevent offloading in rare situations where effects are left active by apps
1636 // in the background.
1637 if (isNonOffloadableEffectEnabled()) {
1638 return false;
1639 }
1640
1641 // See if there is a profile to support this.
1642 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001643 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001644 offloadInfo.sample_rate,
1645 offloadInfo.format,
1646 offloadInfo.channel_mask,
1647 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001648 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1649 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001650}
1651
Eric Laurent6a94d692014-05-20 11:18:06 -07001652status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1653 audio_port_type_t type,
1654 unsigned int *num_ports,
1655 struct audio_port *ports,
1656 unsigned int *generation)
1657{
1658 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1659 generation == NULL) {
1660 return BAD_VALUE;
1661 }
1662 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1663 if (ports == NULL) {
1664 *num_ports = 0;
1665 }
1666
1667 size_t portsWritten = 0;
1668 size_t portsMax = *num_ports;
1669 *num_ports = 0;
1670 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1671 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1672 for (size_t i = 0;
1673 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1674 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1675 }
1676 *num_ports += mAvailableOutputDevices.size();
1677 }
1678 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1679 for (size_t i = 0;
1680 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1681 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1682 }
1683 *num_ports += mAvailableInputDevices.size();
1684 }
1685 }
1686 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1687 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1688 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1689 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1690 }
1691 *num_ports += mInputs.size();
1692 }
1693 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001694 size_t numOutputs = 0;
1695 for (size_t i = 0; i < mOutputs.size(); i++) {
1696 if (!mOutputs[i]->isDuplicated()) {
1697 numOutputs++;
1698 if (portsWritten < portsMax) {
1699 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1700 }
1701 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001702 }
Eric Laurent84c70242014-06-23 08:46:27 -07001703 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001704 }
1705 }
1706 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001707 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001708 return NO_ERROR;
1709}
1710
1711status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1712{
1713 return NO_ERROR;
1714}
1715
Eric Laurent1f2f2232014-06-02 12:01:23 -07001716sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001717 audio_port_handle_t id) const
1718{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001719 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001720 for (size_t i = 0; i < mOutputs.size(); i++) {
1721 outputDesc = mOutputs.valueAt(i);
1722 if (outputDesc->mId == id) {
1723 break;
1724 }
1725 }
1726 return outputDesc;
1727}
1728
Eric Laurent1f2f2232014-06-02 12:01:23 -07001729sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001730 audio_port_handle_t id) const
1731{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001732 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001733 for (size_t i = 0; i < mInputs.size(); i++) {
1734 inputDesc = mInputs.valueAt(i);
1735 if (inputDesc->mId == id) {
1736 break;
1737 }
1738 }
1739 return inputDesc;
1740}
1741
Eric Laurent1f2f2232014-06-02 12:01:23 -07001742sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1743 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001744{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001745 sp <HwModule> module;
1746
Eric Laurent6a94d692014-05-20 11:18:06 -07001747 for (size_t i = 0; i < mHwModules.size(); i++) {
1748 if (mHwModules[i]->mHandle == 0) {
1749 continue;
1750 }
1751 if (audio_is_output_device(device)) {
1752 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1753 {
1754 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1755 return mHwModules[i];
1756 }
1757 }
1758 } else {
1759 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1760 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1761 device & ~AUDIO_DEVICE_BIT_IN) {
1762 return mHwModules[i];
1763 }
1764 }
1765 }
1766 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001767 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001768}
1769
Eric Laurent1f2f2232014-06-02 12:01:23 -07001770sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001771{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001772 sp <HwModule> module;
1773
Eric Laurent1afeecb2014-05-14 08:52:28 -07001774 for (size_t i = 0; i < mHwModules.size(); i++)
1775 {
1776 if (strcmp(mHwModules[i]->mName, name) == 0) {
1777 return mHwModules[i];
1778 }
1779 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001780 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001781}
1782
1783
Eric Laurent6a94d692014-05-20 11:18:06 -07001784status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1785 audio_patch_handle_t *handle,
1786 uid_t uid)
1787{
1788 ALOGV("createAudioPatch()");
1789
1790 if (handle == NULL || patch == NULL) {
1791 return BAD_VALUE;
1792 }
1793 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1794
1795 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1796 return INVALID_OPERATION;
1797 }
1798 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1799 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1800 return INVALID_OPERATION;
1801 }
1802
1803 sp<AudioPatch> patchDesc;
1804 ssize_t index = mAudioPatches.indexOfKey(*handle);
1805
1806 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1807 patch->sinks[0].type);
1808 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1809 patch->sources[0].role,
1810 patch->sources[0].type);
1811
1812 if (index >= 0) {
1813 patchDesc = mAudioPatches.valueAt(index);
1814 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1815 mUidCached, patchDesc->mUid, uid);
1816 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1817 return INVALID_OPERATION;
1818 }
1819 } else {
1820 *handle = 0;
1821 }
1822
1823 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1824 // TODO add support for mix to mix connection
1825 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1826 ALOGV("createAudioPatch() source mix sink not device");
1827 return BAD_VALUE;
1828 }
1829 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001830 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001831 if (outputDesc == NULL) {
1832 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1833 return BAD_VALUE;
1834 }
Eric Laurent84c70242014-06-23 08:46:27 -07001835 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1836 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001837 if (patchDesc != 0) {
1838 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1839 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1840 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1841 return BAD_VALUE;
1842 }
1843 }
1844 sp<DeviceDescriptor> devDesc =
1845 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1846 if (devDesc == 0) {
1847 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1848 return BAD_VALUE;
1849 }
1850
Eric Laurent84c70242014-06-23 08:46:27 -07001851 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001852 patch->sources[0].sample_rate,
1853 patch->sources[0].format,
1854 patch->sources[0].channel_mask,
1855 AUDIO_OUTPUT_FLAG_NONE)) {
1856 return INVALID_OPERATION;
1857 }
1858 // TODO: reconfigure output format and channels here
1859 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001860 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001861 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001862 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001863 true,
1864 0,
1865 handle);
1866 index = mAudioPatches.indexOfKey(*handle);
1867 if (index >= 0) {
1868 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1869 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1870 }
1871 patchDesc = mAudioPatches.valueAt(index);
1872 patchDesc->mUid = uid;
1873 ALOGV("createAudioPatch() success");
1874 } else {
1875 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1876 return INVALID_OPERATION;
1877 }
1878 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1879 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1880 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001881 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001882 if (inputDesc == NULL) {
1883 return BAD_VALUE;
1884 }
1885 if (patchDesc != 0) {
1886 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1887 return BAD_VALUE;
1888 }
1889 }
1890 sp<DeviceDescriptor> devDesc =
1891 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1892 if (devDesc == 0) {
1893 return BAD_VALUE;
1894 }
1895
Eric Laurent84c70242014-06-23 08:46:27 -07001896 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001897 patch->sinks[0].sample_rate,
1898 patch->sinks[0].format,
1899 patch->sinks[0].channel_mask,
1900 AUDIO_OUTPUT_FLAG_NONE)) {
1901 return INVALID_OPERATION;
1902 }
1903 // TODO: reconfigure output format and channels here
1904 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001905 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001906 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001907 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001908 true,
1909 handle);
1910 index = mAudioPatches.indexOfKey(*handle);
1911 if (index >= 0) {
1912 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1913 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1914 }
1915 patchDesc = mAudioPatches.valueAt(index);
1916 patchDesc->mUid = uid;
1917 ALOGV("createAudioPatch() success");
1918 } else {
1919 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1920 return INVALID_OPERATION;
1921 }
1922 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1923 // device to device connection
1924 if (patchDesc != 0) {
1925 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1926 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1927 return BAD_VALUE;
1928 }
1929 }
1930
1931 sp<DeviceDescriptor> srcDeviceDesc =
1932 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1933 sp<DeviceDescriptor> sinkDeviceDesc =
1934 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1935 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1936 return BAD_VALUE;
1937 }
1938 //update source and sink with our own data as the data passed in the patch may
1939 // be incomplete.
1940 struct audio_patch newPatch = *patch;
1941 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1942 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1943
1944 // TODO: add support for devices on different HW modules
1945 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1946 return INVALID_OPERATION;
1947 }
1948 // TODO: check from routing capabilities in config file and other conflicting patches
1949
1950 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1951 if (index >= 0) {
1952 afPatchHandle = patchDesc->mAfPatchHandle;
1953 }
1954
1955 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1956 &afPatchHandle,
1957 0);
1958 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1959 status, afPatchHandle);
1960 if (status == NO_ERROR) {
1961 if (index < 0) {
1962 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1963 &newPatch, uid);
1964 addAudioPatch(patchDesc->mHandle, patchDesc);
1965 } else {
1966 patchDesc->mPatch = newPatch;
1967 }
1968 patchDesc->mAfPatchHandle = afPatchHandle;
1969 *handle = patchDesc->mHandle;
1970 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001971 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001972 } else {
1973 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1974 status);
1975 return INVALID_OPERATION;
1976 }
1977 } else {
1978 return BAD_VALUE;
1979 }
1980 } else {
1981 return BAD_VALUE;
1982 }
1983 return NO_ERROR;
1984}
1985
1986status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1987 uid_t uid)
1988{
1989 ALOGV("releaseAudioPatch() patch %d", handle);
1990
1991 ssize_t index = mAudioPatches.indexOfKey(handle);
1992
1993 if (index < 0) {
1994 return BAD_VALUE;
1995 }
1996 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1997 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1998 mUidCached, patchDesc->mUid, uid);
1999 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2000 return INVALID_OPERATION;
2001 }
2002
2003 struct audio_patch *patch = &patchDesc->mPatch;
2004 patchDesc->mUid = mUidCached;
2005 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002006 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002007 if (outputDesc == NULL) {
2008 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2009 return BAD_VALUE;
2010 }
2011
2012 setOutputDevice(outputDesc->mIoHandle,
2013 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2014 true,
2015 0,
2016 NULL);
2017 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2018 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002019 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002020 if (inputDesc == NULL) {
2021 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2022 return BAD_VALUE;
2023 }
2024 setInputDevice(inputDesc->mIoHandle,
2025 getNewInputDevice(inputDesc->mIoHandle),
2026 true,
2027 NULL);
2028 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2029 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2030 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2031 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2032 status, patchDesc->mAfPatchHandle);
2033 removeAudioPatch(patchDesc->mHandle);
2034 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002035 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002036 } else {
2037 return BAD_VALUE;
2038 }
2039 } else {
2040 return BAD_VALUE;
2041 }
2042 return NO_ERROR;
2043}
2044
2045status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2046 struct audio_patch *patches,
2047 unsigned int *generation)
2048{
2049 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2050 generation == NULL) {
2051 return BAD_VALUE;
2052 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002053 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002054 *num_patches, patches, mAudioPatches.size());
2055 if (patches == NULL) {
2056 *num_patches = 0;
2057 }
2058
2059 size_t patchesWritten = 0;
2060 size_t patchesMax = *num_patches;
2061 for (size_t i = 0;
2062 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2063 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2064 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002065 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002066 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2067 }
2068 *num_patches = mAudioPatches.size();
2069
2070 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002071 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002072 return NO_ERROR;
2073}
2074
Eric Laurente1715a42014-05-20 11:30:42 -07002075status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002076{
Eric Laurente1715a42014-05-20 11:30:42 -07002077 ALOGV("setAudioPortConfig()");
2078
2079 if (config == NULL) {
2080 return BAD_VALUE;
2081 }
2082 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2083 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002084 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2085 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002086 }
2087
Eric Laurenta121f902014-06-03 13:32:54 -07002088 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002089 if (config->type == AUDIO_PORT_TYPE_MIX) {
2090 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002091 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002092 if (outputDesc == NULL) {
2093 return BAD_VALUE;
2094 }
Eric Laurent84c70242014-06-23 08:46:27 -07002095 ALOG_ASSERT(!outputDesc->isDuplicated(),
2096 "setAudioPortConfig() called on duplicated output %d",
2097 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002098 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002099 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002100 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002101 if (inputDesc == NULL) {
2102 return BAD_VALUE;
2103 }
Eric Laurenta121f902014-06-03 13:32:54 -07002104 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002105 } else {
2106 return BAD_VALUE;
2107 }
2108 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2109 sp<DeviceDescriptor> deviceDesc;
2110 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2111 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2112 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2113 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2114 } else {
2115 return BAD_VALUE;
2116 }
2117 if (deviceDesc == NULL) {
2118 return BAD_VALUE;
2119 }
Eric Laurenta121f902014-06-03 13:32:54 -07002120 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002121 } else {
2122 return BAD_VALUE;
2123 }
2124
Eric Laurenta121f902014-06-03 13:32:54 -07002125 struct audio_port_config backupConfig;
2126 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2127 if (status == NO_ERROR) {
2128 struct audio_port_config newConfig;
2129 audioPortConfig->toAudioPortConfig(&newConfig, config);
2130 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002131 }
Eric Laurenta121f902014-06-03 13:32:54 -07002132 if (status != NO_ERROR) {
2133 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002134 }
Eric Laurente1715a42014-05-20 11:30:42 -07002135
2136 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002137}
2138
2139void AudioPolicyManager::clearAudioPatches(uid_t uid)
2140{
2141 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2142 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2143 if (patchDesc->mUid == uid) {
2144 // releaseAudioPatch() removes the patch from mAudioPatches
2145 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2146 i--;
2147 }
2148 }
2149 }
2150}
2151
2152status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2153 const sp<AudioPatch>& patch)
2154{
2155 ssize_t index = mAudioPatches.indexOfKey(handle);
2156
2157 if (index >= 0) {
2158 ALOGW("addAudioPatch() patch %d already in", handle);
2159 return ALREADY_EXISTS;
2160 }
2161 mAudioPatches.add(handle, patch);
2162 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2163 "sink handle %d",
2164 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2165 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2166 return NO_ERROR;
2167}
2168
2169status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2170{
2171 ssize_t index = mAudioPatches.indexOfKey(handle);
2172
2173 if (index < 0) {
2174 ALOGW("removeAudioPatch() patch %d not in", handle);
2175 return ALREADY_EXISTS;
2176 }
2177 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2178 mAudioPatches.valueAt(index)->mAfPatchHandle);
2179 mAudioPatches.removeItemsAt(index);
2180 return NO_ERROR;
2181}
2182
Eric Laurente552edb2014-03-10 17:42:56 -07002183// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002184// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002185// ----------------------------------------------------------------------------
2186
Eric Laurent3a4311c2014-03-17 12:00:47 -07002187uint32_t AudioPolicyManager::nextUniqueId()
2188{
2189 return android_atomic_inc(&mNextUniqueId);
2190}
2191
Eric Laurent6a94d692014-05-20 11:18:06 -07002192uint32_t AudioPolicyManager::nextAudioPortGeneration()
2193{
2194 return android_atomic_inc(&mAudioPortGeneration);
2195}
2196
Eric Laurente0720872014-03-11 09:30:41 -07002197AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002198 :
2199#ifdef AUDIO_POLICY_TEST
2200 Thread(false),
2201#endif //AUDIO_POLICY_TEST
2202 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002203 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002204 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2205 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002206 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002207 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2208 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002209{
Eric Laurent6a94d692014-05-20 11:18:06 -07002210 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002211 mpClientInterface = clientInterface;
2212
Eric Laurent3b73df72014-03-11 09:06:29 -07002213 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2214 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002215 }
2216
Eric Laurent1afeecb2014-05-14 08:52:28 -07002217 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002218 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2219 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2220 ALOGE("could not load audio policy configuration file, setting defaults");
2221 defaultAudioPolicyConfig();
2222 }
2223 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002224 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002225
2226 // must be done after reading the policy
2227 initializeVolumeCurves();
2228
2229 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002230 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2231 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002232 for (size_t i = 0; i < mHwModules.size(); i++) {
2233 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2234 if (mHwModules[i]->mHandle == 0) {
2235 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2236 continue;
2237 }
2238 // open all output streams needed to access attached devices
2239 // except for direct output streams that are only opened when they are actually
2240 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002241 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002242 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2243 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002244 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Eric Laurent3a4311c2014-03-17 12:00:47 -07002246 if (outProfile->mSupportedDevices.isEmpty()) {
2247 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2248 continue;
2249 }
2250
2251 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2252 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002253 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002254 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002255
Eric Laurent1c333e22014-05-20 10:48:17 -07002256 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002257 audio_io_handle_t output = mpClientInterface->openOutput(
2258 outProfile->mModule->mHandle,
2259 &outputDesc->mDevice,
2260 &outputDesc->mSamplingRate,
2261 &outputDesc->mFormat,
2262 &outputDesc->mChannelMask,
2263 &outputDesc->mLatency,
2264 outputDesc->mFlags);
2265 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002266 ALOGW("Cannot open output stream for device %08x on hw module %s",
2267 outputDesc->mDevice,
2268 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002269 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002270 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002271 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002272 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002273 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002274 // give a valid ID to an attached device once confirmed it is reachable
2275 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2276 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002277 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002278 }
2279 }
Eric Laurente552edb2014-03-10 17:42:56 -07002280 if (mPrimaryOutput == 0 &&
2281 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2282 mPrimaryOutput = output;
2283 }
2284 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002285 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002286 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002287 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002288 true);
2289 }
2290 }
2291 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002292 // open input streams needed to access attached devices to validate
2293 // mAvailableInputDevices list
2294 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2295 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002296 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002297
Eric Laurent3a4311c2014-03-17 12:00:47 -07002298 if (inProfile->mSupportedDevices.isEmpty()) {
2299 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2300 continue;
2301 }
2302
2303 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2304 if (profileTypes & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002305 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002306
2307 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002308 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002309 audio_io_handle_t input = mpClientInterface->openInput(
2310 inProfile->mModule->mHandle,
2311 &inputDesc->mDevice,
2312 &inputDesc->mSamplingRate,
2313 &inputDesc->mFormat,
2314 &inputDesc->mChannelMask);
2315
2316 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002317 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002318 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002319 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002320 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002321 // give a valid ID to an attached device once confirmed it is reachable
2322 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2323 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002324 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002325 }
2326 }
2327 mpClientInterface->closeInput(input);
2328 } else {
2329 ALOGW("Cannot open input stream for device %08x on hw module %s",
2330 inputDesc->mDevice,
2331 mHwModules[i]->mName);
2332 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002333 }
2334 }
2335 }
2336 // make sure all attached devices have been allocated a unique ID
2337 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2338 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002339 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002340 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2341 continue;
2342 }
2343 i++;
2344 }
2345 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2346 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002347 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002348 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2349 continue;
2350 }
2351 i++;
2352 }
2353 // make sure default device is reachable
2354 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002355 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002356 }
Eric Laurente552edb2014-03-10 17:42:56 -07002357
2358 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2359
2360 updateDevicesAndOutputs();
2361
2362#ifdef AUDIO_POLICY_TEST
2363 if (mPrimaryOutput != 0) {
2364 AudioParameter outputCmd = AudioParameter();
2365 outputCmd.addInt(String8("set_id"), 0);
2366 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2367
2368 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2369 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002370 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2371 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002372 mTestLatencyMs = 0;
2373 mCurOutput = 0;
2374 mDirectOutput = false;
2375 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2376 mTestOutputs[i] = 0;
2377 }
2378
2379 const size_t SIZE = 256;
2380 char buffer[SIZE];
2381 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2382 run(buffer, ANDROID_PRIORITY_AUDIO);
2383 }
2384#endif //AUDIO_POLICY_TEST
2385}
2386
Eric Laurente0720872014-03-11 09:30:41 -07002387AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002388{
2389#ifdef AUDIO_POLICY_TEST
2390 exit();
2391#endif //AUDIO_POLICY_TEST
2392 for (size_t i = 0; i < mOutputs.size(); i++) {
2393 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002394 }
2395 for (size_t i = 0; i < mInputs.size(); i++) {
2396 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002397 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002398 mAvailableOutputDevices.clear();
2399 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002400 mOutputs.clear();
2401 mInputs.clear();
2402 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002403}
2404
Eric Laurente0720872014-03-11 09:30:41 -07002405status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002406{
2407 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2408}
2409
2410#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002411bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002412{
2413 ALOGV("entering threadLoop()");
2414 while (!exitPending())
2415 {
2416 String8 command;
2417 int valueInt;
2418 String8 value;
2419
2420 Mutex::Autolock _l(mLock);
2421 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2422
2423 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2424 AudioParameter param = AudioParameter(command);
2425
2426 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2427 valueInt != 0) {
2428 ALOGV("Test command %s received", command.string());
2429 String8 target;
2430 if (param.get(String8("target"), target) != NO_ERROR) {
2431 target = "Manager";
2432 }
2433 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2434 param.remove(String8("test_cmd_policy_output"));
2435 mCurOutput = valueInt;
2436 }
2437 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2438 param.remove(String8("test_cmd_policy_direct"));
2439 if (value == "false") {
2440 mDirectOutput = false;
2441 } else if (value == "true") {
2442 mDirectOutput = true;
2443 }
2444 }
2445 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2446 param.remove(String8("test_cmd_policy_input"));
2447 mTestInput = valueInt;
2448 }
2449
2450 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2451 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002452 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002453 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002454 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002455 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002456 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002457 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002458 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002459 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002460 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002461 if (target == "Manager") {
2462 mTestFormat = format;
2463 } else if (mTestOutputs[mCurOutput] != 0) {
2464 AudioParameter outputParam = AudioParameter();
2465 outputParam.addInt(String8("format"), format);
2466 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2467 }
2468 }
2469 }
2470 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2471 param.remove(String8("test_cmd_policy_channels"));
2472 int channels = 0;
2473
2474 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002475 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002476 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002477 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002478 }
2479 if (channels != 0) {
2480 if (target == "Manager") {
2481 mTestChannels = channels;
2482 } else if (mTestOutputs[mCurOutput] != 0) {
2483 AudioParameter outputParam = AudioParameter();
2484 outputParam.addInt(String8("channels"), channels);
2485 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2486 }
2487 }
2488 }
2489 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2490 param.remove(String8("test_cmd_policy_sampleRate"));
2491 if (valueInt >= 0 && valueInt <= 96000) {
2492 int samplingRate = valueInt;
2493 if (target == "Manager") {
2494 mTestSamplingRate = samplingRate;
2495 } else if (mTestOutputs[mCurOutput] != 0) {
2496 AudioParameter outputParam = AudioParameter();
2497 outputParam.addInt(String8("sampling_rate"), samplingRate);
2498 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2499 }
2500 }
2501 }
2502
2503 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2504 param.remove(String8("test_cmd_policy_reopen"));
2505
Eric Laurent1f2f2232014-06-02 12:01:23 -07002506 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002507 mpClientInterface->closeOutput(mPrimaryOutput);
2508
2509 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2510
Eric Laurente552edb2014-03-10 17:42:56 -07002511 mOutputs.removeItem(mPrimaryOutput);
2512
Eric Laurent1f2f2232014-06-02 12:01:23 -07002513 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002514 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2515 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2516 &outputDesc->mDevice,
2517 &outputDesc->mSamplingRate,
2518 &outputDesc->mFormat,
2519 &outputDesc->mChannelMask,
2520 &outputDesc->mLatency,
2521 outputDesc->mFlags);
2522 if (mPrimaryOutput == 0) {
2523 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2524 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2525 } else {
2526 AudioParameter outputCmd = AudioParameter();
2527 outputCmd.addInt(String8("set_id"), 0);
2528 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2529 addOutput(mPrimaryOutput, outputDesc);
2530 }
2531 }
2532
2533
2534 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2535 }
2536 }
2537 return false;
2538}
2539
Eric Laurente0720872014-03-11 09:30:41 -07002540void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002541{
2542 {
2543 AutoMutex _l(mLock);
2544 requestExit();
2545 mWaitWorkCV.signal();
2546 }
2547 requestExitAndWait();
2548}
2549
Eric Laurente0720872014-03-11 09:30:41 -07002550int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002551{
2552 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2553 if (output == mTestOutputs[i]) return i;
2554 }
2555 return 0;
2556}
2557#endif //AUDIO_POLICY_TEST
2558
2559// ---
2560
Eric Laurent1f2f2232014-06-02 12:01:23 -07002561void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002562{
Eric Laurent1c333e22014-05-20 10:48:17 -07002563 outputDesc->mIoHandle = output;
2564 outputDesc->mId = nextUniqueId();
2565 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002566 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002567}
2568
Eric Laurent1f2f2232014-06-02 12:01:23 -07002569void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002570{
Eric Laurent1c333e22014-05-20 10:48:17 -07002571 inputDesc->mIoHandle = input;
2572 inputDesc->mId = nextUniqueId();
2573 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002574 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002575}
Eric Laurente552edb2014-03-10 17:42:56 -07002576
Eric Laurent3a4311c2014-03-17 12:00:47 -07002577String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2578{
2579 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2580 return String8("a2dp_sink_address=")+address;
2581 }
2582 return address;
2583}
2584
Eric Laurente0720872014-03-11 09:30:41 -07002585status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002586 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002587 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002588 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002589{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002590 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002591
Eric Laurent3b73df72014-03-11 09:06:29 -07002592 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002593 // first list already open outputs that can be routed to this device
2594 for (size_t i = 0; i < mOutputs.size(); i++) {
2595 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002596 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002597 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2598 outputs.add(mOutputs.keyAt(i));
2599 }
2600 }
2601 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002602 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002603 for (size_t i = 0; i < mHwModules.size(); i++)
2604 {
2605 if (mHwModules[i]->mHandle == 0) {
2606 continue;
2607 }
2608 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2609 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002610 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002611 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002612 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2613 }
2614 }
2615 }
2616
2617 if (profiles.isEmpty() && outputs.isEmpty()) {
2618 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2619 return BAD_VALUE;
2620 }
2621
2622 // open outputs for matching profiles if needed. Direct outputs are also opened to
2623 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2624 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002625 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002626
2627 // nothing to do if one output is already opened for this profile
2628 size_t j;
2629 for (j = 0; j < mOutputs.size(); j++) {
2630 desc = mOutputs.valueAt(j);
2631 if (!desc->isDuplicated() && desc->mProfile == profile) {
2632 break;
2633 }
2634 }
2635 if (j != mOutputs.size()) {
2636 continue;
2637 }
2638
Eric Laurent3a4311c2014-03-17 12:00:47 -07002639 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002640 desc = new AudioOutputDescriptor(profile);
2641 desc->mDevice = device;
2642 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2643 offloadInfo.sample_rate = desc->mSamplingRate;
2644 offloadInfo.format = desc->mFormat;
2645 offloadInfo.channel_mask = desc->mChannelMask;
2646
2647 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2648 &desc->mDevice,
2649 &desc->mSamplingRate,
2650 &desc->mFormat,
2651 &desc->mChannelMask,
2652 &desc->mLatency,
2653 desc->mFlags,
2654 &offloadInfo);
2655 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002656 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002657 if (!address.isEmpty()) {
2658 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002659 }
2660
Eric Laurentd4692962014-05-05 18:13:44 -07002661 // Here is where we step through and resolve any "dynamic" fields
2662 String8 reply;
2663 char *value;
2664 if (profile->mSamplingRates[0] == 0) {
2665 reply = mpClientInterface->getParameters(output,
2666 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2667 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2668 reply.string());
2669 value = strpbrk((char *)reply.string(), "=");
2670 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002671 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002672 }
Eric Laurentd4692962014-05-05 18:13:44 -07002673 }
2674 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2675 reply = mpClientInterface->getParameters(output,
2676 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2677 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2678 reply.string());
2679 value = strpbrk((char *)reply.string(), "=");
2680 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002681 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002682 }
Eric Laurentd4692962014-05-05 18:13:44 -07002683 }
2684 if (profile->mChannelMasks[0] == 0) {
2685 reply = mpClientInterface->getParameters(output,
2686 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2687 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2688 reply.string());
2689 value = strpbrk((char *)reply.string(), "=");
2690 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002691 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002692 }
Eric Laurentd4692962014-05-05 18:13:44 -07002693 }
2694 if (((profile->mSamplingRates[0] == 0) &&
2695 (profile->mSamplingRates.size() < 2)) ||
2696 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2697 (profile->mFormats.size() < 2)) ||
2698 ((profile->mChannelMasks[0] == 0) &&
2699 (profile->mChannelMasks.size() < 2))) {
2700 ALOGW("checkOutputsForDevice() direct output missing param");
2701 mpClientInterface->closeOutput(output);
2702 output = 0;
2703 } else if (profile->mSamplingRates[0] == 0) {
2704 mpClientInterface->closeOutput(output);
2705 desc->mSamplingRate = profile->mSamplingRates[1];
2706 offloadInfo.sample_rate = desc->mSamplingRate;
2707 output = mpClientInterface->openOutput(
2708 profile->mModule->mHandle,
2709 &desc->mDevice,
2710 &desc->mSamplingRate,
2711 &desc->mFormat,
2712 &desc->mChannelMask,
2713 &desc->mLatency,
2714 desc->mFlags,
2715 &offloadInfo);
2716 }
2717
2718 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002719 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002720 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2721 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002722
Eric Laurentd4692962014-05-05 18:13:44 -07002723 // set initial stream volume for device
2724 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002725
Eric Laurentd4692962014-05-05 18:13:44 -07002726 //TODO: configure audio effect output stage here
2727
2728 // open a duplicating output thread for the new output and the primary output
2729 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2730 mPrimaryOutput);
2731 if (duplicatedOutput != 0) {
2732 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002733 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002734 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2735 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2736 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2737 dupOutputDesc->mFormat = desc->mFormat;
2738 dupOutputDesc->mChannelMask = desc->mChannelMask;
2739 dupOutputDesc->mLatency = desc->mLatency;
2740 addOutput(duplicatedOutput, dupOutputDesc);
2741 applyStreamVolumes(duplicatedOutput, device, 0, true);
2742 } else {
2743 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2744 mPrimaryOutput, output);
2745 mpClientInterface->closeOutput(output);
2746 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002747 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002748 output = 0;
2749 }
Eric Laurente552edb2014-03-10 17:42:56 -07002750 }
2751 }
2752 }
2753 if (output == 0) {
2754 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002755 profiles.removeAt(profile_index);
2756 profile_index--;
2757 } else {
2758 outputs.add(output);
2759 ALOGV("checkOutputsForDevice(): adding output %d", output);
2760 }
2761 }
2762
2763 if (profiles.isEmpty()) {
2764 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2765 return BAD_VALUE;
2766 }
Eric Laurentd4692962014-05-05 18:13:44 -07002767 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002768 // check if one opened output is not needed any more after disconnecting one device
2769 for (size_t i = 0; i < mOutputs.size(); i++) {
2770 desc = mOutputs.valueAt(i);
2771 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002772 !(desc->mProfile->mSupportedDevices.types() &
2773 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002774 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2775 outputs.add(mOutputs.keyAt(i));
2776 }
2777 }
Eric Laurentd4692962014-05-05 18:13:44 -07002778 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002779 for (size_t i = 0; i < mHwModules.size(); i++)
2780 {
2781 if (mHwModules[i]->mHandle == 0) {
2782 continue;
2783 }
2784 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2785 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002786 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002787 if (profile->mSupportedDevices.types() & device) {
2788 ALOGV("checkOutputsForDevice(): "
2789 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002790 if (profile->mSamplingRates[0] == 0) {
2791 profile->mSamplingRates.clear();
2792 profile->mSamplingRates.add(0);
2793 }
2794 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2795 profile->mFormats.clear();
2796 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2797 }
2798 if (profile->mChannelMasks[0] == 0) {
2799 profile->mChannelMasks.clear();
2800 profile->mChannelMasks.add(0);
2801 }
2802 }
2803 }
2804 }
2805 }
2806 return NO_ERROR;
2807}
2808
Eric Laurentd4692962014-05-05 18:13:44 -07002809status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2810 audio_policy_dev_state_t state,
2811 SortedVector<audio_io_handle_t>& inputs,
2812 const String8 address)
2813{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002814 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002815 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2816 // first list already open inputs that can be routed to this device
2817 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2818 desc = mInputs.valueAt(input_index);
2819 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2820 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2821 inputs.add(mInputs.keyAt(input_index));
2822 }
2823 }
2824
2825 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002826 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002827 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2828 {
2829 if (mHwModules[module_idx]->mHandle == 0) {
2830 continue;
2831 }
2832 for (size_t profile_index = 0;
2833 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2834 profile_index++)
2835 {
2836 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2837 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002838 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002839 profile_index, module_idx);
2840 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2841 }
2842 }
2843 }
2844
2845 if (profiles.isEmpty() && inputs.isEmpty()) {
2846 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2847 return BAD_VALUE;
2848 }
2849
2850 // open inputs for matching profiles if needed. Direct inputs are also opened to
2851 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2852 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2853
Eric Laurent1c333e22014-05-20 10:48:17 -07002854 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002855 // nothing to do if one input is already opened for this profile
2856 size_t input_index;
2857 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2858 desc = mInputs.valueAt(input_index);
2859 if (desc->mProfile == profile) {
2860 break;
2861 }
2862 }
2863 if (input_index != mInputs.size()) {
2864 continue;
2865 }
2866
2867 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2868 desc = new AudioInputDescriptor(profile);
2869 desc->mDevice = device;
2870
2871 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2872 &desc->mDevice,
2873 &desc->mSamplingRate,
2874 &desc->mFormat,
2875 &desc->mChannelMask);
2876
2877 if (input != 0) {
2878 if (!address.isEmpty()) {
2879 mpClientInterface->setParameters(input, addressToParameter(device, address));
2880 }
2881
2882 // Here is where we step through and resolve any "dynamic" fields
2883 String8 reply;
2884 char *value;
2885 if (profile->mSamplingRates[0] == 0) {
2886 reply = mpClientInterface->getParameters(input,
2887 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2888 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2889 reply.string());
2890 value = strpbrk((char *)reply.string(), "=");
2891 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002892 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002893 }
2894 }
2895 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2896 reply = mpClientInterface->getParameters(input,
2897 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2898 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2899 value = strpbrk((char *)reply.string(), "=");
2900 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002901 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002902 }
2903 }
2904 if (profile->mChannelMasks[0] == 0) {
2905 reply = mpClientInterface->getParameters(input,
2906 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2907 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2908 reply.string());
2909 value = strpbrk((char *)reply.string(), "=");
2910 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002911 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002912 }
2913 }
2914 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2915 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2916 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2917 ALOGW("checkInputsForDevice() direct input missing param");
2918 mpClientInterface->closeInput(input);
2919 input = 0;
2920 }
2921
2922 if (input != 0) {
2923 addInput(input, desc);
2924 }
2925 } // endif input != 0
2926
2927 if (input == 0) {
2928 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07002929 profiles.removeAt(profile_index);
2930 profile_index--;
2931 } else {
2932 inputs.add(input);
2933 ALOGV("checkInputsForDevice(): adding input %d", input);
2934 }
2935 } // end scan profiles
2936
2937 if (profiles.isEmpty()) {
2938 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2939 return BAD_VALUE;
2940 }
2941 } else {
2942 // Disconnect
2943 // check if one opened input is not needed any more after disconnecting one device
2944 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2945 desc = mInputs.valueAt(input_index);
2946 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2947 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2948 mInputs.keyAt(input_index));
2949 inputs.add(mInputs.keyAt(input_index));
2950 }
2951 }
2952 // Clear any profiles associated with the disconnected device.
2953 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2954 if (mHwModules[module_index]->mHandle == 0) {
2955 continue;
2956 }
2957 for (size_t profile_index = 0;
2958 profile_index < mHwModules[module_index]->mInputProfiles.size();
2959 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002960 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002961 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002962 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002963 profile_index, module_index);
2964 if (profile->mSamplingRates[0] == 0) {
2965 profile->mSamplingRates.clear();
2966 profile->mSamplingRates.add(0);
2967 }
2968 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2969 profile->mFormats.clear();
2970 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2971 }
2972 if (profile->mChannelMasks[0] == 0) {
2973 profile->mChannelMasks.clear();
2974 profile->mChannelMasks.add(0);
2975 }
2976 }
2977 }
2978 }
2979 } // end disconnect
2980
2981 return NO_ERROR;
2982}
2983
2984
Eric Laurente0720872014-03-11 09:30:41 -07002985void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002986{
2987 ALOGV("closeOutput(%d)", output);
2988
Eric Laurent1f2f2232014-06-02 12:01:23 -07002989 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07002990 if (outputDesc == NULL) {
2991 ALOGW("closeOutput() unknown output %d", output);
2992 return;
2993 }
2994
2995 // look for duplicated outputs connected to the output being removed.
2996 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002997 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002998 if (dupOutputDesc->isDuplicated() &&
2999 (dupOutputDesc->mOutput1 == outputDesc ||
3000 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003001 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003002 if (dupOutputDesc->mOutput1 == outputDesc) {
3003 outputDesc2 = dupOutputDesc->mOutput2;
3004 } else {
3005 outputDesc2 = dupOutputDesc->mOutput1;
3006 }
3007 // As all active tracks on duplicated output will be deleted,
3008 // and as they were also referenced on the other output, the reference
3009 // count for their stream type must be adjusted accordingly on
3010 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003011 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003012 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003013 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003014 }
3015 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3016 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3017
3018 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003019 mOutputs.removeItem(duplicatedOutput);
3020 }
3021 }
3022
3023 AudioParameter param;
3024 param.add(String8("closing"), String8("true"));
3025 mpClientInterface->setParameters(output, param.toString());
3026
3027 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003028 mOutputs.removeItem(output);
3029 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003030 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003031}
3032
Eric Laurente0720872014-03-11 09:30:41 -07003033SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003034 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003035{
3036 SortedVector<audio_io_handle_t> outputs;
3037
3038 ALOGVV("getOutputsForDevice() device %04x", device);
3039 for (size_t i = 0; i < openOutputs.size(); i++) {
3040 ALOGVV("output %d isDuplicated=%d device=%04x",
3041 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3042 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3043 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3044 outputs.add(openOutputs.keyAt(i));
3045 }
3046 }
3047 return outputs;
3048}
3049
Eric Laurente0720872014-03-11 09:30:41 -07003050bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003051 SortedVector<audio_io_handle_t>& outputs2)
3052{
3053 if (outputs1.size() != outputs2.size()) {
3054 return false;
3055 }
3056 for (size_t i = 0; i < outputs1.size(); i++) {
3057 if (outputs1[i] != outputs2[i]) {
3058 return false;
3059 }
3060 }
3061 return true;
3062}
3063
Eric Laurente0720872014-03-11 09:30:41 -07003064void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003065{
3066 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3067 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3068 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3069 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3070
3071 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3072 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3073 strategy, srcOutputs[0], dstOutputs[0]);
3074 // mute strategy while moving tracks from one output to another
3075 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003076 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003077 if (desc->isStrategyActive(strategy)) {
3078 setStrategyMute(strategy, true, srcOutputs[i]);
3079 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3080 }
3081 }
3082
3083 // Move effects associated to this strategy from previous output to new output
3084 if (strategy == STRATEGY_MEDIA) {
3085 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3086 SortedVector<audio_io_handle_t> moved;
3087 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003088 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3089 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3090 effectDesc->mIo != fxOutput) {
3091 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003092 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3093 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003094 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003095 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003096 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003097 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003098 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003099 }
3100 }
3101 }
3102 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003103 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3104 if (getStrategy((audio_stream_type_t)i) == strategy) {
3105 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003106 }
3107 }
3108 }
3109}
3110
Eric Laurente0720872014-03-11 09:30:41 -07003111void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003112{
3113 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3114 checkOutputForStrategy(STRATEGY_PHONE);
3115 checkOutputForStrategy(STRATEGY_SONIFICATION);
3116 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3117 checkOutputForStrategy(STRATEGY_MEDIA);
3118 checkOutputForStrategy(STRATEGY_DTMF);
3119}
3120
Eric Laurente0720872014-03-11 09:30:41 -07003121audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003122{
Eric Laurente552edb2014-03-10 17:42:56 -07003123 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003124 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003125 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3126 return mOutputs.keyAt(i);
3127 }
3128 }
3129
3130 return 0;
3131}
3132
Eric Laurente0720872014-03-11 09:30:41 -07003133void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003134{
Eric Laurente552edb2014-03-10 17:42:56 -07003135 audio_io_handle_t a2dpOutput = getA2dpOutput();
3136 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003137 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003138 return;
3139 }
3140
Eric Laurent3a4311c2014-03-17 12:00:47 -07003141 bool isScoConnected =
3142 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003143 // suspend A2DP output if:
3144 // (NOT already suspended) &&
3145 // ((SCO device is connected &&
3146 // (forced usage for communication || for record is SCO))) ||
3147 // (phone state is ringing || in call)
3148 //
3149 // restore A2DP output if:
3150 // (Already suspended) &&
3151 // ((SCO device is NOT connected ||
3152 // (forced usage NOT for communication && NOT for record is SCO))) &&
3153 // (phone state is NOT ringing && NOT in call)
3154 //
3155 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003156 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003157 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3158 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3159 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3160 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003161
3162 mpClientInterface->restoreOutput(a2dpOutput);
3163 mA2dpSuspended = false;
3164 }
3165 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003166 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003167 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3168 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3169 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3170 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003171
3172 mpClientInterface->suspendOutput(a2dpOutput);
3173 mA2dpSuspended = true;
3174 }
3175 }
3176}
3177
Eric Laurent1c333e22014-05-20 10:48:17 -07003178audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003179{
3180 audio_devices_t device = AUDIO_DEVICE_NONE;
3181
Eric Laurent1f2f2232014-06-02 12:01:23 -07003182 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003183
3184 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3185 if (index >= 0) {
3186 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3187 if (patchDesc->mUid != mUidCached) {
3188 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3189 outputDesc->device(), outputDesc->mPatchHandle);
3190 return outputDesc->device();
3191 }
3192 }
3193
Eric Laurente552edb2014-03-10 17:42:56 -07003194 // check the following by order of priority to request a routing change if necessary:
3195 // 1: the strategy enforced audible is active on the output:
3196 // use device for strategy enforced audible
3197 // 2: we are in call or the strategy phone is active on the output:
3198 // use device for strategy phone
3199 // 3: the strategy sonification is active on the output:
3200 // use device for strategy sonification
3201 // 4: the strategy "respectful" sonification is active on the output:
3202 // use device for strategy "respectful" sonification
3203 // 5: the strategy media is active on the output:
3204 // use device for strategy media
3205 // 6: the strategy DTMF is active on the output:
3206 // use device for strategy DTMF
3207 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3208 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3209 } else if (isInCall() ||
3210 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3211 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3212 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3213 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3214 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3215 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3216 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3217 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3218 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3219 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3220 }
3221
Eric Laurent1c333e22014-05-20 10:48:17 -07003222 ALOGV("getNewOutputDevice() selected device %x", device);
3223 return device;
3224}
3225
3226audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3227{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003228 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003229
3230 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3231 if (index >= 0) {
3232 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3233 if (patchDesc->mUid != mUidCached) {
3234 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3235 inputDesc->mDevice, inputDesc->mPatchHandle);
3236 return inputDesc->mDevice;
3237 }
3238 }
3239
Eric Laurent1c333e22014-05-20 10:48:17 -07003240 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3241
3242 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003243 return device;
3244}
3245
Eric Laurente0720872014-03-11 09:30:41 -07003246uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003247 return (uint32_t)getStrategy(stream);
3248}
3249
Eric Laurente0720872014-03-11 09:30:41 -07003250audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003251 // By checking the range of stream before calling getStrategy, we avoid
3252 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3253 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003254 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003255 return AUDIO_DEVICE_NONE;
3256 }
3257 audio_devices_t devices;
3258 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3259 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3260 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3261 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003262 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003263 if (outputDesc->isStrategyActive(strategy)) {
3264 devices = outputDesc->device();
3265 break;
3266 }
Eric Laurente552edb2014-03-10 17:42:56 -07003267 }
3268 return devices;
3269}
3270
Eric Laurente0720872014-03-11 09:30:41 -07003271AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003272 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003273 // stream to strategy mapping
3274 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003275 case AUDIO_STREAM_VOICE_CALL:
3276 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003277 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003278 case AUDIO_STREAM_RING:
3279 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003280 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003281 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003282 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003283 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003284 return STRATEGY_DTMF;
3285 default:
3286 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003287 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003288 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3289 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003290 case AUDIO_STREAM_TTS:
3291 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003292 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003293 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003294 return STRATEGY_ENFORCED_AUDIBLE;
3295 }
3296}
3297
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003298uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3299 // flags to strategy mapping
3300 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3301 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3302 }
3303
3304 // usage to strategy mapping
3305 switch (attr->usage) {
3306 case AUDIO_USAGE_MEDIA:
3307 case AUDIO_USAGE_GAME:
3308 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3309 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3310 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3311 return (uint32_t) STRATEGY_MEDIA;
3312
3313 case AUDIO_USAGE_VOICE_COMMUNICATION:
3314 return (uint32_t) STRATEGY_PHONE;
3315
3316 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3317 return (uint32_t) STRATEGY_DTMF;
3318
3319 case AUDIO_USAGE_ALARM:
3320 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3321 return (uint32_t) STRATEGY_SONIFICATION;
3322
3323 case AUDIO_USAGE_NOTIFICATION:
3324 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3325 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3326 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3327 case AUDIO_USAGE_NOTIFICATION_EVENT:
3328 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3329
3330 case AUDIO_USAGE_UNKNOWN:
3331 default:
3332 return (uint32_t) STRATEGY_MEDIA;
3333 }
3334}
3335
Eric Laurente0720872014-03-11 09:30:41 -07003336void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003337 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003338 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003339 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3340 updateDevicesAndOutputs();
3341 break;
3342 default:
3343 break;
3344 }
3345}
3346
Eric Laurente0720872014-03-11 09:30:41 -07003347audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003348 bool fromCache)
3349{
3350 uint32_t device = AUDIO_DEVICE_NONE;
3351
3352 if (fromCache) {
3353 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3354 strategy, mDeviceForStrategy[strategy]);
3355 return mDeviceForStrategy[strategy];
3356 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003357 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003358 switch (strategy) {
3359
3360 case STRATEGY_SONIFICATION_RESPECTFUL:
3361 if (isInCall()) {
3362 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003363 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003364 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3365 // while media is playing on a remote device, use the the sonification behavior.
3366 // Note that we test this usecase before testing if media is playing because
3367 // the isStreamActive() method only informs about the activity of a stream, not
3368 // if it's for local playback. Note also that we use the same delay between both tests
3369 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003370 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003371 // while media is playing (or has recently played), use the same device
3372 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3373 } else {
3374 // when media is not playing anymore, fall back on the sonification behavior
3375 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3376 }
3377
3378 break;
3379
3380 case STRATEGY_DTMF:
3381 if (!isInCall()) {
3382 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3383 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3384 break;
3385 }
3386 // when in call, DTMF and PHONE strategies follow the same rules
3387 // FALL THROUGH
3388
3389 case STRATEGY_PHONE:
3390 // for phone strategy, we first consider the forced use and then the available devices by order
3391 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003392 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3393 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003394 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003395 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003396 if (device) break;
3397 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003398 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003399 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003400 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003401 if (device) break;
3402 // if SCO device is requested but no SCO device is available, fall back to default case
3403 // FALL THROUGH
3404
3405 default: // FORCE_NONE
3406 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003407 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003408 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003409 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003410 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003411 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003412 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003413 if (device) break;
3414 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003415 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003416 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003417 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003418 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003419 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003420 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003421 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003422 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003423 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003424 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003425 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003426 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003427 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003428 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003429 if (device) break;
3430 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003431 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003432 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003433 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003434 if (device == AUDIO_DEVICE_NONE) {
3435 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3436 }
3437 break;
3438
Eric Laurent3b73df72014-03-11 09:06:29 -07003439 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003440 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3441 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003442 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003443 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003444 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003445 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003446 if (device) break;
3447 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003448 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003449 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003450 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003451 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003452 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003453 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003454 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003455 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003456 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003457 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003458 if (device) break;
3459 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003460 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003461 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003462 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003463 if (device == AUDIO_DEVICE_NONE) {
3464 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3465 }
3466 break;
3467 }
3468 break;
3469
3470 case STRATEGY_SONIFICATION:
3471
3472 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3473 // handleIncallSonification().
3474 if (isInCall()) {
3475 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3476 break;
3477 }
3478 // FALL THROUGH
3479
3480 case STRATEGY_ENFORCED_AUDIBLE:
3481 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3482 // except:
3483 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3484 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3485
3486 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003487 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003488 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003489 if (device == AUDIO_DEVICE_NONE) {
3490 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3491 }
3492 }
3493 // The second device used for sonification is the same as the device used by media strategy
3494 // FALL THROUGH
3495
3496 case STRATEGY_MEDIA: {
3497 uint32_t device2 = AUDIO_DEVICE_NONE;
3498 if (strategy != STRATEGY_SONIFICATION) {
3499 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003500 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003501 }
3502 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003503 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003504 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003505 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003506 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003507 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003508 }
3509 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003510 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003511 }
3512 }
3513 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003514 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003515 }
3516 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003517 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
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_USB_ACCESSORY;
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_DEVICE;
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_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003527 }
3528 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3529 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003530 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003531 }
3532 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003533 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003534 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003535 }
3536 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003537 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003538 }
3539
3540 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3541 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3542 device |= device2;
3543 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003544 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003545 if (device == AUDIO_DEVICE_NONE) {
3546 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3547 }
3548 } break;
3549
3550 default:
3551 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3552 break;
3553 }
3554
3555 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3556 return device;
3557}
3558
Eric Laurente0720872014-03-11 09:30:41 -07003559void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003560{
3561 for (int i = 0; i < NUM_STRATEGIES; i++) {
3562 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3563 }
3564 mPreviousOutputs = mOutputs;
3565}
3566
Eric Laurent1f2f2232014-06-02 12:01:23 -07003567uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003568 audio_devices_t prevDevice,
3569 uint32_t delayMs)
3570{
3571 // mute/unmute strategies using an incompatible device combination
3572 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3573 // if unmuting, unmute only after the specified delay
3574 if (outputDesc->isDuplicated()) {
3575 return 0;
3576 }
3577
3578 uint32_t muteWaitMs = 0;
3579 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003580 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003581
3582 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3583 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3584 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3585 bool doMute = false;
3586
3587 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3588 doMute = true;
3589 outputDesc->mStrategyMutedByDevice[i] = true;
3590 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3591 doMute = true;
3592 outputDesc->mStrategyMutedByDevice[i] = false;
3593 }
Eric Laurent99401132014-05-07 19:48:15 -07003594 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003595 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003596 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003597 // skip output if it does not share any device with current output
3598 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3599 == AUDIO_DEVICE_NONE) {
3600 continue;
3601 }
3602 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3603 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3604 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3605 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3606 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003607 if (mute) {
3608 // FIXME: should not need to double latency if volume could be applied
3609 // immediately by the audioflinger mixer. We must account for the delay
3610 // between now and the next time the audioflinger thread for this output
3611 // will process a buffer (which corresponds to one buffer size,
3612 // usually 1/2 or 1/4 of the latency).
3613 if (muteWaitMs < desc->latency() * 2) {
3614 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003615 }
3616 }
3617 }
3618 }
3619 }
3620 }
3621
Eric Laurent99401132014-05-07 19:48:15 -07003622 // temporary mute output if device selection changes to avoid volume bursts due to
3623 // different per device volumes
3624 if (outputDesc->isActive() && (device != prevDevice)) {
3625 if (muteWaitMs < outputDesc->latency() * 2) {
3626 muteWaitMs = outputDesc->latency() * 2;
3627 }
3628 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3629 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003630 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003631 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003632 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003633 muteWaitMs *2, device);
3634 }
3635 }
3636 }
3637
Eric Laurente552edb2014-03-10 17:42:56 -07003638 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3639 if (muteWaitMs > delayMs) {
3640 muteWaitMs -= delayMs;
3641 usleep(muteWaitMs * 1000);
3642 return muteWaitMs;
3643 }
3644 return 0;
3645}
3646
Eric Laurente0720872014-03-11 09:30:41 -07003647uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003648 audio_devices_t device,
3649 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003650 int delayMs,
3651 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003652{
3653 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003654 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003655 AudioParameter param;
3656 uint32_t muteWaitMs;
3657
3658 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003659 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3660 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003661 return muteWaitMs;
3662 }
3663 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3664 // output profile
3665 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003666 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003667 return 0;
3668 }
3669
3670 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003671 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003672
3673 audio_devices_t prevDevice = outputDesc->mDevice;
3674
3675 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3676
3677 if (device != AUDIO_DEVICE_NONE) {
3678 outputDesc->mDevice = device;
3679 }
3680 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3681
3682 // Do not change the routing if:
3683 // - the requested device is AUDIO_DEVICE_NONE
3684 // - the requested device is the same as current device and force is not specified.
3685 // Doing this check here allows the caller to call setOutputDevice() without conditions
3686 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3687 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3688 return muteWaitMs;
3689 }
3690
3691 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003692
Eric Laurente552edb2014-03-10 17:42:56 -07003693 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003694 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003695 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003696 } else {
3697 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3698 if (!deviceList.isEmpty()) {
3699 struct audio_patch patch;
3700 outputDesc->toAudioPortConfig(&patch.sources[0]);
3701 patch.num_sources = 1;
3702 patch.num_sinks = 0;
3703 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3704 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003705 patch.num_sinks++;
3706 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003707 ssize_t index;
3708 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3709 index = mAudioPatches.indexOfKey(*patchHandle);
3710 } else {
3711 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3712 }
3713 sp< AudioPatch> patchDesc;
3714 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3715 if (index >= 0) {
3716 patchDesc = mAudioPatches.valueAt(index);
3717 afPatchHandle = patchDesc->mAfPatchHandle;
3718 }
3719
Eric Laurent1c333e22014-05-20 10:48:17 -07003720 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003721 &afPatchHandle,
3722 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003723 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3724 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003725 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003726 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003727 if (index < 0) {
3728 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3729 &patch, mUidCached);
3730 addAudioPatch(patchDesc->mHandle, patchDesc);
3731 } else {
3732 patchDesc->mPatch = patch;
3733 }
3734 patchDesc->mAfPatchHandle = afPatchHandle;
3735 patchDesc->mUid = mUidCached;
3736 if (patchHandle) {
3737 *patchHandle = patchDesc->mHandle;
3738 }
3739 outputDesc->mPatchHandle = patchDesc->mHandle;
3740 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003741 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003742 }
3743 }
3744 }
Eric Laurente552edb2014-03-10 17:42:56 -07003745
3746 // update stream volumes according to new device
3747 applyStreamVolumes(output, device, delayMs);
3748
3749 return muteWaitMs;
3750}
3751
Eric Laurent1c333e22014-05-20 10:48:17 -07003752status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003753 int delayMs,
3754 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003755{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003756 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003757 ssize_t index;
3758 if (patchHandle) {
3759 index = mAudioPatches.indexOfKey(*patchHandle);
3760 } else {
3761 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3762 }
3763 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 return INVALID_OPERATION;
3765 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003766 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3767 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003768 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3769 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003770 removeAudioPatch(patchDesc->mHandle);
3771 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003772 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003773 return status;
3774}
3775
3776status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3777 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003778 bool force,
3779 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003780{
3781 status_t status = NO_ERROR;
3782
Eric Laurent1f2f2232014-06-02 12:01:23 -07003783 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003784 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3785 inputDesc->mDevice = device;
3786
3787 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3788 if (!deviceList.isEmpty()) {
3789 struct audio_patch patch;
3790 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3791 patch.num_sinks = 1;
3792 //only one input device for now
3793 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003794 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003795 ssize_t index;
3796 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3797 index = mAudioPatches.indexOfKey(*patchHandle);
3798 } else {
3799 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3800 }
3801 sp< AudioPatch> patchDesc;
3802 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3803 if (index >= 0) {
3804 patchDesc = mAudioPatches.valueAt(index);
3805 afPatchHandle = patchDesc->mAfPatchHandle;
3806 }
3807
Eric Laurent1c333e22014-05-20 10:48:17 -07003808 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003809 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003810 0);
3811 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003812 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003813 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003814 if (index < 0) {
3815 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3816 &patch, mUidCached);
3817 addAudioPatch(patchDesc->mHandle, patchDesc);
3818 } else {
3819 patchDesc->mPatch = patch;
3820 }
3821 patchDesc->mAfPatchHandle = afPatchHandle;
3822 patchDesc->mUid = mUidCached;
3823 if (patchHandle) {
3824 *patchHandle = patchDesc->mHandle;
3825 }
3826 inputDesc->mPatchHandle = patchDesc->mHandle;
3827 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003828 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003829 }
3830 }
3831 }
3832 return status;
3833}
3834
Eric Laurent6a94d692014-05-20 11:18:06 -07003835status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3836 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003837{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003838 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003839 ssize_t index;
3840 if (patchHandle) {
3841 index = mAudioPatches.indexOfKey(*patchHandle);
3842 } else {
3843 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3844 }
3845 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003846 return INVALID_OPERATION;
3847 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003848 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3849 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003850 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3851 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003852 removeAudioPatch(patchDesc->mHandle);
3853 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003854 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003855 return status;
3856}
3857
3858sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003859 uint32_t samplingRate,
3860 audio_format_t format,
3861 audio_channel_mask_t channelMask)
3862{
3863 // Choose an input profile based on the requested capture parameters: select the first available
3864 // profile supporting all requested parameters.
3865
3866 for (size_t i = 0; i < mHwModules.size(); i++)
3867 {
3868 if (mHwModules[i]->mHandle == 0) {
3869 continue;
3870 }
3871 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3872 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003873 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003874 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003875 if (profile->isCompatibleProfile(device, samplingRate, format,
3876 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3877 return profile;
3878 }
3879 }
3880 }
3881 return NULL;
3882}
3883
Eric Laurente0720872014-03-11 09:30:41 -07003884audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003885{
3886 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003887 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3888 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003889 switch (inputSource) {
3890 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003891 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003892 device = AUDIO_DEVICE_IN_VOICE_CALL;
3893 break;
3894 }
3895 // FALL THROUGH
3896
3897 case AUDIO_SOURCE_DEFAULT:
3898 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003899 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3900 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3901 break;
3902 }
3903 // FALL THROUGH
3904
Eric Laurente552edb2014-03-10 17:42:56 -07003905 case AUDIO_SOURCE_VOICE_RECOGNITION:
3906 case AUDIO_SOURCE_HOTWORD:
3907 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003908 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003909 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003910 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003911 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003912 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003913 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3914 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003915 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003916 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3917 }
3918 break;
3919 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003920 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003921 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003922 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003923 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3924 }
3925 break;
3926 case AUDIO_SOURCE_VOICE_DOWNLINK:
3927 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003928 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003929 device = AUDIO_DEVICE_IN_VOICE_CALL;
3930 }
3931 break;
3932 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003933 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003934 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3935 }
3936 break;
3937 default:
3938 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3939 break;
3940 }
3941 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3942 return device;
3943}
3944
Eric Laurente0720872014-03-11 09:30:41 -07003945bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003946{
3947 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3948 device &= ~AUDIO_DEVICE_BIT_IN;
3949 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3950 return true;
3951 }
3952 return false;
3953}
3954
Eric Laurente0720872014-03-11 09:30:41 -07003955audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003956{
3957 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003958 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003959 if ((input_descriptor->mRefCount > 0)
3960 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3961 return mInputs.keyAt(i);
3962 }
3963 }
3964 return 0;
3965}
3966
3967
Eric Laurente0720872014-03-11 09:30:41 -07003968audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003969{
3970 if (device == AUDIO_DEVICE_NONE) {
3971 // this happens when forcing a route update and no track is active on an output.
3972 // In this case the returned category is not important.
3973 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003974 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003975 // Multiple device selection is either:
3976 // - speaker + one other device: give priority to speaker in this case.
3977 // - one A2DP device + another device: happens with duplicated output. In this case
3978 // retain the device on the A2DP output as the other must not correspond to an active
3979 // selection if not the speaker.
3980 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3981 device = AUDIO_DEVICE_OUT_SPEAKER;
3982 } else {
3983 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3984 }
3985 }
3986
Eric Laurent3b73df72014-03-11 09:06:29 -07003987 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003988 "getDeviceForVolume() invalid device combination: %08x",
3989 device);
3990
3991 return device;
3992}
3993
Eric Laurente0720872014-03-11 09:30:41 -07003994AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003995{
3996 switch(getDeviceForVolume(device)) {
3997 case AUDIO_DEVICE_OUT_EARPIECE:
3998 return DEVICE_CATEGORY_EARPIECE;
3999 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4000 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4001 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4002 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4003 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4004 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4005 return DEVICE_CATEGORY_HEADSET;
4006 case AUDIO_DEVICE_OUT_SPEAKER:
4007 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4008 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4009 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4010 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4011 case AUDIO_DEVICE_OUT_USB_DEVICE:
4012 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4013 default:
4014 return DEVICE_CATEGORY_SPEAKER;
4015 }
4016}
4017
Eric Laurente0720872014-03-11 09:30:41 -07004018float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004019 int indexInUi)
4020{
4021 device_category deviceCategory = getDeviceCategory(device);
4022 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4023
4024 // the volume index in the UI is relative to the min and max volume indices for this stream type
4025 int nbSteps = 1 + curve[VOLMAX].mIndex -
4026 curve[VOLMIN].mIndex;
4027 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4028 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4029
4030 // find what part of the curve this index volume belongs to, or if it's out of bounds
4031 int segment = 0;
4032 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4033 return 0.0f;
4034 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4035 segment = 0;
4036 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4037 segment = 1;
4038 } else if (volIdx <= curve[VOLMAX].mIndex) {
4039 segment = 2;
4040 } else { // out of bounds
4041 return 1.0f;
4042 }
4043
4044 // linear interpolation in the attenuation table in dB
4045 float decibels = curve[segment].mDBAttenuation +
4046 ((float)(volIdx - curve[segment].mIndex)) *
4047 ( (curve[segment+1].mDBAttenuation -
4048 curve[segment].mDBAttenuation) /
4049 ((float)(curve[segment+1].mIndex -
4050 curve[segment].mIndex)) );
4051
4052 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4053
4054 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4055 curve[segment].mIndex, volIdx,
4056 curve[segment+1].mIndex,
4057 curve[segment].mDBAttenuation,
4058 decibels,
4059 curve[segment+1].mDBAttenuation,
4060 amplification);
4061
4062 return amplification;
4063}
4064
Eric Laurente0720872014-03-11 09:30:41 -07004065const AudioPolicyManager::VolumeCurvePoint
4066 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004067 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4068};
4069
Eric Laurente0720872014-03-11 09:30:41 -07004070const AudioPolicyManager::VolumeCurvePoint
4071 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004072 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4073};
4074
Eric Laurente0720872014-03-11 09:30:41 -07004075const AudioPolicyManager::VolumeCurvePoint
4076 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004077 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4078};
4079
Eric Laurente0720872014-03-11 09:30:41 -07004080const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004081 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
4082 {1, -56.0f}, {20, -34.0f}, {86, -10.0f}, {100, 0.0f}
4083};
4084
4085const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004086 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004087 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4088};
4089
Eric Laurente0720872014-03-11 09:30:41 -07004090const AudioPolicyManager::VolumeCurvePoint
4091 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004092 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4093};
4094
4095// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4096// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4097// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4098// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4099
Eric Laurente0720872014-03-11 09:30:41 -07004100const AudioPolicyManager::VolumeCurvePoint
4101 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004102 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4103};
4104
Eric Laurente0720872014-03-11 09:30:41 -07004105const AudioPolicyManager::VolumeCurvePoint
4106 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004107 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4108};
4109
Eric Laurente0720872014-03-11 09:30:41 -07004110const AudioPolicyManager::VolumeCurvePoint
4111 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004112 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4113};
4114
Eric Laurente0720872014-03-11 09:30:41 -07004115const AudioPolicyManager::VolumeCurvePoint
4116 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004117 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4118};
4119
Eric Laurente0720872014-03-11 09:30:41 -07004120const AudioPolicyManager::VolumeCurvePoint
4121 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004122 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4123};
4124
Eric Laurente0720872014-03-11 09:30:41 -07004125const AudioPolicyManager::VolumeCurvePoint
4126 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4127 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004128 { // AUDIO_STREAM_VOICE_CALL
4129 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4130 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4131 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4132 },
4133 { // AUDIO_STREAM_SYSTEM
4134 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4135 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4136 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4137 },
4138 { // AUDIO_STREAM_RING
4139 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4140 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4141 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4142 },
4143 { // AUDIO_STREAM_MUSIC
4144 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4145 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4146 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4147 },
4148 { // AUDIO_STREAM_ALARM
4149 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4150 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4151 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4152 },
4153 { // AUDIO_STREAM_NOTIFICATION
4154 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4155 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4156 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4157 },
4158 { // AUDIO_STREAM_BLUETOOTH_SCO
4159 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4160 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4161 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4162 },
4163 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4164 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4165 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4166 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4167 },
4168 { // AUDIO_STREAM_DTMF
4169 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4170 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4171 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4172 },
4173 { // AUDIO_STREAM_TTS
4174 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4175 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4176 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4177 },
4178};
4179
Eric Laurente0720872014-03-11 09:30:41 -07004180void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004181{
4182 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4183 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4184 mStreams[i].mVolumeCurve[j] =
4185 sVolumeProfiles[i][j];
4186 }
4187 }
4188
4189 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4190 if (mSpeakerDrcEnabled) {
4191 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4192 sDefaultSystemVolumeCurveDrc;
4193 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4194 sSpeakerSonificationVolumeCurveDrc;
4195 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4196 sSpeakerSonificationVolumeCurveDrc;
4197 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4198 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004199 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4200 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004201 }
4202}
4203
Eric Laurente0720872014-03-11 09:30:41 -07004204float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004205 int index,
4206 audio_io_handle_t output,
4207 audio_devices_t device)
4208{
4209 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004210 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004211 StreamDescriptor &streamDesc = mStreams[stream];
4212
4213 if (device == AUDIO_DEVICE_NONE) {
4214 device = outputDesc->device();
4215 }
4216
4217 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004218 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004219 index != mStreams[stream].mIndexMin &&
4220 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
4221 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
4222 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
4223 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
4224 return 1.0;
4225 }
4226
4227 volume = volIndexToAmpl(device, streamDesc, index);
4228
4229 // if a headset is connected, apply the following rules to ring tones and notifications
4230 // to avoid sound level bursts in user's ears:
4231 // - always attenuate ring tones and notifications volume by 6dB
4232 // - if music is playing, always limit the volume to current music volume,
4233 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004234 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004235 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4236 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4237 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4238 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4239 ((stream_strategy == STRATEGY_SONIFICATION)
4240 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004241 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004242 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004243 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004244 streamDesc.mCanBeMuted) {
4245 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4246 // when the phone is ringing we must consider that music could have been paused just before
4247 // by the music application and behave as if music was active if the last music track was
4248 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004249 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004250 mLimitRingtoneVolume) {
4251 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004252 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4253 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004254 output,
4255 musicDevice);
4256 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4257 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4258 if (volume > minVol) {
4259 volume = minVol;
4260 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4261 }
4262 }
4263 }
4264
4265 return volume;
4266}
4267
Eric Laurente0720872014-03-11 09:30:41 -07004268status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004269 int index,
4270 audio_io_handle_t output,
4271 audio_devices_t device,
4272 int delayMs,
4273 bool force)
4274{
4275
4276 // do not change actual stream volume if the stream is muted
4277 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4278 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4279 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4280 return NO_ERROR;
4281 }
4282
4283 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004284 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4285 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4286 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4287 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004288 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004289 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004290 return INVALID_OPERATION;
4291 }
4292
4293 float volume = computeVolume(stream, index, output, device);
4294 // We actually change the volume if:
4295 // - the float value returned by computeVolume() changed
4296 // - the force flag is set
4297 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4298 force) {
4299 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4300 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4301 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4302 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004303 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4304 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004305 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004306 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004307 }
4308
Eric Laurent3b73df72014-03-11 09:06:29 -07004309 if (stream == AUDIO_STREAM_VOICE_CALL ||
4310 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004311 float voiceVolume;
4312 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004313 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004314 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4315 } else {
4316 voiceVolume = 1.0;
4317 }
4318
4319 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4320 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4321 mLastVoiceVolume = voiceVolume;
4322 }
4323 }
4324
4325 return NO_ERROR;
4326}
4327
Eric Laurente0720872014-03-11 09:30:41 -07004328void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004329 audio_devices_t device,
4330 int delayMs,
4331 bool force)
4332{
4333 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4334
Eric Laurent3b73df72014-03-11 09:06:29 -07004335 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4336 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004337 mStreams[stream].getVolumeIndex(device),
4338 output,
4339 device,
4340 delayMs,
4341 force);
4342 }
4343}
4344
Eric Laurente0720872014-03-11 09:30:41 -07004345void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004346 bool on,
4347 audio_io_handle_t output,
4348 int delayMs,
4349 audio_devices_t device)
4350{
4351 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004352 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4353 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4354 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004355 }
4356 }
4357}
4358
Eric Laurente0720872014-03-11 09:30:41 -07004359void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004360 bool on,
4361 audio_io_handle_t output,
4362 int delayMs,
4363 audio_devices_t device)
4364{
4365 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004366 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004367 if (device == AUDIO_DEVICE_NONE) {
4368 device = outputDesc->device();
4369 }
4370
4371 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4372 stream, on, output, outputDesc->mMuteCount[stream], device);
4373
4374 if (on) {
4375 if (outputDesc->mMuteCount[stream] == 0) {
4376 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004377 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4378 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004379 checkAndSetVolume(stream, 0, output, device, delayMs);
4380 }
4381 }
4382 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4383 outputDesc->mMuteCount[stream]++;
4384 } else {
4385 if (outputDesc->mMuteCount[stream] == 0) {
4386 ALOGV("setStreamMute() unmuting non muted stream!");
4387 return;
4388 }
4389 if (--outputDesc->mMuteCount[stream] == 0) {
4390 checkAndSetVolume(stream,
4391 streamDesc.getVolumeIndex(device),
4392 output,
4393 device,
4394 delayMs);
4395 }
4396 }
4397}
4398
Eric Laurente0720872014-03-11 09:30:41 -07004399void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004400 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004401{
4402 // if the stream pertains to sonification strategy and we are in call we must
4403 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4404 // in the device used for phone strategy and play the tone if the selected device does not
4405 // interfere with the device used for phone strategy
4406 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4407 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004408 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004409 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4410 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004411 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004412 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4413 stream, starting, outputDesc->mDevice, stateChange);
4414 if (outputDesc->mRefCount[stream]) {
4415 int muteCount = 1;
4416 if (stateChange) {
4417 muteCount = outputDesc->mRefCount[stream];
4418 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004419 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004420 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4421 for (int i = 0; i < muteCount; i++) {
4422 setStreamMute(stream, starting, mPrimaryOutput);
4423 }
4424 } else {
4425 ALOGV("handleIncallSonification() high visibility");
4426 if (outputDesc->device() &
4427 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4428 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4429 for (int i = 0; i < muteCount; i++) {
4430 setStreamMute(stream, starting, mPrimaryOutput);
4431 }
4432 }
4433 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004434 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4435 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004436 } else {
4437 mpClientInterface->stopTone();
4438 }
4439 }
4440 }
4441 }
4442}
4443
Eric Laurente0720872014-03-11 09:30:41 -07004444bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004445{
4446 return isStateInCall(mPhoneState);
4447}
4448
Eric Laurente0720872014-03-11 09:30:41 -07004449bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004450 return ((state == AUDIO_MODE_IN_CALL) ||
4451 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004452}
4453
Eric Laurente0720872014-03-11 09:30:41 -07004454uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004455{
4456 return MAX_EFFECTS_CPU_LOAD;
4457}
4458
Eric Laurente0720872014-03-11 09:30:41 -07004459uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004460{
4461 return MAX_EFFECTS_MEMORY;
4462}
4463
Eric Laurent6a94d692014-05-20 11:18:06 -07004464
Eric Laurente552edb2014-03-10 17:42:56 -07004465// --- AudioOutputDescriptor class implementation
4466
Eric Laurente0720872014-03-11 09:30:41 -07004467AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004468 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004469 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004470 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004471 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4472{
4473 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004474 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004475 mRefCount[i] = 0;
4476 mCurVolume[i] = -1.0;
4477 mMuteCount[i] = 0;
4478 mStopTime[i] = 0;
4479 }
4480 for (int i = 0; i < NUM_STRATEGIES; i++) {
4481 mStrategyMutedByDevice[i] = false;
4482 }
4483 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004484 mAudioPort = profile;
Eric Laurente552edb2014-03-10 17:42:56 -07004485 mSamplingRate = profile->mSamplingRates[0];
4486 mFormat = profile->mFormats[0];
4487 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004488 if (profile->mGains.size() > 0) {
4489 profile->mGains[0]->getDefaultConfig(&mGain);
4490 }
Eric Laurente552edb2014-03-10 17:42:56 -07004491 mFlags = profile->mFlags;
4492 }
4493}
4494
Eric Laurente0720872014-03-11 09:30:41 -07004495audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004496{
4497 if (isDuplicated()) {
4498 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4499 } else {
4500 return mDevice;
4501 }
4502}
4503
Eric Laurente0720872014-03-11 09:30:41 -07004504uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004505{
4506 if (isDuplicated()) {
4507 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4508 } else {
4509 return mLatency;
4510 }
4511}
4512
Eric Laurente0720872014-03-11 09:30:41 -07004513bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004514 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004515{
4516 if (isDuplicated()) {
4517 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4518 } else if (outputDesc->isDuplicated()){
4519 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4520 } else {
4521 return (mProfile->mModule == outputDesc->mProfile->mModule);
4522 }
4523}
4524
Eric Laurente0720872014-03-11 09:30:41 -07004525void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004526 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004527{
4528 // forward usage count change to attached outputs
4529 if (isDuplicated()) {
4530 mOutput1->changeRefCount(stream, delta);
4531 mOutput2->changeRefCount(stream, delta);
4532 }
4533 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004534 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4535 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004536 mRefCount[stream] = 0;
4537 return;
4538 }
4539 mRefCount[stream] += delta;
4540 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4541}
4542
Eric Laurente0720872014-03-11 09:30:41 -07004543audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004544{
4545 if (isDuplicated()) {
4546 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4547 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004548 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004549 }
4550}
4551
Eric Laurente0720872014-03-11 09:30:41 -07004552bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004553{
4554 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4555}
4556
Eric Laurente0720872014-03-11 09:30:41 -07004557bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004558 uint32_t inPastMs,
4559 nsecs_t sysTime) const
4560{
4561 if ((sysTime == 0) && (inPastMs != 0)) {
4562 sysTime = systemTime();
4563 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004564 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4565 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004566 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004567 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004568 return true;
4569 }
4570 }
4571 return false;
4572}
4573
Eric Laurente0720872014-03-11 09:30:41 -07004574bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004575 uint32_t inPastMs,
4576 nsecs_t sysTime) const
4577{
4578 if (mRefCount[stream] != 0) {
4579 return true;
4580 }
4581 if (inPastMs == 0) {
4582 return false;
4583 }
4584 if (sysTime == 0) {
4585 sysTime = systemTime();
4586 }
4587 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4588 return true;
4589 }
4590 return false;
4591}
4592
Eric Laurent1c333e22014-05-20 10:48:17 -07004593void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004594 struct audio_port_config *dstConfig,
4595 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004596{
Eric Laurent84c70242014-06-23 08:46:27 -07004597 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4598
Eric Laurent1f2f2232014-06-02 12:01:23 -07004599 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4600 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4601 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004602 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004603 }
4604 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4605
Eric Laurent6a94d692014-05-20 11:18:06 -07004606 dstConfig->id = mId;
4607 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4608 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004609 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4610 dstConfig->ext.mix.handle = mIoHandle;
4611 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004612}
4613
4614void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4615 struct audio_port *port) const
4616{
Eric Laurent84c70242014-06-23 08:46:27 -07004617 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004618 mProfile->toAudioPort(port);
4619 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004620 toAudioPortConfig(&port->active_config);
4621 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004622 port->ext.mix.handle = mIoHandle;
4623 port->ext.mix.latency_class =
4624 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4625}
Eric Laurente552edb2014-03-10 17:42:56 -07004626
Eric Laurente0720872014-03-11 09:30:41 -07004627status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004628{
4629 const size_t SIZE = 256;
4630 char buffer[SIZE];
4631 String8 result;
4632
4633 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4634 result.append(buffer);
4635 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4636 result.append(buffer);
4637 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4638 result.append(buffer);
4639 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4640 result.append(buffer);
4641 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4642 result.append(buffer);
4643 snprintf(buffer, SIZE, " Devices %08x\n", device());
4644 result.append(buffer);
4645 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4646 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004647 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4648 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4649 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004650 result.append(buffer);
4651 }
4652 write(fd, result.string(), result.size());
4653
4654 return NO_ERROR;
4655}
4656
4657// --- AudioInputDescriptor class implementation
4658
Eric Laurent1c333e22014-05-20 10:48:17 -07004659AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004660 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004661 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004662 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004663{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004664 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004665 mAudioPort = profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004666 mSamplingRate = profile->mSamplingRates[0];
4667 mFormat = profile->mFormats[0];
4668 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004669 if (profile->mGains.size() > 0) {
4670 profile->mGains[0]->getDefaultConfig(&mGain);
4671 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004672 } else {
4673 mSamplingRate = 0;
4674 mFormat = AUDIO_FORMAT_DEFAULT;
4675 mChannelMask = 0;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004676 }
Eric Laurente552edb2014-03-10 17:42:56 -07004677}
4678
Eric Laurent1c333e22014-05-20 10:48:17 -07004679void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004680 struct audio_port_config *dstConfig,
4681 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004682{
Eric Laurent84c70242014-06-23 08:46:27 -07004683 ALOG_ASSERT(mProfile != 0,
4684 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004685 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4686 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4687 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004688 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004689 }
4690
4691 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4692
Eric Laurent6a94d692014-05-20 11:18:06 -07004693 dstConfig->id = mId;
4694 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4695 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004696 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4697 dstConfig->ext.mix.handle = mIoHandle;
4698 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004699}
4700
4701void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4702 struct audio_port *port) const
4703{
Eric Laurent84c70242014-06-23 08:46:27 -07004704 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4705
Eric Laurent1c333e22014-05-20 10:48:17 -07004706 mProfile->toAudioPort(port);
4707 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004708 toAudioPortConfig(&port->active_config);
4709 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004710 port->ext.mix.handle = mIoHandle;
4711 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4712}
4713
Eric Laurente0720872014-03-11 09:30:41 -07004714status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004715{
4716 const size_t SIZE = 256;
4717 char buffer[SIZE];
4718 String8 result;
4719
4720 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4721 result.append(buffer);
4722 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4723 result.append(buffer);
4724 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4725 result.append(buffer);
4726 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4727 result.append(buffer);
4728 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4729 result.append(buffer);
4730 write(fd, result.string(), result.size());
4731
4732 return NO_ERROR;
4733}
4734
4735// --- StreamDescriptor class implementation
4736
Eric Laurente0720872014-03-11 09:30:41 -07004737AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004738 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4739{
4740 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4741}
4742
Eric Laurente0720872014-03-11 09:30:41 -07004743int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004744{
Eric Laurente0720872014-03-11 09:30:41 -07004745 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004746 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4747 if (mIndexCur.indexOfKey(device) < 0) {
4748 device = AUDIO_DEVICE_OUT_DEFAULT;
4749 }
4750 return mIndexCur.valueFor(device);
4751}
4752
Eric Laurente0720872014-03-11 09:30:41 -07004753void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004754{
4755 const size_t SIZE = 256;
4756 char buffer[SIZE];
4757 String8 result;
4758
4759 snprintf(buffer, SIZE, "%s %02d %02d ",
4760 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4761 result.append(buffer);
4762 for (size_t i = 0; i < mIndexCur.size(); i++) {
4763 snprintf(buffer, SIZE, "%04x : %02d, ",
4764 mIndexCur.keyAt(i),
4765 mIndexCur.valueAt(i));
4766 result.append(buffer);
4767 }
4768 result.append("\n");
4769
4770 write(fd, result.string(), result.size());
4771}
4772
4773// --- EffectDescriptor class implementation
4774
Eric Laurente0720872014-03-11 09:30:41 -07004775status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004776{
4777 const size_t SIZE = 256;
4778 char buffer[SIZE];
4779 String8 result;
4780
4781 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4782 result.append(buffer);
4783 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4784 result.append(buffer);
4785 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4786 result.append(buffer);
4787 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4788 result.append(buffer);
4789 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4790 result.append(buffer);
4791 write(fd, result.string(), result.size());
4792
4793 return NO_ERROR;
4794}
4795
Eric Laurent1c333e22014-05-20 10:48:17 -07004796// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004797
Eric Laurente0720872014-03-11 09:30:41 -07004798AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004799 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4800 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004801{
4802}
4803
Eric Laurente0720872014-03-11 09:30:41 -07004804AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004805{
4806 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004807 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004808 }
4809 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004810 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004811 }
4812 free((void *)mName);
4813}
4814
Eric Laurent1afeecb2014-05-14 08:52:28 -07004815status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4816{
4817 cnode *node = root->first_child;
4818
4819 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4820
4821 while (node) {
4822 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4823 profile->loadSamplingRates((char *)node->value);
4824 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4825 profile->loadFormats((char *)node->value);
4826 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4827 profile->loadInChannels((char *)node->value);
4828 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4829 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4830 mDeclaredDevices);
4831 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4832 profile->loadGains(node);
4833 }
4834 node = node->next;
4835 }
4836 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4837 "loadInput() invalid supported devices");
4838 ALOGW_IF(profile->mChannelMasks.size() == 0,
4839 "loadInput() invalid supported channel masks");
4840 ALOGW_IF(profile->mSamplingRates.size() == 0,
4841 "loadInput() invalid supported sampling rates");
4842 ALOGW_IF(profile->mFormats.size() == 0,
4843 "loadInput() invalid supported formats");
4844 if (!profile->mSupportedDevices.isEmpty() &&
4845 (profile->mChannelMasks.size() != 0) &&
4846 (profile->mSamplingRates.size() != 0) &&
4847 (profile->mFormats.size() != 0)) {
4848
4849 ALOGV("loadInput() adding input Supported Devices %04x",
4850 profile->mSupportedDevices.types());
4851
4852 mInputProfiles.add(profile);
4853 return NO_ERROR;
4854 } else {
4855 return BAD_VALUE;
4856 }
4857}
4858
4859status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4860{
4861 cnode *node = root->first_child;
4862
4863 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4864
4865 while (node) {
4866 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4867 profile->loadSamplingRates((char *)node->value);
4868 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4869 profile->loadFormats((char *)node->value);
4870 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4871 profile->loadOutChannels((char *)node->value);
4872 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4873 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4874 mDeclaredDevices);
4875 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4876 profile->mFlags = parseFlagNames((char *)node->value);
4877 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4878 profile->loadGains(node);
4879 }
4880 node = node->next;
4881 }
4882 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4883 "loadOutput() invalid supported devices");
4884 ALOGW_IF(profile->mChannelMasks.size() == 0,
4885 "loadOutput() invalid supported channel masks");
4886 ALOGW_IF(profile->mSamplingRates.size() == 0,
4887 "loadOutput() invalid supported sampling rates");
4888 ALOGW_IF(profile->mFormats.size() == 0,
4889 "loadOutput() invalid supported formats");
4890 if (!profile->mSupportedDevices.isEmpty() &&
4891 (profile->mChannelMasks.size() != 0) &&
4892 (profile->mSamplingRates.size() != 0) &&
4893 (profile->mFormats.size() != 0)) {
4894
4895 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4896 profile->mSupportedDevices.types(), profile->mFlags);
4897
4898 mOutputProfiles.add(profile);
4899 return NO_ERROR;
4900 } else {
4901 return BAD_VALUE;
4902 }
4903}
4904
4905status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4906{
4907 cnode *node = root->first_child;
4908
4909 audio_devices_t type = AUDIO_DEVICE_NONE;
4910 while (node) {
4911 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4912 type = parseDeviceNames((char *)node->value);
4913 break;
4914 }
4915 node = node->next;
4916 }
4917 if (type == AUDIO_DEVICE_NONE ||
4918 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4919 ALOGW("loadDevice() bad type %08x", type);
4920 return BAD_VALUE;
4921 }
4922 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4923 deviceDesc->mModule = this;
4924
4925 node = root->first_child;
4926 while (node) {
4927 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4928 deviceDesc->mAddress = String8((char *)node->value);
4929 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4930 if (audio_is_input_device(type)) {
4931 deviceDesc->loadInChannels((char *)node->value);
4932 } else {
4933 deviceDesc->loadOutChannels((char *)node->value);
4934 }
4935 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4936 deviceDesc->loadGains(node);
4937 }
4938 node = node->next;
4939 }
4940
4941 ALOGV("loadDevice() adding device name %s type %08x address %s",
4942 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4943
4944 mDeclaredDevices.add(deviceDesc);
4945
4946 return NO_ERROR;
4947}
4948
Eric Laurente0720872014-03-11 09:30:41 -07004949void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004950{
4951 const size_t SIZE = 256;
4952 char buffer[SIZE];
4953 String8 result;
4954
4955 snprintf(buffer, SIZE, " - name: %s\n", mName);
4956 result.append(buffer);
4957 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4958 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07004959 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
4960 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07004961 write(fd, result.string(), result.size());
4962 if (mOutputProfiles.size()) {
4963 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4964 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004965 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004966 write(fd, buffer, strlen(buffer));
4967 mOutputProfiles[i]->dump(fd);
4968 }
4969 }
4970 if (mInputProfiles.size()) {
4971 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4972 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004973 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004974 write(fd, buffer, strlen(buffer));
4975 mInputProfiles[i]->dump(fd);
4976 }
4977 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07004978 if (mDeclaredDevices.size()) {
4979 write(fd, " - devices:\n", strlen(" - devices:\n"));
4980 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
4981 mDeclaredDevices[i]->dump(fd, 4, i);
4982 }
4983 }
Eric Laurente552edb2014-03-10 17:42:56 -07004984}
4985
Eric Laurent1c333e22014-05-20 10:48:17 -07004986// --- AudioPort class implementation
4987
Eric Laurenta121f902014-06-03 13:32:54 -07004988
4989AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
4990 audio_port_role_t role, const sp<HwModule>& module) :
4991 mName(name), mType(type), mRole(role), mModule(module)
4992{
4993 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
4994 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
4995}
4996
Eric Laurent1c333e22014-05-20 10:48:17 -07004997void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
4998{
4999 port->role = mRole;
5000 port->type = mType;
5001 unsigned int i;
5002 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5003 port->sample_rates[i] = mSamplingRates[i];
5004 }
5005 port->num_sample_rates = i;
5006 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5007 port->channel_masks[i] = mChannelMasks[i];
5008 }
5009 port->num_channel_masks = i;
5010 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5011 port->formats[i] = mFormats[i];
5012 }
5013 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005014
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005015 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005016
5017 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5018 port->gains[i] = mGains[i]->mGain;
5019 }
5020 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005021}
5022
5023
5024void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5025{
5026 char *str = strtok(name, "|");
5027
5028 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5029 // rates should be read from the output stream after it is opened for the first time
5030 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5031 mSamplingRates.add(0);
5032 return;
5033 }
5034
5035 while (str != NULL) {
5036 uint32_t rate = atoi(str);
5037 if (rate != 0) {
5038 ALOGV("loadSamplingRates() adding rate %d", rate);
5039 mSamplingRates.add(rate);
5040 }
5041 str = strtok(NULL, "|");
5042 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005043}
5044
5045void AudioPolicyManager::AudioPort::loadFormats(char *name)
5046{
5047 char *str = strtok(name, "|");
5048
5049 // by convention, "0' in the first entry in mFormats indicates the supported formats
5050 // should be read from the output stream after it is opened for the first time
5051 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5052 mFormats.add(AUDIO_FORMAT_DEFAULT);
5053 return;
5054 }
5055
5056 while (str != NULL) {
5057 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5058 ARRAY_SIZE(sFormatNameToEnumTable),
5059 str);
5060 if (format != AUDIO_FORMAT_DEFAULT) {
5061 mFormats.add(format);
5062 }
5063 str = strtok(NULL, "|");
5064 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005065}
5066
5067void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5068{
5069 const char *str = strtok(name, "|");
5070
5071 ALOGV("loadInChannels() %s", name);
5072
5073 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5074 mChannelMasks.add(0);
5075 return;
5076 }
5077
5078 while (str != NULL) {
5079 audio_channel_mask_t channelMask =
5080 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5081 ARRAY_SIZE(sInChannelsNameToEnumTable),
5082 str);
5083 if (channelMask != 0) {
5084 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5085 mChannelMasks.add(channelMask);
5086 }
5087 str = strtok(NULL, "|");
5088 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005089}
5090
5091void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5092{
5093 const char *str = strtok(name, "|");
5094
5095 ALOGV("loadOutChannels() %s", name);
5096
5097 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5098 // masks should be read from the output stream after it is opened for the first time
5099 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5100 mChannelMasks.add(0);
5101 return;
5102 }
5103
5104 while (str != NULL) {
5105 audio_channel_mask_t channelMask =
5106 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5107 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5108 str);
5109 if (channelMask != 0) {
5110 mChannelMasks.add(channelMask);
5111 }
5112 str = strtok(NULL, "|");
5113 }
5114 return;
5115}
5116
Eric Laurent1afeecb2014-05-14 08:52:28 -07005117audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5118{
5119 const char *str = strtok(name, "|");
5120
5121 ALOGV("loadGainMode() %s", name);
5122 audio_gain_mode_t mode = 0;
5123 while (str != NULL) {
5124 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5125 ARRAY_SIZE(sGainModeNameToEnumTable),
5126 str);
5127 str = strtok(NULL, "|");
5128 }
5129 return mode;
5130}
5131
Eric Laurenta121f902014-06-03 13:32:54 -07005132void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005133{
5134 cnode *node = root->first_child;
5135
Eric Laurenta121f902014-06-03 13:32:54 -07005136 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005137
5138 while (node) {
5139 if (strcmp(node->name, GAIN_MODE) == 0) {
5140 gain->mGain.mode = loadGainMode((char *)node->value);
5141 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005142 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005143 gain->mGain.channel_mask =
5144 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5145 ARRAY_SIZE(sInChannelsNameToEnumTable),
5146 (char *)node->value);
5147 } else {
5148 gain->mGain.channel_mask =
5149 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5150 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5151 (char *)node->value);
5152 }
5153 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5154 gain->mGain.min_value = atoi((char *)node->value);
5155 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5156 gain->mGain.max_value = atoi((char *)node->value);
5157 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5158 gain->mGain.default_value = atoi((char *)node->value);
5159 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5160 gain->mGain.step_value = atoi((char *)node->value);
5161 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5162 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5163 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5164 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5165 }
5166 node = node->next;
5167 }
5168
5169 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5170 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5171
5172 if (gain->mGain.mode == 0) {
5173 return;
5174 }
5175 mGains.add(gain);
5176}
5177
5178void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5179{
5180 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005181 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005182 while (node) {
5183 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005184 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005185 node = node->next;
5186 }
5187}
5188
Eric Laurenta121f902014-06-03 13:32:54 -07005189status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const
5190{
5191 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5192 if (mSamplingRates[i] == samplingRate) {
5193 return NO_ERROR;
5194 }
5195 }
5196 return BAD_VALUE;
5197}
5198
5199status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const
5200{
5201 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5202 if (mChannelMasks[i] == channelMask) {
5203 return NO_ERROR;
5204 }
5205 }
5206 return BAD_VALUE;
5207}
5208
5209status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5210{
5211 for (size_t i = 0; i < mFormats.size(); i ++) {
5212 if (mFormats[i] == format) {
5213 return NO_ERROR;
5214 }
5215 }
5216 return BAD_VALUE;
5217}
5218
5219status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5220 int index) const
5221{
5222 if (index < 0 || (size_t)index >= mGains.size()) {
5223 return BAD_VALUE;
5224 }
5225 return mGains[index]->checkConfig(gainConfig);
5226}
5227
Eric Laurent1afeecb2014-05-14 08:52:28 -07005228void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5229{
5230 const size_t SIZE = 256;
5231 char buffer[SIZE];
5232 String8 result;
5233
5234 if (mName.size() != 0) {
5235 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5236 result.append(buffer);
5237 }
5238
5239 if (mSamplingRates.size() != 0) {
5240 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5241 result.append(buffer);
5242 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5243 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5244 result.append(buffer);
5245 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5246 }
5247 result.append("\n");
5248 }
5249
5250 if (mChannelMasks.size() != 0) {
5251 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5252 result.append(buffer);
5253 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5254 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5255 result.append(buffer);
5256 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5257 }
5258 result.append("\n");
5259 }
5260
5261 if (mFormats.size() != 0) {
5262 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5263 result.append(buffer);
5264 for (size_t i = 0; i < mFormats.size(); i++) {
5265 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5266 ARRAY_SIZE(sFormatNameToEnumTable),
5267 mFormats[i]));
5268 result.append(buffer);
5269 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5270 }
5271 result.append("\n");
5272 }
5273 write(fd, result.string(), result.size());
5274 if (mGains.size() != 0) {
5275 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5276 write(fd, buffer, strlen(buffer) + 1);
5277 result.append(buffer);
5278 for (size_t i = 0; i < mGains.size(); i++) {
5279 mGains[i]->dump(fd, spaces + 2, i);
5280 }
5281 }
5282}
5283
5284// --- AudioGain class implementation
5285
Eric Laurenta121f902014-06-03 13:32:54 -07005286AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005287{
Eric Laurenta121f902014-06-03 13:32:54 -07005288 mIndex = index;
5289 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005290 memset(&mGain, 0, sizeof(struct audio_gain));
5291}
5292
Eric Laurenta121f902014-06-03 13:32:54 -07005293void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5294{
5295 config->index = mIndex;
5296 config->mode = mGain.mode;
5297 config->channel_mask = mGain.channel_mask;
5298 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5299 config->values[0] = mGain.default_value;
5300 } else {
5301 uint32_t numValues;
5302 if (mUseInChannelMask) {
5303 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5304 } else {
5305 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5306 }
5307 for (size_t i = 0; i < numValues; i++) {
5308 config->values[i] = mGain.default_value;
5309 }
5310 }
5311 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5312 config->ramp_duration_ms = mGain.min_ramp_ms;
5313 }
5314}
5315
5316status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5317{
5318 if ((config->mode & ~mGain.mode) != 0) {
5319 return BAD_VALUE;
5320 }
5321 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5322 if ((config->values[0] < mGain.min_value) ||
5323 (config->values[0] > mGain.max_value)) {
5324 return BAD_VALUE;
5325 }
5326 } else {
5327 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5328 return BAD_VALUE;
5329 }
5330 uint32_t numValues;
5331 if (mUseInChannelMask) {
5332 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5333 } else {
5334 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5335 }
5336 for (size_t i = 0; i < numValues; i++) {
5337 if ((config->values[i] < mGain.min_value) ||
5338 (config->values[i] > mGain.max_value)) {
5339 return BAD_VALUE;
5340 }
5341 }
5342 }
5343 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5344 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5345 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5346 return BAD_VALUE;
5347 }
5348 }
5349 return NO_ERROR;
5350}
5351
Eric Laurent1afeecb2014-05-14 08:52:28 -07005352void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5353{
5354 const size_t SIZE = 256;
5355 char buffer[SIZE];
5356 String8 result;
5357
5358 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5359 result.append(buffer);
5360 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5361 result.append(buffer);
5362 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5363 result.append(buffer);
5364 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5365 result.append(buffer);
5366 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5367 result.append(buffer);
5368 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5369 result.append(buffer);
5370 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5371 result.append(buffer);
5372 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5373 result.append(buffer);
5374 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5375 result.append(buffer);
5376
5377 write(fd, result.string(), result.size());
5378}
5379
Eric Laurent1f2f2232014-06-02 12:01:23 -07005380// --- AudioPortConfig class implementation
5381
5382AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5383{
5384 mSamplingRate = 0;
5385 mChannelMask = AUDIO_CHANNEL_NONE;
5386 mFormat = AUDIO_FORMAT_INVALID;
5387 mGain.index = -1;
5388}
5389
Eric Laurenta121f902014-06-03 13:32:54 -07005390status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5391 const struct audio_port_config *config,
5392 struct audio_port_config *backupConfig)
5393{
5394 struct audio_port_config localBackupConfig;
5395 status_t status = NO_ERROR;
5396
5397 localBackupConfig.config_mask = config->config_mask;
5398 toAudioPortConfig(&localBackupConfig);
5399
5400 if (mAudioPort == 0) {
5401 status = NO_INIT;
5402 goto exit;
5403 }
5404 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5405 status = mAudioPort->checkSamplingRate(config->sample_rate);
5406 if (status != NO_ERROR) {
5407 goto exit;
5408 }
5409 mSamplingRate = config->sample_rate;
5410 }
5411 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5412 status = mAudioPort->checkChannelMask(config->channel_mask);
5413 if (status != NO_ERROR) {
5414 goto exit;
5415 }
5416 mChannelMask = config->channel_mask;
5417 }
5418 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5419 status = mAudioPort->checkFormat(config->format);
5420 if (status != NO_ERROR) {
5421 goto exit;
5422 }
5423 mFormat = config->format;
5424 }
5425 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5426 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5427 if (status != NO_ERROR) {
5428 goto exit;
5429 }
5430 mGain = config->gain;
5431 }
5432
5433exit:
5434 if (status != NO_ERROR) {
5435 applyAudioPortConfig(&localBackupConfig);
5436 }
5437 if (backupConfig != NULL) {
5438 *backupConfig = localBackupConfig;
5439 }
5440 return status;
5441}
5442
Eric Laurent1f2f2232014-06-02 12:01:23 -07005443void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5444 struct audio_port_config *dstConfig,
5445 const struct audio_port_config *srcConfig) const
5446{
5447 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5448 dstConfig->sample_rate = mSamplingRate;
5449 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5450 dstConfig->sample_rate = srcConfig->sample_rate;
5451 }
5452 } else {
5453 dstConfig->sample_rate = 0;
5454 }
5455 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5456 dstConfig->channel_mask = mChannelMask;
5457 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5458 dstConfig->channel_mask = srcConfig->channel_mask;
5459 }
5460 } else {
5461 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5462 }
5463 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5464 dstConfig->format = mFormat;
5465 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5466 dstConfig->format = srcConfig->format;
5467 }
5468 } else {
5469 dstConfig->format = AUDIO_FORMAT_INVALID;
5470 }
5471 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5472 dstConfig->gain = mGain;
5473 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5474 dstConfig->gain = srcConfig->gain;
5475 }
5476 } else {
5477 dstConfig->gain.index = -1;
5478 }
5479 if (dstConfig->gain.index != -1) {
5480 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5481 } else {
5482 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5483 }
5484}
5485
Eric Laurent1c333e22014-05-20 10:48:17 -07005486// --- IOProfile class implementation
5487
Eric Laurent1afeecb2014-05-14 08:52:28 -07005488AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005489 const sp<HwModule>& module)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005490 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005491{
5492}
5493
Eric Laurente0720872014-03-11 09:30:41 -07005494AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005495{
5496}
5497
5498// checks if the IO profile is compatible with specified parameters.
5499// Sampling rate, format and channel mask must be specified in order to
5500// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005501bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005502 uint32_t samplingRate,
5503 audio_format_t format,
5504 audio_channel_mask_t channelMask,
5505 audio_output_flags_t flags) const
5506{
5507 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5508 return false;
5509 }
5510
Eric Laurent3a4311c2014-03-17 12:00:47 -07005511 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005512 return false;
5513 }
5514 if ((mFlags & flags) != flags) {
5515 return false;
5516 }
Eric Laurenta121f902014-06-03 13:32:54 -07005517 if (checkSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005518 return false;
5519 }
Eric Laurenta121f902014-06-03 13:32:54 -07005520 if (checkChannelMask(channelMask) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005521 return false;
5522 }
Eric Laurenta121f902014-06-03 13:32:54 -07005523 if (checkFormat(format) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005524 return false;
5525 }
5526 return true;
5527}
5528
Eric Laurente0720872014-03-11 09:30:41 -07005529void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005530{
5531 const size_t SIZE = 256;
5532 char buffer[SIZE];
5533 String8 result;
5534
Eric Laurent1afeecb2014-05-14 08:52:28 -07005535 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005536
Eric Laurente552edb2014-03-10 17:42:56 -07005537 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5538 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005539 snprintf(buffer, SIZE, " - devices:\n");
5540 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005541 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005542 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5543 mSupportedDevices[i]->dump(fd, 6, i);
5544 }
Eric Laurente552edb2014-03-10 17:42:56 -07005545}
5546
Eric Laurentd4692962014-05-05 18:13:44 -07005547void AudioPolicyManager::IOProfile::log()
5548{
5549 const size_t SIZE = 256;
5550 char buffer[SIZE];
5551 String8 result;
5552
5553 ALOGV(" - sampling rates: ");
5554 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5555 ALOGV(" %d", mSamplingRates[i]);
5556 }
5557
5558 ALOGV(" - channel masks: ");
5559 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5560 ALOGV(" 0x%04x", mChannelMasks[i]);
5561 }
5562
5563 ALOGV(" - formats: ");
5564 for (size_t i = 0; i < mFormats.size(); i++) {
5565 ALOGV(" 0x%08x", mFormats[i]);
5566 }
5567
5568 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5569 ALOGV(" - flags: 0x%04x\n", mFlags);
5570}
5571
5572
Eric Laurent3a4311c2014-03-17 12:00:47 -07005573// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005574
Eric Laurent1f2f2232014-06-02 12:01:23 -07005575
5576AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5577 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5578 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5579 AUDIO_PORT_ROLE_SOURCE,
5580 NULL),
5581 mDeviceType(type), mAddress(""),
5582 mChannelMask(AUDIO_CHANNEL_NONE), mId(0)
5583{
5584 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005585 if (mGains.size() > 0) {
5586 mGains[0]->getDefaultConfig(&mGain);
5587 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005588}
5589
Eric Laurent3a4311c2014-03-17 12:00:47 -07005590bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005591{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005592 // Devices are considered equal if they:
5593 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5594 // - have the same address or one device does not specify the address
5595 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005596 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005597 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005598 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005599 mChannelMask == other->mChannelMask);
5600}
5601
5602void AudioPolicyManager::DeviceVector::refreshTypes()
5603{
Eric Laurent1c333e22014-05-20 10:48:17 -07005604 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005605 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005606 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005607 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005608 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005609}
5610
5611ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5612{
5613 for(size_t i = 0; i < size(); i++) {
5614 if (item->equals(itemAt(i))) {
5615 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005616 }
5617 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005618 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005619}
5620
Eric Laurent3a4311c2014-03-17 12:00:47 -07005621ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005622{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005623 ssize_t ret = indexOf(item);
5624
5625 if (ret < 0) {
5626 ret = SortedVector::add(item);
5627 if (ret >= 0) {
5628 refreshTypes();
5629 }
5630 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005631 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005632 ret = -1;
5633 }
5634 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005635}
5636
Eric Laurent3a4311c2014-03-17 12:00:47 -07005637ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5638{
5639 size_t i;
5640 ssize_t ret = indexOf(item);
5641
5642 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005643 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005644 } else {
5645 ret = SortedVector::removeAt(ret);
5646 if (ret >= 0) {
5647 refreshTypes();
5648 }
5649 }
5650 return ret;
5651}
5652
5653void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5654{
5655 DeviceVector deviceList;
5656
5657 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5658 types &= ~role_bit;
5659
5660 while (types) {
5661 uint32_t i = 31 - __builtin_clz(types);
5662 uint32_t type = 1 << i;
5663 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005664 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005665 }
5666}
5667
Eric Laurent1afeecb2014-05-14 08:52:28 -07005668void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5669 const DeviceVector& declaredDevices)
5670{
5671 char *devName = strtok(name, "|");
5672 while (devName != NULL) {
5673 if (strlen(devName) != 0) {
5674 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5675 ARRAY_SIZE(sDeviceNameToEnumTable),
5676 devName);
5677 if (type != AUDIO_DEVICE_NONE) {
5678 add(new DeviceDescriptor(String8(""), type));
5679 } else {
5680 sp<DeviceDescriptor> deviceDesc =
5681 declaredDevices.getDeviceFromName(String8(devName));
5682 if (deviceDesc != 0) {
5683 add(deviceDesc);
5684 }
5685 }
5686 }
5687 devName = strtok(NULL, "|");
5688 }
5689}
5690
Eric Laurent1c333e22014-05-20 10:48:17 -07005691sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5692 audio_devices_t type, String8 address) const
5693{
5694 sp<DeviceDescriptor> device;
5695 for (size_t i = 0; i < size(); i++) {
5696 if (itemAt(i)->mDeviceType == type) {
5697 device = itemAt(i);
5698 if (itemAt(i)->mAddress = address) {
5699 break;
5700 }
5701 }
5702 }
5703 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5704 type, address.string(), device.get());
5705 return device;
5706}
5707
Eric Laurent6a94d692014-05-20 11:18:06 -07005708sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5709 audio_port_handle_t id) const
5710{
5711 sp<DeviceDescriptor> device;
5712 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005713 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07005714 if (itemAt(i)->mId == id) {
5715 device = itemAt(i);
5716 break;
5717 }
5718 }
5719 return device;
5720}
5721
Eric Laurent1c333e22014-05-20 10:48:17 -07005722AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5723 audio_devices_t type) const
5724{
5725 DeviceVector devices;
5726 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5727 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5728 devices.add(itemAt(i));
5729 type &= ~itemAt(i)->mDeviceType;
5730 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5731 itemAt(i)->mDeviceType, itemAt(i).get());
5732 }
5733 }
5734 return devices;
5735}
5736
Eric Laurent1afeecb2014-05-14 08:52:28 -07005737sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5738 const String8& name) const
5739{
5740 sp<DeviceDescriptor> device;
5741 for (size_t i = 0; i < size(); i++) {
5742 if (itemAt(i)->mName == name) {
5743 device = itemAt(i);
5744 break;
5745 }
5746 }
5747 return device;
5748}
5749
Eric Laurent6a94d692014-05-20 11:18:06 -07005750void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5751 struct audio_port_config *dstConfig,
5752 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005753{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005754 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
5755 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005756 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005757 }
5758
5759 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5760
Eric Laurent6a94d692014-05-20 11:18:06 -07005761 dstConfig->id = mId;
5762 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005763 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005764 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005765 dstConfig->ext.device.type = mDeviceType;
5766 dstConfig->ext.device.hw_module = mModule->mHandle;
5767 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005768}
5769
5770void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5771{
Eric Laurente1715a42014-05-20 11:30:42 -07005772 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07005773 AudioPort::toAudioPort(port);
5774 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005775 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005776 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005777 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005778 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5779}
5780
Eric Laurent1afeecb2014-05-14 08:52:28 -07005781status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005782{
5783 const size_t SIZE = 256;
5784 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005785 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005786
Eric Laurent1afeecb2014-05-14 08:52:28 -07005787 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5788 result.append(buffer);
5789 if (mId != 0) {
5790 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5791 result.append(buffer);
5792 }
5793 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5794 enumToString(sDeviceNameToEnumTable,
5795 ARRAY_SIZE(sDeviceNameToEnumTable),
5796 mDeviceType));
5797 result.append(buffer);
5798 if (mAddress.size() != 0) {
5799 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5800 result.append(buffer);
5801 }
5802 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5803 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5804 result.append(buffer);
5805 }
5806 write(fd, result.string(), result.size());
5807 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005808
5809 return NO_ERROR;
5810}
5811
5812
5813// --- audio_policy.conf file parsing
5814
Eric Laurente0720872014-03-11 09:30:41 -07005815audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005816{
5817 uint32_t flag = 0;
5818
5819 // it is OK to cast name to non const here as we are not going to use it after
5820 // strtok() modifies it
5821 char *flagName = strtok(name, "|");
5822 while (flagName != NULL) {
5823 if (strlen(flagName) != 0) {
5824 flag |= stringToEnum(sFlagNameToEnumTable,
5825 ARRAY_SIZE(sFlagNameToEnumTable),
5826 flagName);
5827 }
5828 flagName = strtok(NULL, "|");
5829 }
5830 //force direct flag if offload flag is set: offloading implies a direct output stream
5831 // and all common behaviors are driven by checking only the direct flag
5832 // this should normally be set appropriately in the policy configuration file
5833 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5834 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5835 }
5836
5837 return (audio_output_flags_t)flag;
5838}
5839
Eric Laurente0720872014-03-11 09:30:41 -07005840audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005841{
5842 uint32_t device = 0;
5843
5844 char *devName = strtok(name, "|");
5845 while (devName != NULL) {
5846 if (strlen(devName) != 0) {
5847 device |= stringToEnum(sDeviceNameToEnumTable,
5848 ARRAY_SIZE(sDeviceNameToEnumTable),
5849 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005850 }
Eric Laurente552edb2014-03-10 17:42:56 -07005851 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005852 }
Eric Laurente552edb2014-03-10 17:42:56 -07005853 return device;
5854}
5855
Eric Laurente0720872014-03-11 09:30:41 -07005856void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005857{
Eric Laurente552edb2014-03-10 17:42:56 -07005858 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005859 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005860 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07005861
Eric Laurent1afeecb2014-05-14 08:52:28 -07005862 node = config_find(root, DEVICES_TAG);
5863 if (node != NULL) {
5864 node = node->first_child;
5865 while (node) {
5866 ALOGV("loadHwModule() loading device %s", node->name);
5867 status_t tmpStatus = module->loadDevice(node);
5868 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5869 status = tmpStatus;
5870 }
5871 node = node->next;
5872 }
5873 }
5874 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005875 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005876 node = node->first_child;
5877 while (node) {
5878 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005879 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005880 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5881 status = tmpStatus;
5882 }
5883 node = node->next;
5884 }
5885 }
5886 node = config_find(root, INPUTS_TAG);
5887 if (node != NULL) {
5888 node = node->first_child;
5889 while (node) {
5890 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005891 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005892 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5893 status = tmpStatus;
5894 }
5895 node = node->next;
5896 }
5897 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005898 loadGlobalConfig(root, module);
5899
Eric Laurente552edb2014-03-10 17:42:56 -07005900 if (status == NO_ERROR) {
5901 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07005902 }
5903}
5904
Eric Laurente0720872014-03-11 09:30:41 -07005905void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005906{
5907 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5908 if (node == NULL) {
5909 return;
5910 }
5911
5912 node = node->first_child;
5913 while (node) {
5914 ALOGV("loadHwModules() loading module %s", node->name);
5915 loadHwModule(node);
5916 node = node->next;
5917 }
5918}
5919
Eric Laurent1f2f2232014-06-02 12:01:23 -07005920void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07005921{
5922 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07005923
Eric Laurente552edb2014-03-10 17:42:56 -07005924 if (node == NULL) {
5925 return;
5926 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005927 DeviceVector declaredDevices;
5928 if (module != NULL) {
5929 declaredDevices = module->mDeclaredDevices;
5930 }
5931
Eric Laurente552edb2014-03-10 17:42:56 -07005932 node = node->first_child;
5933 while (node) {
5934 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005935 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5936 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005937 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5938 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005939 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005940 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005941 ARRAY_SIZE(sDeviceNameToEnumTable),
5942 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005943 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005944 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005945 } else {
5946 ALOGW("loadGlobalConfig() default device not specified");
5947 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005948 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005949 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005950 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5951 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005952 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005953 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5954 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5955 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07005956 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
5957 uint32_t major, minor;
5958 sscanf((char *)node->value, "%u.%u", &major, &minor);
5959 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
5960 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
5961 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07005962 }
5963 node = node->next;
5964 }
5965}
5966
Eric Laurente0720872014-03-11 09:30:41 -07005967status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005968{
5969 cnode *root;
5970 char *data;
5971
5972 data = (char *)load_file(path, NULL);
5973 if (data == NULL) {
5974 return -ENODEV;
5975 }
5976 root = config_node("", "");
5977 config_load(root, data);
5978
Eric Laurente552edb2014-03-10 17:42:56 -07005979 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005980 // legacy audio_policy.conf files have one global_configuration section
5981 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07005982 config_free(root);
5983 free(root);
5984 free(data);
5985
5986 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5987
5988 return NO_ERROR;
5989}
5990
Eric Laurente0720872014-03-11 09:30:41 -07005991void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07005992{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005993 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07005994 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005995 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
5996 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005997 mAvailableOutputDevices.add(mDefaultOutputDevice);
5998 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005999
6000 module = new HwModule("primary");
6001
Eric Laurent1afeecb2014-05-14 08:52:28 -07006002 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006003 profile->mSamplingRates.add(44100);
6004 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6005 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006006 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006007 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6008 module->mOutputProfiles.add(profile);
6009
Eric Laurent1afeecb2014-05-14 08:52:28 -07006010 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006011 profile->mSamplingRates.add(8000);
6012 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6013 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006014 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006015 module->mInputProfiles.add(profile);
6016
6017 mHwModules.add(module);
6018}
6019
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006020audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6021{
6022 // flags to stream type mapping
6023 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6024 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6025 }
6026 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6027 return AUDIO_STREAM_BLUETOOTH_SCO;
6028 }
6029
6030 // usage to stream type mapping
6031 switch (attr->usage) {
6032 case AUDIO_USAGE_MEDIA:
6033 case AUDIO_USAGE_GAME:
6034 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6035 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6036 return AUDIO_STREAM_MUSIC;
6037 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6038 return AUDIO_STREAM_SYSTEM;
6039 case AUDIO_USAGE_VOICE_COMMUNICATION:
6040 return AUDIO_STREAM_VOICE_CALL;
6041
6042 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6043 return AUDIO_STREAM_DTMF;
6044
6045 case AUDIO_USAGE_ALARM:
6046 return AUDIO_STREAM_ALARM;
6047 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6048 return AUDIO_STREAM_RING;
6049
6050 case AUDIO_USAGE_NOTIFICATION:
6051 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6052 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6053 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6054 case AUDIO_USAGE_NOTIFICATION_EVENT:
6055 return AUDIO_STREAM_NOTIFICATION;
6056
6057 case AUDIO_USAGE_UNKNOWN:
6058 default:
6059 return AUDIO_STREAM_MUSIC;
6060 }
6061}
Eric Laurente552edb2014-03-10 17:42:56 -07006062}; // namespace android