blob: 73c9313bd29372f8ca8c0bc471b49f310f2ee556 [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),
Terry Heo7999a222014-06-27 15:23:36 +0900104 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700105};
106
107const StringToEnum sFlagNameToEnumTable[] = {
108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
113 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
114};
115
116const StringToEnum sFormatNameToEnumTable[] = {
117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
122 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
123 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
124 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
125 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700126 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
127 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
128 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
129 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
130 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131};
132
133const StringToEnum sOutChannelsNameToEnumTable[] = {
134 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
135 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
136 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
137 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
138};
139
140const StringToEnum sInChannelsNameToEnumTable[] = {
141 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
142 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
143 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
144};
145
Eric Laurent1afeecb2014-05-14 08:52:28 -0700146const StringToEnum sGainModeNameToEnumTable[] = {
147 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
148 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
149 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
150};
151
Eric Laurent3a4311c2014-03-17 12:00:47 -0700152
153uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
154 size_t size,
155 const char *name)
156{
157 for (size_t i = 0; i < size; i++) {
158 if (strcmp(table[i].name, name) == 0) {
159 ALOGV("stringToEnum() found %s", table[i].name);
160 return table[i].value;
161 }
162 }
163 return 0;
164}
165
166const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
167 size_t size,
168 uint32_t value)
169{
170 for (size_t i = 0; i < size; i++) {
171 if (table[i].value == value) {
172 return table[i].name;
173 }
174 }
175 return "";
176}
177
178bool AudioPolicyManager::stringToBool(const char *value)
179{
180 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
181}
182
183
184// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700185// AudioPolicyInterface implementation
186// ----------------------------------------------------------------------------
187
188
Eric Laurente0720872014-03-11 09:30:41 -0700189status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700191 const char *device_address)
192{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700193 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700194
195 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
196
197 // connect/disconnect only 1 device at a time
198 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
199
Eric Laurente552edb2014-03-10 17:42:56 -0700200 // handle output devices
201 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700202 SortedVector <audio_io_handle_t> outputs;
203
Eric Laurent1afeecb2014-05-14 08:52:28 -0700204 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
205 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
207
Eric Laurente552edb2014-03-10 17:42:56 -0700208 // save a copy of the opened output descriptors before any output is opened or closed
209 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
210 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700211 switch (state)
212 {
213 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700214 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700215 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700216 ALOGW("setDeviceConnectionState() device already connected: %x", device);
217 return INVALID_OPERATION;
218 }
219 ALOGV("setDeviceConnectionState() connecting device %x", device);
220
Eric Laurent3a4311c2014-03-17 12:00:47 -0700221 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700222 return INVALID_OPERATION;
223 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700224 // outputs should never be empty here
225 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
226 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700227 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700228 outputs.size());
229 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 index = mAvailableOutputDevices.add(devDesc);
231 if (index >= 0) {
232 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700233 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700234 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
235 "could not find HW module for device %08x", device);
236 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 } else {
238 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700239 }
240
241 break;
242 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700243 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700244 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700245 ALOGW("setDeviceConnectionState() device not connected: %x", device);
246 return INVALID_OPERATION;
247 }
248
249 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
250 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700252
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700254 // not currently handling multiple simultaneous submixes: ignoring remote submix
255 // case and address
256 } break;
257
258 default:
259 ALOGE("setDeviceConnectionState() invalid state: %x", state);
260 return BAD_VALUE;
261 }
262
Eric Laurent3a4311c2014-03-17 12:00:47 -0700263 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
264 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700265 checkA2dpSuspend();
266 checkOutputForAllStrategies();
267 // outputs must be closed after checkOutputForAllStrategies() is executed
268 if (!outputs.isEmpty()) {
269 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700270 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700271 // close unused outputs after device disconnection or direct outputs that have been
272 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700273 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700274 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
275 (desc->mDirectOpenCount == 0))) {
276 closeOutput(outputs[i]);
277 }
278 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 // check again after closing A2DP output to reset mA2dpSuspended if needed
280 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700281 }
282
283 updateDevicesAndOutputs();
284 for (size_t i = 0; i < mOutputs.size(); i++) {
285 // do not force device change on duplicated output because if device is 0, it will
286 // also force a device 0 for the two outputs it is duplicated to which may override
287 // a valid device selection on those outputs.
288 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700289 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700290 !mOutputs.valueAt(i)->isDuplicated(),
291 0);
292 }
293
Eric Laurent72aa32f2014-05-30 18:51:48 -0700294 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700295 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700296 } // end if is output device
297
Eric Laurente552edb2014-03-10 17:42:56 -0700298 // handle input devices
299 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700300 SortedVector <audio_io_handle_t> inputs;
301
Eric Laurent1afeecb2014-05-14 08:52:28 -0700302 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
303 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700304 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700305 switch (state)
306 {
307 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700308 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700309 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700310 ALOGW("setDeviceConnectionState() device already connected: %d", device);
311 return INVALID_OPERATION;
312 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700313 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700314 if (module == NULL) {
315 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
316 device);
317 return INVALID_OPERATION;
318 }
Eric Laurentd4692962014-05-05 18:13:44 -0700319 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
320 return INVALID_OPERATION;
321 }
322
Eric Laurent3a4311c2014-03-17 12:00:47 -0700323 index = mAvailableInputDevices.add(devDesc);
324 if (index >= 0) {
325 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700326 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700327 } else {
328 return NO_MEMORY;
329 }
Eric Laurentd4692962014-05-05 18:13:44 -0700330 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700331
332 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700333 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700334 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700335 ALOGW("setDeviceConnectionState() device not connected: %d", device);
336 return INVALID_OPERATION;
337 }
Eric Laurentd4692962014-05-05 18:13:44 -0700338 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700339 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700340 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700341
342 default:
343 ALOGE("setDeviceConnectionState() invalid state: %x", state);
344 return BAD_VALUE;
345 }
346
Eric Laurentd4692962014-05-05 18:13:44 -0700347 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700348
Eric Laurentb52c1522014-05-20 11:27:36 -0700349 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700350 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700351 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700352
353 ALOGW("setDeviceConnectionState() invalid device: %x", device);
354 return BAD_VALUE;
355}
356
Eric Laurente0720872014-03-11 09:30:41 -0700357audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700358 const char *device_address)
359{
Eric Laurent3b73df72014-03-11 09:06:29 -0700360 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700361 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700362 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
363 devDesc->mAddress = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 ssize_t index;
365 DeviceVector *deviceVector;
366
Eric Laurente552edb2014-03-10 17:42:56 -0700367 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700368 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700369 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700370 deviceVector = &mAvailableInputDevices;
371 } else {
372 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
373 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700374 }
375
Eric Laurent3a4311c2014-03-17 12:00:47 -0700376 index = deviceVector->indexOf(devDesc);
377 if (index >= 0) {
378 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
379 } else {
380 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
381 }
Eric Laurente552edb2014-03-10 17:42:56 -0700382}
383
Eric Laurente0720872014-03-11 09:30:41 -0700384void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700385{
386 ALOGV("setPhoneState() state %d", state);
387 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700388 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700389 ALOGW("setPhoneState() invalid state %d", state);
390 return;
391 }
392
393 if (state == mPhoneState ) {
394 ALOGW("setPhoneState() setting same state %d", state);
395 return;
396 }
397
398 // if leaving call state, handle special case of active streams
399 // pertaining to sonification strategy see handleIncallSonification()
400 if (isInCall()) {
401 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700402 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
403 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700404 }
405 }
406
407 // store previous phone state for management of sonification strategy below
408 int oldState = mPhoneState;
409 mPhoneState = state;
410 bool force = false;
411
412 // are we entering or starting a call
413 if (!isStateInCall(oldState) && isStateInCall(state)) {
414 ALOGV(" Entering call in setPhoneState()");
415 // force routing command to audio hardware when starting a call
416 // even if no device change is needed
417 force = true;
418 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
419 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
420 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
421 }
422 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
423 ALOGV(" Exiting call in setPhoneState()");
424 // force routing command to audio hardware when exiting a call
425 // even if no device change is needed
426 force = true;
427 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
428 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
429 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
430 }
431 } else if (isStateInCall(state) && (state != oldState)) {
432 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
433 // force routing command to audio hardware when switching between telephony and VoIP
434 // even if no device change is needed
435 force = true;
436 }
437
438 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700439 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700440 checkA2dpSuspend();
441 checkOutputForAllStrategies();
442 updateDevicesAndOutputs();
443
Eric Laurent1f2f2232014-06-02 12:01:23 -0700444 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700445
446 // force routing command to audio hardware when ending call
447 // even if no device change is needed
448 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
449 newDevice = hwOutputDesc->device();
450 }
451
452 int delayMs = 0;
453 if (isStateInCall(state)) {
454 nsecs_t sysTime = systemTime();
455 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700456 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700457 // mute media and sonification strategies and delay device switch by the largest
458 // latency of any output where either strategy is active.
459 // This avoid sending the ring tone or music tail into the earpiece or headset.
460 if ((desc->isStrategyActive(STRATEGY_MEDIA,
461 SONIFICATION_HEADSET_MUSIC_DELAY,
462 sysTime) ||
463 desc->isStrategyActive(STRATEGY_SONIFICATION,
464 SONIFICATION_HEADSET_MUSIC_DELAY,
465 sysTime)) &&
466 (delayMs < (int)desc->mLatency*2)) {
467 delayMs = desc->mLatency*2;
468 }
469 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
470 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
471 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
472 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
473 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
474 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
475 }
476 }
477
478 // change routing is necessary
479 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
480
481 // if entering in call state, handle special case of active streams
482 // pertaining to sonification strategy see handleIncallSonification()
483 if (isStateInCall(state)) {
484 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700485 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
486 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700487 }
488 }
489
490 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700491 if (state == AUDIO_MODE_RINGTONE &&
492 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700493 mLimitRingtoneVolume = true;
494 } else {
495 mLimitRingtoneVolume = false;
496 }
497}
498
Eric Laurente0720872014-03-11 09:30:41 -0700499void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700500 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700501{
502 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
503
504 bool forceVolumeReeval = false;
505 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700506 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
507 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
508 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700509 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
510 return;
511 }
512 forceVolumeReeval = true;
513 mForceUse[usage] = config;
514 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700515 case AUDIO_POLICY_FORCE_FOR_MEDIA:
516 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
517 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
518 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
519 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900520 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700521 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
522 return;
523 }
524 mForceUse[usage] = config;
525 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700526 case AUDIO_POLICY_FORCE_FOR_RECORD:
527 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
528 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700529 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
530 return;
531 }
532 mForceUse[usage] = config;
533 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700534 case AUDIO_POLICY_FORCE_FOR_DOCK:
535 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
536 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
537 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
538 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
539 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
541 }
542 forceVolumeReeval = true;
543 mForceUse[usage] = config;
544 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700545 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
546 if (config != AUDIO_POLICY_FORCE_NONE &&
547 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700548 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
549 }
550 forceVolumeReeval = true;
551 mForceUse[usage] = config;
552 break;
553 default:
554 ALOGW("setForceUse() invalid usage %d", usage);
555 break;
556 }
557
558 // check for device and output changes triggered by new force usage
559 checkA2dpSuspend();
560 checkOutputForAllStrategies();
561 updateDevicesAndOutputs();
562 for (size_t i = 0; i < mOutputs.size(); i++) {
563 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700564 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700565 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
566 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
567 applyStreamVolumes(output, newDevice, 0, true);
568 }
569 }
570
571 audio_io_handle_t activeInput = getActiveInput();
572 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700573 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700574 }
575
576}
577
Eric Laurente0720872014-03-11 09:30:41 -0700578audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700579{
580 return mForceUse[usage];
581}
582
Eric Laurente0720872014-03-11 09:30:41 -0700583void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700584{
585 ALOGV("setSystemProperty() property %s, value %s", property, value);
586}
587
588// Find a direct output profile compatible with the parameters passed, even if the input flags do
589// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700590sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700591 audio_devices_t device,
592 uint32_t samplingRate,
593 audio_format_t format,
594 audio_channel_mask_t channelMask,
595 audio_output_flags_t flags)
596{
597 for (size_t i = 0; i < mHwModules.size(); i++) {
598 if (mHwModules[i]->mHandle == 0) {
599 continue;
600 }
601 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700602 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700603 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700604 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
605 if (profile->isCompatibleProfile(device, samplingRate, format,
606 channelMask,
607 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700608 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700609 }
610 } else {
611 if (profile->isCompatibleProfile(device, samplingRate, format,
612 channelMask,
613 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700614 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700615 }
616 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700617 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
618 return profile;
619 }
Eric Laurente552edb2014-03-10 17:42:56 -0700620 }
621 }
622 return 0;
623}
624
Eric Laurente0720872014-03-11 09:30:41 -0700625audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700626 uint32_t samplingRate,
627 audio_format_t format,
628 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700629 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700630 const audio_offload_info_t *offloadInfo)
631{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700632
Eric Laurent3b73df72014-03-11 09:06:29 -0700633 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700634 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
635 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
636 device, stream, samplingRate, format, channelMask, flags);
637
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700638 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
639 offloadInfo);
640}
641
642audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
643 uint32_t samplingRate,
644 audio_format_t format,
645 audio_channel_mask_t channelMask,
646 audio_output_flags_t flags,
647 const audio_offload_info_t *offloadInfo)
648{
649 if (attr == NULL) {
650 ALOGE("getOutputForAttr() called with NULL audio attributes");
651 return 0;
652 }
653 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
654 attr->usage, attr->content_type, attr->tags);
655
656 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
657 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
658 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
659 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
660 device, samplingRate, format, channelMask, flags);
661
662 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
663 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
664 offloadInfo);
665}
666
667audio_io_handle_t AudioPolicyManager::getOutputForDevice(
668 audio_devices_t device,
669 audio_stream_type_t stream,
670 uint32_t samplingRate,
671 audio_format_t format,
672 audio_channel_mask_t channelMask,
673 audio_output_flags_t flags,
674 const audio_offload_info_t *offloadInfo)
675{
676 audio_io_handle_t output = 0;
677 uint32_t latency = 0;
678
Eric Laurente552edb2014-03-10 17:42:56 -0700679#ifdef AUDIO_POLICY_TEST
680 if (mCurOutput != 0) {
681 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
682 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
683
684 if (mTestOutputs[mCurOutput] == 0) {
685 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700686 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700687 outputDesc->mDevice = mTestDevice;
688 outputDesc->mSamplingRate = mTestSamplingRate;
689 outputDesc->mFormat = mTestFormat;
690 outputDesc->mChannelMask = mTestChannels;
691 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700692 outputDesc->mFlags =
693 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700694 outputDesc->mRefCount[stream] = 0;
695 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
696 &outputDesc->mSamplingRate,
697 &outputDesc->mFormat,
698 &outputDesc->mChannelMask,
699 &outputDesc->mLatency,
700 outputDesc->mFlags,
701 offloadInfo);
702 if (mTestOutputs[mCurOutput]) {
703 AudioParameter outputCmd = AudioParameter();
704 outputCmd.addInt(String8("set_id"),mCurOutput);
705 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
706 addOutput(mTestOutputs[mCurOutput], outputDesc);
707 }
708 }
709 return mTestOutputs[mCurOutput];
710 }
711#endif //AUDIO_POLICY_TEST
712
713 // open a direct output if required by specified parameters
714 //force direct flag if offload flag is set: offloading implies a direct output stream
715 // and all common behaviors are driven by checking only the direct flag
716 // this should normally be set appropriately in the policy configuration file
717 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700718 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700719 }
720
721 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
722 // creating an offloaded track and tearing it down immediately after start when audioflinger
723 // detects there is an active non offloadable effect.
724 // FIXME: We should check the audio session here but we do not have it in this context.
725 // This may prevent offloading in rare situations where effects are left active by apps
726 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700727 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700728 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
729 !isNonOffloadableEffectEnabled()) {
730 profile = getProfileForDirectOutput(device,
731 samplingRate,
732 format,
733 channelMask,
734 (audio_output_flags_t)flags);
735 }
736
Eric Laurent1c333e22014-05-20 10:48:17 -0700737 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700738 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700739
740 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700741 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700742 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
743 outputDesc = desc;
744 // reuse direct output if currently open and configured with same parameters
745 if ((samplingRate == outputDesc->mSamplingRate) &&
746 (format == outputDesc->mFormat) &&
747 (channelMask == outputDesc->mChannelMask)) {
748 outputDesc->mDirectOpenCount++;
749 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
750 return mOutputs.keyAt(i);
751 }
752 }
753 }
754 // close direct output if currently open and configured with different parameters
755 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700756 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700757 }
758 outputDesc = new AudioOutputDescriptor(profile);
759 outputDesc->mDevice = device;
760 outputDesc->mSamplingRate = samplingRate;
761 outputDesc->mFormat = format;
762 outputDesc->mChannelMask = channelMask;
763 outputDesc->mLatency = 0;
764 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
765 outputDesc->mRefCount[stream] = 0;
766 outputDesc->mStopTime[stream] = 0;
767 outputDesc->mDirectOpenCount = 1;
768 output = mpClientInterface->openOutput(profile->mModule->mHandle,
769 &outputDesc->mDevice,
770 &outputDesc->mSamplingRate,
771 &outputDesc->mFormat,
772 &outputDesc->mChannelMask,
773 &outputDesc->mLatency,
774 outputDesc->mFlags,
775 offloadInfo);
776
777 // only accept an output with the requested parameters
778 if (output == 0 ||
779 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
780 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
781 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
782 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
783 "format %d %d, channelMask %04x %04x", output, samplingRate,
784 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
785 outputDesc->mChannelMask);
786 if (output != 0) {
787 mpClientInterface->closeOutput(output);
788 }
Eric Laurente552edb2014-03-10 17:42:56 -0700789 return 0;
790 }
791 audio_io_handle_t srcOutput = getOutputForEffect();
792 addOutput(output, outputDesc);
793 audio_io_handle_t dstOutput = getOutputForEffect();
794 if (dstOutput == output) {
795 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
796 }
797 mPreviousOutputs = mOutputs;
798 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700799 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700800 return output;
801 }
802
803 // ignoring channel mask due to downmix capability in mixer
804
805 // open a non direct output
806
807 // for non direct outputs, only PCM is supported
808 if (audio_is_linear_pcm(format)) {
809 // get which output is suitable for the specified stream. The actual
810 // routing change will happen when startOutput() will be called
811 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
812
813 output = selectOutput(outputs, flags);
814 }
815 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
816 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
817
818 ALOGV("getOutput() returns output %d", output);
819
820 return output;
821}
822
Eric Laurente0720872014-03-11 09:30:41 -0700823audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700824 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700825{
826 // select one output among several that provide a path to a particular device or set of
827 // devices (the list was previously build by getOutputsForDevice()).
828 // The priority is as follows:
829 // 1: the output with the highest number of requested policy flags
830 // 2: the primary output
831 // 3: the first output in the list
832
833 if (outputs.size() == 0) {
834 return 0;
835 }
836 if (outputs.size() == 1) {
837 return outputs[0];
838 }
839
840 int maxCommonFlags = 0;
841 audio_io_handle_t outputFlags = 0;
842 audio_io_handle_t outputPrimary = 0;
843
844 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700845 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700846 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700847 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700848 if (commonFlags > maxCommonFlags) {
849 outputFlags = outputs[i];
850 maxCommonFlags = commonFlags;
851 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
852 }
853 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
854 outputPrimary = outputs[i];
855 }
856 }
857 }
858
859 if (outputFlags != 0) {
860 return outputFlags;
861 }
862 if (outputPrimary != 0) {
863 return outputPrimary;
864 }
865
866 return outputs[0];
867}
868
Eric Laurente0720872014-03-11 09:30:41 -0700869status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700870 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700871 int session)
872{
873 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
874 ssize_t index = mOutputs.indexOfKey(output);
875 if (index < 0) {
876 ALOGW("startOutput() unknown output %d", output);
877 return BAD_VALUE;
878 }
879
Eric Laurent1f2f2232014-06-02 12:01:23 -0700880 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700881
882 // increment usage count for this stream on the requested output:
883 // NOTE that the usage count is the same for duplicated output and hardware output which is
884 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
885 outputDesc->changeRefCount(stream, 1);
886
887 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700888 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700889 routing_strategy strategy = getStrategy(stream);
890 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
891 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
892 uint32_t waitMs = 0;
893 bool force = false;
894 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700895 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700896 if (desc != outputDesc) {
897 // force a device change if any other output is managed by the same hw
898 // module and has a current device selection that differs from selected device.
899 // In this case, the audio HAL must receive the new device selection so that it can
900 // change the device currently selected by the other active output.
901 if (outputDesc->sharesHwModuleWith(desc) &&
902 desc->device() != newDevice) {
903 force = true;
904 }
905 // wait for audio on other active outputs to be presented when starting
906 // a notification so that audio focus effect can propagate.
907 uint32_t latency = desc->latency();
908 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
909 waitMs = latency;
910 }
911 }
912 }
913 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
914
915 // handle special case for sonification while in call
916 if (isInCall()) {
917 handleIncallSonification(stream, true, false);
918 }
919
920 // apply volume rules for current stream and device if necessary
921 checkAndSetVolume(stream,
922 mStreams[stream].getVolumeIndex(newDevice),
923 output,
924 newDevice);
925
926 // update the outputs if starting an output with a stream that can affect notification
927 // routing
928 handleNotificationRoutingForStream(stream);
929 if (waitMs > muteWaitMs) {
930 usleep((waitMs - muteWaitMs) * 2 * 1000);
931 }
932 }
933 return NO_ERROR;
934}
935
936
Eric Laurente0720872014-03-11 09:30:41 -0700937status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700938 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700939 int session)
940{
941 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
942 ssize_t index = mOutputs.indexOfKey(output);
943 if (index < 0) {
944 ALOGW("stopOutput() unknown output %d", output);
945 return BAD_VALUE;
946 }
947
Eric Laurent1f2f2232014-06-02 12:01:23 -0700948 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700949
950 // handle special case for sonification while in call
951 if (isInCall()) {
952 handleIncallSonification(stream, false, false);
953 }
954
955 if (outputDesc->mRefCount[stream] > 0) {
956 // decrement usage count of this stream on the output
957 outputDesc->changeRefCount(stream, -1);
958 // store time at which the stream was stopped - see isStreamActive()
959 if (outputDesc->mRefCount[stream] == 0) {
960 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700961 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 // delay the device switch by twice the latency because stopOutput() is executed when
963 // the track stop() command is received and at that time the audio track buffer can
964 // still contain data that needs to be drained. The latency only covers the audio HAL
965 // and kernel buffers. Also the latency does not always include additional delay in the
966 // audio path (audio DSP, CODEC ...)
967 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
968
969 // force restoring the device selection on other active outputs if it differs from the
970 // one being selected for this output
971 for (size_t i = 0; i < mOutputs.size(); i++) {
972 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700973 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700974 if (curOutput != output &&
975 desc->isActive() &&
976 outputDesc->sharesHwModuleWith(desc) &&
977 (newDevice != desc->device())) {
978 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700979 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700980 true,
981 outputDesc->mLatency*2);
982 }
983 }
984 // update the outputs if stopping one with a stream that can affect notification routing
985 handleNotificationRoutingForStream(stream);
986 }
987 return NO_ERROR;
988 } else {
989 ALOGW("stopOutput() refcount is already 0 for output %d", output);
990 return INVALID_OPERATION;
991 }
992}
993
Eric Laurente0720872014-03-11 09:30:41 -0700994void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700995{
996 ALOGV("releaseOutput() %d", output);
997 ssize_t index = mOutputs.indexOfKey(output);
998 if (index < 0) {
999 ALOGW("releaseOutput() releasing unknown output %d", output);
1000 return;
1001 }
1002
1003#ifdef AUDIO_POLICY_TEST
1004 int testIndex = testOutputIndex(output);
1005 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001006 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001007 if (outputDesc->isActive()) {
1008 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001009 mOutputs.removeItem(output);
1010 mTestOutputs[testIndex] = 0;
1011 }
1012 return;
1013 }
1014#endif //AUDIO_POLICY_TEST
1015
Eric Laurent1f2f2232014-06-02 12:01:23 -07001016 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001017 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001018 if (desc->mDirectOpenCount <= 0) {
1019 ALOGW("releaseOutput() invalid open count %d for output %d",
1020 desc->mDirectOpenCount, output);
1021 return;
1022 }
1023 if (--desc->mDirectOpenCount == 0) {
1024 closeOutput(output);
1025 // If effects where present on the output, audioflinger moved them to the primary
1026 // output by default: move them back to the appropriate output.
1027 audio_io_handle_t dstOutput = getOutputForEffect();
1028 if (dstOutput != mPrimaryOutput) {
1029 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1030 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001031 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001032 }
1033 }
1034}
1035
1036
Eric Laurente0720872014-03-11 09:30:41 -07001037audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001038 uint32_t samplingRate,
1039 audio_format_t format,
1040 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001041 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001042{
1043 audio_io_handle_t input = 0;
1044 audio_devices_t device = getDeviceForInputSource(inputSource);
1045
1046 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1047 inputSource, samplingRate, format, channelMask, acoustics);
1048
1049 if (device == AUDIO_DEVICE_NONE) {
1050 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1051 return 0;
1052 }
1053
1054 // adapt channel selection to input source
1055 switch(inputSource) {
1056 case AUDIO_SOURCE_VOICE_UPLINK:
1057 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1058 break;
1059 case AUDIO_SOURCE_VOICE_DOWNLINK:
1060 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1061 break;
1062 case AUDIO_SOURCE_VOICE_CALL:
1063 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1064 break;
1065 default:
1066 break;
1067 }
1068
Eric Laurent1c333e22014-05-20 10:48:17 -07001069 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001070 samplingRate,
1071 format,
1072 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001073 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001074 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1075 "channelMask %04x",
1076 device, samplingRate, format, channelMask);
1077 return 0;
1078 }
1079
1080 if (profile->mModule->mHandle == 0) {
1081 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1082 return 0;
1083 }
1084
Eric Laurent1f2f2232014-06-02 12:01:23 -07001085 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001086
1087 inputDesc->mInputSource = inputSource;
1088 inputDesc->mDevice = device;
1089 inputDesc->mSamplingRate = samplingRate;
1090 inputDesc->mFormat = format;
1091 inputDesc->mChannelMask = channelMask;
1092 inputDesc->mRefCount = 0;
1093 input = mpClientInterface->openInput(profile->mModule->mHandle,
1094 &inputDesc->mDevice,
1095 &inputDesc->mSamplingRate,
1096 &inputDesc->mFormat,
1097 &inputDesc->mChannelMask);
1098
1099 // only accept input with the exact requested set of parameters
1100 if (input == 0 ||
1101 (samplingRate != inputDesc->mSamplingRate) ||
1102 (format != inputDesc->mFormat) ||
1103 (channelMask != inputDesc->mChannelMask)) {
1104 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1105 samplingRate, format, channelMask);
1106 if (input != 0) {
1107 mpClientInterface->closeInput(input);
1108 }
Eric Laurente552edb2014-03-10 17:42:56 -07001109 return 0;
1110 }
Eric Laurentd4692962014-05-05 18:13:44 -07001111 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001112 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001113 return input;
1114}
1115
Eric Laurente0720872014-03-11 09:30:41 -07001116status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001117{
1118 ALOGV("startInput() input %d", input);
1119 ssize_t index = mInputs.indexOfKey(input);
1120 if (index < 0) {
1121 ALOGW("startInput() unknown input %d", input);
1122 return BAD_VALUE;
1123 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001124 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001125
1126#ifdef AUDIO_POLICY_TEST
1127 if (mTestInput == 0)
1128#endif //AUDIO_POLICY_TEST
1129 {
1130 // refuse 2 active AudioRecord clients at the same time except if the active input
1131 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1132 audio_io_handle_t activeInput = getActiveInput();
1133 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001134 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001135 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1136 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1137 stopInput(activeInput);
1138 releaseInput(activeInput);
1139 } else {
1140 ALOGW("startInput() input %d failed: other input already started", input);
1141 return INVALID_OPERATION;
1142 }
1143 }
1144 }
1145
Eric Laurent1c333e22014-05-20 10:48:17 -07001146 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001147
1148 // automatically enable the remote submix output when input is started
1149 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1150 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001151 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001152 }
1153
Eric Laurente552edb2014-03-10 17:42:56 -07001154 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1155
Eric Laurente552edb2014-03-10 17:42:56 -07001156 inputDesc->mRefCount = 1;
1157 return NO_ERROR;
1158}
1159
Eric Laurente0720872014-03-11 09:30:41 -07001160status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001161{
1162 ALOGV("stopInput() input %d", input);
1163 ssize_t index = mInputs.indexOfKey(input);
1164 if (index < 0) {
1165 ALOGW("stopInput() unknown input %d", input);
1166 return BAD_VALUE;
1167 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001168 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001169
1170 if (inputDesc->mRefCount == 0) {
1171 ALOGW("stopInput() input %d already stopped", input);
1172 return INVALID_OPERATION;
1173 } else {
1174 // automatically disable the remote submix output when input is stopped
1175 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1176 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001177 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001178 }
1179
Eric Laurent1c333e22014-05-20 10:48:17 -07001180 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001181 inputDesc->mRefCount = 0;
1182 return NO_ERROR;
1183 }
1184}
1185
Eric Laurente0720872014-03-11 09:30:41 -07001186void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001187{
1188 ALOGV("releaseInput() %d", input);
1189 ssize_t index = mInputs.indexOfKey(input);
1190 if (index < 0) {
1191 ALOGW("releaseInput() releasing unknown input %d", input);
1192 return;
1193 }
1194 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001195 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001196 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001197 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001198 ALOGV("releaseInput() exit");
1199}
1200
Eric Laurentd4692962014-05-05 18:13:44 -07001201void AudioPolicyManager::closeAllInputs() {
1202 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1203 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1204 }
1205 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001206 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001207}
1208
Eric Laurente0720872014-03-11 09:30:41 -07001209void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001210 int indexMin,
1211 int indexMax)
1212{
1213 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1214 if (indexMin < 0 || indexMin >= indexMax) {
1215 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1216 return;
1217 }
1218 mStreams[stream].mIndexMin = indexMin;
1219 mStreams[stream].mIndexMax = indexMax;
1220}
1221
Eric Laurente0720872014-03-11 09:30:41 -07001222status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001223 int index,
1224 audio_devices_t device)
1225{
1226
1227 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1228 return BAD_VALUE;
1229 }
1230 if (!audio_is_output_device(device)) {
1231 return BAD_VALUE;
1232 }
1233
1234 // Force max volume if stream cannot be muted
1235 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1236
1237 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1238 stream, device, index);
1239
1240 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1241 // clear all device specific values
1242 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1243 mStreams[stream].mIndexCur.clear();
1244 }
1245 mStreams[stream].mIndexCur.add(device, index);
1246
1247 // compute and apply stream volume on all outputs according to connected device
1248 status_t status = NO_ERROR;
1249 for (size_t i = 0; i < mOutputs.size(); i++) {
1250 audio_devices_t curDevice =
1251 getDeviceForVolume(mOutputs.valueAt(i)->device());
1252 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1253 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1254 if (volStatus != NO_ERROR) {
1255 status = volStatus;
1256 }
1257 }
1258 }
1259 return status;
1260}
1261
Eric Laurente0720872014-03-11 09:30:41 -07001262status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001263 int *index,
1264 audio_devices_t device)
1265{
1266 if (index == NULL) {
1267 return BAD_VALUE;
1268 }
1269 if (!audio_is_output_device(device)) {
1270 return BAD_VALUE;
1271 }
1272 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1273 // the strategy the stream belongs to.
1274 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1275 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1276 }
1277 device = getDeviceForVolume(device);
1278
1279 *index = mStreams[stream].getVolumeIndex(device);
1280 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1281 return NO_ERROR;
1282}
1283
Eric Laurente0720872014-03-11 09:30:41 -07001284audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001285 const SortedVector<audio_io_handle_t>& outputs)
1286{
1287 // select one output among several suitable for global effects.
1288 // The priority is as follows:
1289 // 1: An offloaded output. If the effect ends up not being offloadable,
1290 // AudioFlinger will invalidate the track and the offloaded output
1291 // will be closed causing the effect to be moved to a PCM output.
1292 // 2: A deep buffer output
1293 // 3: the first output in the list
1294
1295 if (outputs.size() == 0) {
1296 return 0;
1297 }
1298
1299 audio_io_handle_t outputOffloaded = 0;
1300 audio_io_handle_t outputDeepBuffer = 0;
1301
1302 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001303 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001304 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001305 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1306 outputOffloaded = outputs[i];
1307 }
1308 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1309 outputDeepBuffer = outputs[i];
1310 }
1311 }
1312
1313 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1314 outputOffloaded, outputDeepBuffer);
1315 if (outputOffloaded != 0) {
1316 return outputOffloaded;
1317 }
1318 if (outputDeepBuffer != 0) {
1319 return outputDeepBuffer;
1320 }
1321
1322 return outputs[0];
1323}
1324
Eric Laurente0720872014-03-11 09:30:41 -07001325audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001326{
1327 // apply simple rule where global effects are attached to the same output as MUSIC streams
1328
Eric Laurent3b73df72014-03-11 09:06:29 -07001329 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001330 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1331 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1332
1333 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1334 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1335 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1336
1337 return output;
1338}
1339
Eric Laurente0720872014-03-11 09:30:41 -07001340status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001341 audio_io_handle_t io,
1342 uint32_t strategy,
1343 int session,
1344 int id)
1345{
1346 ssize_t index = mOutputs.indexOfKey(io);
1347 if (index < 0) {
1348 index = mInputs.indexOfKey(io);
1349 if (index < 0) {
1350 ALOGW("registerEffect() unknown io %d", io);
1351 return INVALID_OPERATION;
1352 }
1353 }
1354
1355 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1356 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1357 desc->name, desc->memoryUsage);
1358 return INVALID_OPERATION;
1359 }
1360 mTotalEffectsMemory += desc->memoryUsage;
1361 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1362 desc->name, io, strategy, session, id);
1363 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1364
Eric Laurent1f2f2232014-06-02 12:01:23 -07001365 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1366 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1367 effectDesc->mIo = io;
1368 effectDesc->mStrategy = (routing_strategy)strategy;
1369 effectDesc->mSession = session;
1370 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001371
Eric Laurent1f2f2232014-06-02 12:01:23 -07001372 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001373
1374 return NO_ERROR;
1375}
1376
Eric Laurente0720872014-03-11 09:30:41 -07001377status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001378{
1379 ssize_t index = mEffects.indexOfKey(id);
1380 if (index < 0) {
1381 ALOGW("unregisterEffect() unknown effect ID %d", id);
1382 return INVALID_OPERATION;
1383 }
1384
Eric Laurent1f2f2232014-06-02 12:01:23 -07001385 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001386
Eric Laurent1f2f2232014-06-02 12:01:23 -07001387 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001388
Eric Laurent1f2f2232014-06-02 12:01:23 -07001389 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001390 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001391 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1392 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001393 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001394 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001395 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001396 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001397
1398 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001399
1400 return NO_ERROR;
1401}
1402
Eric Laurente0720872014-03-11 09:30:41 -07001403status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001404{
1405 ssize_t index = mEffects.indexOfKey(id);
1406 if (index < 0) {
1407 ALOGW("unregisterEffect() unknown effect ID %d", id);
1408 return INVALID_OPERATION;
1409 }
1410
1411 return setEffectEnabled(mEffects.valueAt(index), enabled);
1412}
1413
Eric Laurent1f2f2232014-06-02 12:01:23 -07001414status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001415{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001416 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001417 ALOGV("setEffectEnabled(%s) effect already %s",
1418 enabled?"true":"false", enabled?"enabled":"disabled");
1419 return INVALID_OPERATION;
1420 }
1421
1422 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001423 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001424 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001425 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001426 return INVALID_OPERATION;
1427 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001428 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001429 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1430 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001431 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001432 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001433 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1434 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001435 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001436 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001437 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1438 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001439 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001440 return NO_ERROR;
1441}
1442
Eric Laurente0720872014-03-11 09:30:41 -07001443bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001444{
1445 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001446 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1447 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1448 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001449 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001450 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001451 return true;
1452 }
1453 }
1454 return false;
1455}
1456
Eric Laurente0720872014-03-11 09:30:41 -07001457bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001458{
1459 nsecs_t sysTime = systemTime();
1460 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001461 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001462 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001463 return true;
1464 }
1465 }
1466 return false;
1467}
1468
Eric Laurente0720872014-03-11 09:30:41 -07001469bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001470 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001471{
1472 nsecs_t sysTime = systemTime();
1473 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001474 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001475 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001476 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001477 return true;
1478 }
1479 }
1480 return false;
1481}
1482
Eric Laurente0720872014-03-11 09:30:41 -07001483bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001484{
1485 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001486 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001487 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001488 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001489 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1490 && (inputDescriptor->mRefCount > 0)) {
1491 return true;
1492 }
1493 }
1494 return false;
1495}
1496
1497
Eric Laurente0720872014-03-11 09:30:41 -07001498status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001499{
1500 const size_t SIZE = 256;
1501 char buffer[SIZE];
1502 String8 result;
1503
1504 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1505 result.append(buffer);
1506
1507 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1508 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001509 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1510 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001511 snprintf(buffer, SIZE, " Force use for communications %d\n",
1512 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001513 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001514 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001515 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001516 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001517 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001518 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001519 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001520 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001521 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001522
Eric Laurent3a4311c2014-03-17 12:00:47 -07001523 snprintf(buffer, SIZE, " Available output devices:\n");
1524 result.append(buffer);
1525 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001526 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001527 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001528 }
1529 snprintf(buffer, SIZE, "\n Available input devices:\n");
1530 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001531 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001532 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001533 }
Eric Laurente552edb2014-03-10 17:42:56 -07001534
1535 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1536 write(fd, buffer, strlen(buffer));
1537 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001538 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001539 write(fd, buffer, strlen(buffer));
1540 mHwModules[i]->dump(fd);
1541 }
1542
1543 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1544 write(fd, buffer, strlen(buffer));
1545 for (size_t i = 0; i < mOutputs.size(); i++) {
1546 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1547 write(fd, buffer, strlen(buffer));
1548 mOutputs.valueAt(i)->dump(fd);
1549 }
1550
1551 snprintf(buffer, SIZE, "\nInputs dump:\n");
1552 write(fd, buffer, strlen(buffer));
1553 for (size_t i = 0; i < mInputs.size(); i++) {
1554 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1555 write(fd, buffer, strlen(buffer));
1556 mInputs.valueAt(i)->dump(fd);
1557 }
1558
1559 snprintf(buffer, SIZE, "\nStreams dump:\n");
1560 write(fd, buffer, strlen(buffer));
1561 snprintf(buffer, SIZE,
1562 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1563 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001564 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001565 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001566 write(fd, buffer, strlen(buffer));
1567 mStreams[i].dump(fd);
1568 }
1569
1570 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1571 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1572 write(fd, buffer, strlen(buffer));
1573
1574 snprintf(buffer, SIZE, "Registered effects:\n");
1575 write(fd, buffer, strlen(buffer));
1576 for (size_t i = 0; i < mEffects.size(); i++) {
1577 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1578 write(fd, buffer, strlen(buffer));
1579 mEffects.valueAt(i)->dump(fd);
1580 }
1581
1582
1583 return NO_ERROR;
1584}
1585
1586// This function checks for the parameters which can be offloaded.
1587// This can be enhanced depending on the capability of the DSP and policy
1588// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001589bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001590{
1591 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001592 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001593 offloadInfo.sample_rate, offloadInfo.channel_mask,
1594 offloadInfo.format,
1595 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1596 offloadInfo.has_video);
1597
1598 // Check if offload has been disabled
1599 char propValue[PROPERTY_VALUE_MAX];
1600 if (property_get("audio.offload.disable", propValue, "0")) {
1601 if (atoi(propValue) != 0) {
1602 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1603 return false;
1604 }
1605 }
1606
1607 // Check if stream type is music, then only allow offload as of now.
1608 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1609 {
1610 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1611 return false;
1612 }
1613
1614 //TODO: enable audio offloading with video when ready
1615 if (offloadInfo.has_video)
1616 {
1617 ALOGV("isOffloadSupported: has_video == true, returning false");
1618 return false;
1619 }
1620
1621 //If duration is less than minimum value defined in property, return false
1622 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1623 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1624 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1625 return false;
1626 }
1627 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1628 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1629 return false;
1630 }
1631
1632 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1633 // creating an offloaded track and tearing it down immediately after start when audioflinger
1634 // detects there is an active non offloadable effect.
1635 // FIXME: We should check the audio session here but we do not have it in this context.
1636 // This may prevent offloading in rare situations where effects are left active by apps
1637 // in the background.
1638 if (isNonOffloadableEffectEnabled()) {
1639 return false;
1640 }
1641
1642 // See if there is a profile to support this.
1643 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001644 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001645 offloadInfo.sample_rate,
1646 offloadInfo.format,
1647 offloadInfo.channel_mask,
1648 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001649 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1650 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001651}
1652
Eric Laurent6a94d692014-05-20 11:18:06 -07001653status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1654 audio_port_type_t type,
1655 unsigned int *num_ports,
1656 struct audio_port *ports,
1657 unsigned int *generation)
1658{
1659 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1660 generation == NULL) {
1661 return BAD_VALUE;
1662 }
1663 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1664 if (ports == NULL) {
1665 *num_ports = 0;
1666 }
1667
1668 size_t portsWritten = 0;
1669 size_t portsMax = *num_ports;
1670 *num_ports = 0;
1671 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1672 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1673 for (size_t i = 0;
1674 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1675 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1676 }
1677 *num_ports += mAvailableOutputDevices.size();
1678 }
1679 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1680 for (size_t i = 0;
1681 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1682 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1683 }
1684 *num_ports += mAvailableInputDevices.size();
1685 }
1686 }
1687 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1688 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1689 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1690 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1691 }
1692 *num_ports += mInputs.size();
1693 }
1694 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001695 size_t numOutputs = 0;
1696 for (size_t i = 0; i < mOutputs.size(); i++) {
1697 if (!mOutputs[i]->isDuplicated()) {
1698 numOutputs++;
1699 if (portsWritten < portsMax) {
1700 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1701 }
1702 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001703 }
Eric Laurent84c70242014-06-23 08:46:27 -07001704 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001705 }
1706 }
1707 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001708 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001709 return NO_ERROR;
1710}
1711
1712status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1713{
1714 return NO_ERROR;
1715}
1716
Eric Laurent1f2f2232014-06-02 12:01:23 -07001717sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001718 audio_port_handle_t id) const
1719{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001720 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001721 for (size_t i = 0; i < mOutputs.size(); i++) {
1722 outputDesc = mOutputs.valueAt(i);
1723 if (outputDesc->mId == id) {
1724 break;
1725 }
1726 }
1727 return outputDesc;
1728}
1729
Eric Laurent1f2f2232014-06-02 12:01:23 -07001730sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001731 audio_port_handle_t id) const
1732{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001733 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001734 for (size_t i = 0; i < mInputs.size(); i++) {
1735 inputDesc = mInputs.valueAt(i);
1736 if (inputDesc->mId == id) {
1737 break;
1738 }
1739 }
1740 return inputDesc;
1741}
1742
Eric Laurent1f2f2232014-06-02 12:01:23 -07001743sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1744 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001745{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001746 sp <HwModule> module;
1747
Eric Laurent6a94d692014-05-20 11:18:06 -07001748 for (size_t i = 0; i < mHwModules.size(); i++) {
1749 if (mHwModules[i]->mHandle == 0) {
1750 continue;
1751 }
1752 if (audio_is_output_device(device)) {
1753 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1754 {
1755 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1756 return mHwModules[i];
1757 }
1758 }
1759 } else {
1760 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1761 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1762 device & ~AUDIO_DEVICE_BIT_IN) {
1763 return mHwModules[i];
1764 }
1765 }
1766 }
1767 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001768 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001769}
1770
Eric Laurent1f2f2232014-06-02 12:01:23 -07001771sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001772{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001773 sp <HwModule> module;
1774
Eric Laurent1afeecb2014-05-14 08:52:28 -07001775 for (size_t i = 0; i < mHwModules.size(); i++)
1776 {
1777 if (strcmp(mHwModules[i]->mName, name) == 0) {
1778 return mHwModules[i];
1779 }
1780 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001781 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001782}
1783
1784
Eric Laurent6a94d692014-05-20 11:18:06 -07001785status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1786 audio_patch_handle_t *handle,
1787 uid_t uid)
1788{
1789 ALOGV("createAudioPatch()");
1790
1791 if (handle == NULL || patch == NULL) {
1792 return BAD_VALUE;
1793 }
1794 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1795
1796 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1797 return INVALID_OPERATION;
1798 }
1799 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1800 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1801 return INVALID_OPERATION;
1802 }
1803
1804 sp<AudioPatch> patchDesc;
1805 ssize_t index = mAudioPatches.indexOfKey(*handle);
1806
1807 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1808 patch->sinks[0].type);
1809 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1810 patch->sources[0].role,
1811 patch->sources[0].type);
1812
1813 if (index >= 0) {
1814 patchDesc = mAudioPatches.valueAt(index);
1815 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1816 mUidCached, patchDesc->mUid, uid);
1817 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1818 return INVALID_OPERATION;
1819 }
1820 } else {
1821 *handle = 0;
1822 }
1823
1824 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1825 // TODO add support for mix to mix connection
1826 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1827 ALOGV("createAudioPatch() source mix sink not device");
1828 return BAD_VALUE;
1829 }
1830 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001831 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001832 if (outputDesc == NULL) {
1833 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1834 return BAD_VALUE;
1835 }
Eric Laurent84c70242014-06-23 08:46:27 -07001836 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1837 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001838 if (patchDesc != 0) {
1839 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1840 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1841 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1842 return BAD_VALUE;
1843 }
1844 }
1845 sp<DeviceDescriptor> devDesc =
1846 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1847 if (devDesc == 0) {
1848 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1849 return BAD_VALUE;
1850 }
1851
Eric Laurent84c70242014-06-23 08:46:27 -07001852 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001853 patch->sources[0].sample_rate,
1854 patch->sources[0].format,
1855 patch->sources[0].channel_mask,
1856 AUDIO_OUTPUT_FLAG_NONE)) {
1857 return INVALID_OPERATION;
1858 }
1859 // TODO: reconfigure output format and channels here
1860 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001861 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001862 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001863 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001864 true,
1865 0,
1866 handle);
1867 index = mAudioPatches.indexOfKey(*handle);
1868 if (index >= 0) {
1869 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1870 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1871 }
1872 patchDesc = mAudioPatches.valueAt(index);
1873 patchDesc->mUid = uid;
1874 ALOGV("createAudioPatch() success");
1875 } else {
1876 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1877 return INVALID_OPERATION;
1878 }
1879 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1880 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1881 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001882 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001883 if (inputDesc == NULL) {
1884 return BAD_VALUE;
1885 }
1886 if (patchDesc != 0) {
1887 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1888 return BAD_VALUE;
1889 }
1890 }
1891 sp<DeviceDescriptor> devDesc =
1892 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1893 if (devDesc == 0) {
1894 return BAD_VALUE;
1895 }
1896
Eric Laurent84c70242014-06-23 08:46:27 -07001897 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001898 patch->sinks[0].sample_rate,
1899 patch->sinks[0].format,
1900 patch->sinks[0].channel_mask,
1901 AUDIO_OUTPUT_FLAG_NONE)) {
1902 return INVALID_OPERATION;
1903 }
1904 // TODO: reconfigure output format and channels here
1905 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001906 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001907 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001908 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001909 true,
1910 handle);
1911 index = mAudioPatches.indexOfKey(*handle);
1912 if (index >= 0) {
1913 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1914 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1915 }
1916 patchDesc = mAudioPatches.valueAt(index);
1917 patchDesc->mUid = uid;
1918 ALOGV("createAudioPatch() success");
1919 } else {
1920 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1921 return INVALID_OPERATION;
1922 }
1923 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1924 // device to device connection
1925 if (patchDesc != 0) {
1926 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1927 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1928 return BAD_VALUE;
1929 }
1930 }
1931
1932 sp<DeviceDescriptor> srcDeviceDesc =
1933 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1934 sp<DeviceDescriptor> sinkDeviceDesc =
1935 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1936 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1937 return BAD_VALUE;
1938 }
1939 //update source and sink with our own data as the data passed in the patch may
1940 // be incomplete.
1941 struct audio_patch newPatch = *patch;
1942 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1943 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1944
1945 // TODO: add support for devices on different HW modules
1946 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1947 return INVALID_OPERATION;
1948 }
1949 // TODO: check from routing capabilities in config file and other conflicting patches
1950
1951 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1952 if (index >= 0) {
1953 afPatchHandle = patchDesc->mAfPatchHandle;
1954 }
1955
1956 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1957 &afPatchHandle,
1958 0);
1959 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1960 status, afPatchHandle);
1961 if (status == NO_ERROR) {
1962 if (index < 0) {
1963 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1964 &newPatch, uid);
1965 addAudioPatch(patchDesc->mHandle, patchDesc);
1966 } else {
1967 patchDesc->mPatch = newPatch;
1968 }
1969 patchDesc->mAfPatchHandle = afPatchHandle;
1970 *handle = patchDesc->mHandle;
1971 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001972 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001973 } else {
1974 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1975 status);
1976 return INVALID_OPERATION;
1977 }
1978 } else {
1979 return BAD_VALUE;
1980 }
1981 } else {
1982 return BAD_VALUE;
1983 }
1984 return NO_ERROR;
1985}
1986
1987status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1988 uid_t uid)
1989{
1990 ALOGV("releaseAudioPatch() patch %d", handle);
1991
1992 ssize_t index = mAudioPatches.indexOfKey(handle);
1993
1994 if (index < 0) {
1995 return BAD_VALUE;
1996 }
1997 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1998 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1999 mUidCached, patchDesc->mUid, uid);
2000 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2001 return INVALID_OPERATION;
2002 }
2003
2004 struct audio_patch *patch = &patchDesc->mPatch;
2005 patchDesc->mUid = mUidCached;
2006 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002007 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002008 if (outputDesc == NULL) {
2009 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2010 return BAD_VALUE;
2011 }
2012
2013 setOutputDevice(outputDesc->mIoHandle,
2014 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2015 true,
2016 0,
2017 NULL);
2018 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2019 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002020 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002021 if (inputDesc == NULL) {
2022 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2023 return BAD_VALUE;
2024 }
2025 setInputDevice(inputDesc->mIoHandle,
2026 getNewInputDevice(inputDesc->mIoHandle),
2027 true,
2028 NULL);
2029 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2030 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2031 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2032 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2033 status, patchDesc->mAfPatchHandle);
2034 removeAudioPatch(patchDesc->mHandle);
2035 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002036 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002037 } else {
2038 return BAD_VALUE;
2039 }
2040 } else {
2041 return BAD_VALUE;
2042 }
2043 return NO_ERROR;
2044}
2045
2046status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2047 struct audio_patch *patches,
2048 unsigned int *generation)
2049{
2050 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2051 generation == NULL) {
2052 return BAD_VALUE;
2053 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002054 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002055 *num_patches, patches, mAudioPatches.size());
2056 if (patches == NULL) {
2057 *num_patches = 0;
2058 }
2059
2060 size_t patchesWritten = 0;
2061 size_t patchesMax = *num_patches;
2062 for (size_t i = 0;
2063 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2064 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2065 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002066 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002067 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2068 }
2069 *num_patches = mAudioPatches.size();
2070
2071 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002072 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002073 return NO_ERROR;
2074}
2075
Eric Laurente1715a42014-05-20 11:30:42 -07002076status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002077{
Eric Laurente1715a42014-05-20 11:30:42 -07002078 ALOGV("setAudioPortConfig()");
2079
2080 if (config == NULL) {
2081 return BAD_VALUE;
2082 }
2083 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2084 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002085 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2086 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002087 }
2088
Eric Laurenta121f902014-06-03 13:32:54 -07002089 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002090 if (config->type == AUDIO_PORT_TYPE_MIX) {
2091 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002092 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002093 if (outputDesc == NULL) {
2094 return BAD_VALUE;
2095 }
Eric Laurent84c70242014-06-23 08:46:27 -07002096 ALOG_ASSERT(!outputDesc->isDuplicated(),
2097 "setAudioPortConfig() called on duplicated output %d",
2098 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002099 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002100 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002101 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002102 if (inputDesc == NULL) {
2103 return BAD_VALUE;
2104 }
Eric Laurenta121f902014-06-03 13:32:54 -07002105 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002106 } else {
2107 return BAD_VALUE;
2108 }
2109 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2110 sp<DeviceDescriptor> deviceDesc;
2111 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2112 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2113 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2114 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2115 } else {
2116 return BAD_VALUE;
2117 }
2118 if (deviceDesc == NULL) {
2119 return BAD_VALUE;
2120 }
Eric Laurenta121f902014-06-03 13:32:54 -07002121 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002122 } else {
2123 return BAD_VALUE;
2124 }
2125
Eric Laurenta121f902014-06-03 13:32:54 -07002126 struct audio_port_config backupConfig;
2127 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2128 if (status == NO_ERROR) {
2129 struct audio_port_config newConfig;
2130 audioPortConfig->toAudioPortConfig(&newConfig, config);
2131 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002132 }
Eric Laurenta121f902014-06-03 13:32:54 -07002133 if (status != NO_ERROR) {
2134 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002135 }
Eric Laurente1715a42014-05-20 11:30:42 -07002136
2137 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002138}
2139
2140void AudioPolicyManager::clearAudioPatches(uid_t uid)
2141{
2142 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2143 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2144 if (patchDesc->mUid == uid) {
2145 // releaseAudioPatch() removes the patch from mAudioPatches
2146 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2147 i--;
2148 }
2149 }
2150 }
2151}
2152
2153status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2154 const sp<AudioPatch>& patch)
2155{
2156 ssize_t index = mAudioPatches.indexOfKey(handle);
2157
2158 if (index >= 0) {
2159 ALOGW("addAudioPatch() patch %d already in", handle);
2160 return ALREADY_EXISTS;
2161 }
2162 mAudioPatches.add(handle, patch);
2163 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2164 "sink handle %d",
2165 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2166 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2167 return NO_ERROR;
2168}
2169
2170status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2171{
2172 ssize_t index = mAudioPatches.indexOfKey(handle);
2173
2174 if (index < 0) {
2175 ALOGW("removeAudioPatch() patch %d not in", handle);
2176 return ALREADY_EXISTS;
2177 }
2178 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2179 mAudioPatches.valueAt(index)->mAfPatchHandle);
2180 mAudioPatches.removeItemsAt(index);
2181 return NO_ERROR;
2182}
2183
Eric Laurente552edb2014-03-10 17:42:56 -07002184// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002185// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002186// ----------------------------------------------------------------------------
2187
Eric Laurent3a4311c2014-03-17 12:00:47 -07002188uint32_t AudioPolicyManager::nextUniqueId()
2189{
2190 return android_atomic_inc(&mNextUniqueId);
2191}
2192
Eric Laurent6a94d692014-05-20 11:18:06 -07002193uint32_t AudioPolicyManager::nextAudioPortGeneration()
2194{
2195 return android_atomic_inc(&mAudioPortGeneration);
2196}
2197
Eric Laurente0720872014-03-11 09:30:41 -07002198AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002199 :
2200#ifdef AUDIO_POLICY_TEST
2201 Thread(false),
2202#endif //AUDIO_POLICY_TEST
2203 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002204 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002205 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2206 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002207 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002208 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2209 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002210{
Eric Laurent6a94d692014-05-20 11:18:06 -07002211 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002212 mpClientInterface = clientInterface;
2213
Eric Laurent3b73df72014-03-11 09:06:29 -07002214 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2215 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002216 }
2217
Eric Laurent1afeecb2014-05-14 08:52:28 -07002218 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002219 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2220 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2221 ALOGE("could not load audio policy configuration file, setting defaults");
2222 defaultAudioPolicyConfig();
2223 }
2224 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002225 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002226
2227 // must be done after reading the policy
2228 initializeVolumeCurves();
2229
2230 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002231 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2232 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002233 for (size_t i = 0; i < mHwModules.size(); i++) {
2234 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2235 if (mHwModules[i]->mHandle == 0) {
2236 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2237 continue;
2238 }
2239 // open all output streams needed to access attached devices
2240 // except for direct output streams that are only opened when they are actually
2241 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002242 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002243 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2244 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002245 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002246
Eric Laurent3a4311c2014-03-17 12:00:47 -07002247 if (outProfile->mSupportedDevices.isEmpty()) {
2248 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2249 continue;
2250 }
2251
2252 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2253 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002254 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002255 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002256
Eric Laurent1c333e22014-05-20 10:48:17 -07002257 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002258 audio_io_handle_t output = mpClientInterface->openOutput(
2259 outProfile->mModule->mHandle,
2260 &outputDesc->mDevice,
2261 &outputDesc->mSamplingRate,
2262 &outputDesc->mFormat,
2263 &outputDesc->mChannelMask,
2264 &outputDesc->mLatency,
2265 outputDesc->mFlags);
2266 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002267 ALOGW("Cannot open output stream for device %08x on hw module %s",
2268 outputDesc->mDevice,
2269 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002270 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002271 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002272 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002273 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002274 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002275 // give a valid ID to an attached device once confirmed it is reachable
2276 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2277 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002278 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002279 }
2280 }
Eric Laurente552edb2014-03-10 17:42:56 -07002281 if (mPrimaryOutput == 0 &&
2282 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2283 mPrimaryOutput = output;
2284 }
2285 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002286 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002287 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002288 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002289 true);
2290 }
2291 }
2292 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002293 // open input streams needed to access attached devices to validate
2294 // mAvailableInputDevices list
2295 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2296 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002297 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002298
Eric Laurent3a4311c2014-03-17 12:00:47 -07002299 if (inProfile->mSupportedDevices.isEmpty()) {
2300 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2301 continue;
2302 }
2303
2304 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2305 if (profileTypes & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002306 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002307
2308 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002309 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002310 audio_io_handle_t input = mpClientInterface->openInput(
2311 inProfile->mModule->mHandle,
2312 &inputDesc->mDevice,
2313 &inputDesc->mSamplingRate,
2314 &inputDesc->mFormat,
2315 &inputDesc->mChannelMask);
2316
2317 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002318 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002319 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002320 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002321 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002322 // give a valid ID to an attached device once confirmed it is reachable
2323 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2324 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002325 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002326 }
2327 }
2328 mpClientInterface->closeInput(input);
2329 } else {
2330 ALOGW("Cannot open input stream for device %08x on hw module %s",
2331 inputDesc->mDevice,
2332 mHwModules[i]->mName);
2333 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002334 }
2335 }
2336 }
2337 // make sure all attached devices have been allocated a unique ID
2338 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2339 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002340 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002341 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2342 continue;
2343 }
2344 i++;
2345 }
2346 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2347 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002348 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002349 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2350 continue;
2351 }
2352 i++;
2353 }
2354 // make sure default device is reachable
2355 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002356 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002357 }
Eric Laurente552edb2014-03-10 17:42:56 -07002358
2359 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2360
2361 updateDevicesAndOutputs();
2362
2363#ifdef AUDIO_POLICY_TEST
2364 if (mPrimaryOutput != 0) {
2365 AudioParameter outputCmd = AudioParameter();
2366 outputCmd.addInt(String8("set_id"), 0);
2367 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2368
2369 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2370 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002371 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2372 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002373 mTestLatencyMs = 0;
2374 mCurOutput = 0;
2375 mDirectOutput = false;
2376 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2377 mTestOutputs[i] = 0;
2378 }
2379
2380 const size_t SIZE = 256;
2381 char buffer[SIZE];
2382 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2383 run(buffer, ANDROID_PRIORITY_AUDIO);
2384 }
2385#endif //AUDIO_POLICY_TEST
2386}
2387
Eric Laurente0720872014-03-11 09:30:41 -07002388AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002389{
2390#ifdef AUDIO_POLICY_TEST
2391 exit();
2392#endif //AUDIO_POLICY_TEST
2393 for (size_t i = 0; i < mOutputs.size(); i++) {
2394 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002395 }
2396 for (size_t i = 0; i < mInputs.size(); i++) {
2397 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002398 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002399 mAvailableOutputDevices.clear();
2400 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002401 mOutputs.clear();
2402 mInputs.clear();
2403 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002404}
2405
Eric Laurente0720872014-03-11 09:30:41 -07002406status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002407{
2408 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2409}
2410
2411#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002412bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002413{
2414 ALOGV("entering threadLoop()");
2415 while (!exitPending())
2416 {
2417 String8 command;
2418 int valueInt;
2419 String8 value;
2420
2421 Mutex::Autolock _l(mLock);
2422 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2423
2424 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2425 AudioParameter param = AudioParameter(command);
2426
2427 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2428 valueInt != 0) {
2429 ALOGV("Test command %s received", command.string());
2430 String8 target;
2431 if (param.get(String8("target"), target) != NO_ERROR) {
2432 target = "Manager";
2433 }
2434 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2435 param.remove(String8("test_cmd_policy_output"));
2436 mCurOutput = valueInt;
2437 }
2438 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2439 param.remove(String8("test_cmd_policy_direct"));
2440 if (value == "false") {
2441 mDirectOutput = false;
2442 } else if (value == "true") {
2443 mDirectOutput = true;
2444 }
2445 }
2446 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2447 param.remove(String8("test_cmd_policy_input"));
2448 mTestInput = valueInt;
2449 }
2450
2451 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2452 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002453 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002454 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002455 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002456 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002457 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002458 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002459 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002460 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002461 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002462 if (target == "Manager") {
2463 mTestFormat = format;
2464 } else if (mTestOutputs[mCurOutput] != 0) {
2465 AudioParameter outputParam = AudioParameter();
2466 outputParam.addInt(String8("format"), format);
2467 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2468 }
2469 }
2470 }
2471 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2472 param.remove(String8("test_cmd_policy_channels"));
2473 int channels = 0;
2474
2475 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002476 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002477 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002478 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002479 }
2480 if (channels != 0) {
2481 if (target == "Manager") {
2482 mTestChannels = channels;
2483 } else if (mTestOutputs[mCurOutput] != 0) {
2484 AudioParameter outputParam = AudioParameter();
2485 outputParam.addInt(String8("channels"), channels);
2486 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2487 }
2488 }
2489 }
2490 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2491 param.remove(String8("test_cmd_policy_sampleRate"));
2492 if (valueInt >= 0 && valueInt <= 96000) {
2493 int samplingRate = valueInt;
2494 if (target == "Manager") {
2495 mTestSamplingRate = samplingRate;
2496 } else if (mTestOutputs[mCurOutput] != 0) {
2497 AudioParameter outputParam = AudioParameter();
2498 outputParam.addInt(String8("sampling_rate"), samplingRate);
2499 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2500 }
2501 }
2502 }
2503
2504 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2505 param.remove(String8("test_cmd_policy_reopen"));
2506
Eric Laurent1f2f2232014-06-02 12:01:23 -07002507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002508 mpClientInterface->closeOutput(mPrimaryOutput);
2509
2510 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2511
Eric Laurente552edb2014-03-10 17:42:56 -07002512 mOutputs.removeItem(mPrimaryOutput);
2513
Eric Laurent1f2f2232014-06-02 12:01:23 -07002514 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002515 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2516 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2517 &outputDesc->mDevice,
2518 &outputDesc->mSamplingRate,
2519 &outputDesc->mFormat,
2520 &outputDesc->mChannelMask,
2521 &outputDesc->mLatency,
2522 outputDesc->mFlags);
2523 if (mPrimaryOutput == 0) {
2524 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2525 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2526 } else {
2527 AudioParameter outputCmd = AudioParameter();
2528 outputCmd.addInt(String8("set_id"), 0);
2529 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2530 addOutput(mPrimaryOutput, outputDesc);
2531 }
2532 }
2533
2534
2535 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2536 }
2537 }
2538 return false;
2539}
2540
Eric Laurente0720872014-03-11 09:30:41 -07002541void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002542{
2543 {
2544 AutoMutex _l(mLock);
2545 requestExit();
2546 mWaitWorkCV.signal();
2547 }
2548 requestExitAndWait();
2549}
2550
Eric Laurente0720872014-03-11 09:30:41 -07002551int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002552{
2553 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2554 if (output == mTestOutputs[i]) return i;
2555 }
2556 return 0;
2557}
2558#endif //AUDIO_POLICY_TEST
2559
2560// ---
2561
Eric Laurent1f2f2232014-06-02 12:01:23 -07002562void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002563{
Eric Laurent1c333e22014-05-20 10:48:17 -07002564 outputDesc->mIoHandle = output;
2565 outputDesc->mId = nextUniqueId();
2566 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002567 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002568}
2569
Eric Laurent1f2f2232014-06-02 12:01:23 -07002570void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002571{
Eric Laurent1c333e22014-05-20 10:48:17 -07002572 inputDesc->mIoHandle = input;
2573 inputDesc->mId = nextUniqueId();
2574 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002575 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002576}
Eric Laurente552edb2014-03-10 17:42:56 -07002577
Eric Laurent3a4311c2014-03-17 12:00:47 -07002578String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2579{
2580 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2581 return String8("a2dp_sink_address=")+address;
2582 }
2583 return address;
2584}
2585
Eric Laurente0720872014-03-11 09:30:41 -07002586status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002587 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002588 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002589 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002590{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002591 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002592
Eric Laurent3b73df72014-03-11 09:06:29 -07002593 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002594 // first list already open outputs that can be routed to this device
2595 for (size_t i = 0; i < mOutputs.size(); i++) {
2596 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002597 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002598 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2599 outputs.add(mOutputs.keyAt(i));
2600 }
2601 }
2602 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002603 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002604 for (size_t i = 0; i < mHwModules.size(); i++)
2605 {
2606 if (mHwModules[i]->mHandle == 0) {
2607 continue;
2608 }
2609 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2610 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002611 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002612 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002613 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2614 }
2615 }
2616 }
2617
2618 if (profiles.isEmpty() && outputs.isEmpty()) {
2619 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2620 return BAD_VALUE;
2621 }
2622
2623 // open outputs for matching profiles if needed. Direct outputs are also opened to
2624 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2625 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002626 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002627
2628 // nothing to do if one output is already opened for this profile
2629 size_t j;
2630 for (j = 0; j < mOutputs.size(); j++) {
2631 desc = mOutputs.valueAt(j);
2632 if (!desc->isDuplicated() && desc->mProfile == profile) {
2633 break;
2634 }
2635 }
2636 if (j != mOutputs.size()) {
2637 continue;
2638 }
2639
Eric Laurent3a4311c2014-03-17 12:00:47 -07002640 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002641 desc = new AudioOutputDescriptor(profile);
2642 desc->mDevice = device;
2643 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2644 offloadInfo.sample_rate = desc->mSamplingRate;
2645 offloadInfo.format = desc->mFormat;
2646 offloadInfo.channel_mask = desc->mChannelMask;
2647
2648 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2649 &desc->mDevice,
2650 &desc->mSamplingRate,
2651 &desc->mFormat,
2652 &desc->mChannelMask,
2653 &desc->mLatency,
2654 desc->mFlags,
2655 &offloadInfo);
2656 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002657 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002658 if (!address.isEmpty()) {
2659 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002660 }
2661
Eric Laurentd4692962014-05-05 18:13:44 -07002662 // Here is where we step through and resolve any "dynamic" fields
2663 String8 reply;
2664 char *value;
2665 if (profile->mSamplingRates[0] == 0) {
2666 reply = mpClientInterface->getParameters(output,
2667 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2668 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2669 reply.string());
2670 value = strpbrk((char *)reply.string(), "=");
2671 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002672 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002673 }
Eric Laurentd4692962014-05-05 18:13:44 -07002674 }
2675 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2676 reply = mpClientInterface->getParameters(output,
2677 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2678 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2679 reply.string());
2680 value = strpbrk((char *)reply.string(), "=");
2681 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002682 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002683 }
Eric Laurentd4692962014-05-05 18:13:44 -07002684 }
2685 if (profile->mChannelMasks[0] == 0) {
2686 reply = mpClientInterface->getParameters(output,
2687 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2688 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2689 reply.string());
2690 value = strpbrk((char *)reply.string(), "=");
2691 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002692 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002693 }
Eric Laurentd4692962014-05-05 18:13:44 -07002694 }
2695 if (((profile->mSamplingRates[0] == 0) &&
2696 (profile->mSamplingRates.size() < 2)) ||
2697 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2698 (profile->mFormats.size() < 2)) ||
2699 ((profile->mChannelMasks[0] == 0) &&
2700 (profile->mChannelMasks.size() < 2))) {
2701 ALOGW("checkOutputsForDevice() direct output missing param");
2702 mpClientInterface->closeOutput(output);
2703 output = 0;
2704 } else if (profile->mSamplingRates[0] == 0) {
2705 mpClientInterface->closeOutput(output);
2706 desc->mSamplingRate = profile->mSamplingRates[1];
2707 offloadInfo.sample_rate = desc->mSamplingRate;
2708 output = mpClientInterface->openOutput(
2709 profile->mModule->mHandle,
2710 &desc->mDevice,
2711 &desc->mSamplingRate,
2712 &desc->mFormat,
2713 &desc->mChannelMask,
2714 &desc->mLatency,
2715 desc->mFlags,
2716 &offloadInfo);
2717 }
2718
2719 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002720 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002721 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2722 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002723
Eric Laurentd4692962014-05-05 18:13:44 -07002724 // set initial stream volume for device
2725 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002726
Eric Laurentd4692962014-05-05 18:13:44 -07002727 //TODO: configure audio effect output stage here
2728
2729 // open a duplicating output thread for the new output and the primary output
2730 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2731 mPrimaryOutput);
2732 if (duplicatedOutput != 0) {
2733 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002734 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002735 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2736 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2737 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2738 dupOutputDesc->mFormat = desc->mFormat;
2739 dupOutputDesc->mChannelMask = desc->mChannelMask;
2740 dupOutputDesc->mLatency = desc->mLatency;
2741 addOutput(duplicatedOutput, dupOutputDesc);
2742 applyStreamVolumes(duplicatedOutput, device, 0, true);
2743 } else {
2744 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2745 mPrimaryOutput, output);
2746 mpClientInterface->closeOutput(output);
2747 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002748 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002749 output = 0;
2750 }
Eric Laurente552edb2014-03-10 17:42:56 -07002751 }
2752 }
2753 }
2754 if (output == 0) {
2755 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002756 profiles.removeAt(profile_index);
2757 profile_index--;
2758 } else {
2759 outputs.add(output);
2760 ALOGV("checkOutputsForDevice(): adding output %d", output);
2761 }
2762 }
2763
2764 if (profiles.isEmpty()) {
2765 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2766 return BAD_VALUE;
2767 }
Eric Laurentd4692962014-05-05 18:13:44 -07002768 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002769 // check if one opened output is not needed any more after disconnecting one device
2770 for (size_t i = 0; i < mOutputs.size(); i++) {
2771 desc = mOutputs.valueAt(i);
2772 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002773 !(desc->mProfile->mSupportedDevices.types() &
2774 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002775 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2776 outputs.add(mOutputs.keyAt(i));
2777 }
2778 }
Eric Laurentd4692962014-05-05 18:13:44 -07002779 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002780 for (size_t i = 0; i < mHwModules.size(); i++)
2781 {
2782 if (mHwModules[i]->mHandle == 0) {
2783 continue;
2784 }
2785 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2786 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002787 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002788 if (profile->mSupportedDevices.types() & device) {
2789 ALOGV("checkOutputsForDevice(): "
2790 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002791 if (profile->mSamplingRates[0] == 0) {
2792 profile->mSamplingRates.clear();
2793 profile->mSamplingRates.add(0);
2794 }
2795 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2796 profile->mFormats.clear();
2797 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2798 }
2799 if (profile->mChannelMasks[0] == 0) {
2800 profile->mChannelMasks.clear();
2801 profile->mChannelMasks.add(0);
2802 }
2803 }
2804 }
2805 }
2806 }
2807 return NO_ERROR;
2808}
2809
Eric Laurentd4692962014-05-05 18:13:44 -07002810status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2811 audio_policy_dev_state_t state,
2812 SortedVector<audio_io_handle_t>& inputs,
2813 const String8 address)
2814{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002815 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002816 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2817 // first list already open inputs that can be routed to this device
2818 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2819 desc = mInputs.valueAt(input_index);
2820 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2821 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2822 inputs.add(mInputs.keyAt(input_index));
2823 }
2824 }
2825
2826 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002827 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002828 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2829 {
2830 if (mHwModules[module_idx]->mHandle == 0) {
2831 continue;
2832 }
2833 for (size_t profile_index = 0;
2834 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2835 profile_index++)
2836 {
2837 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2838 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002839 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002840 profile_index, module_idx);
2841 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2842 }
2843 }
2844 }
2845
2846 if (profiles.isEmpty() && inputs.isEmpty()) {
2847 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2848 return BAD_VALUE;
2849 }
2850
2851 // open inputs for matching profiles if needed. Direct inputs are also opened to
2852 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2853 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2854
Eric Laurent1c333e22014-05-20 10:48:17 -07002855 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002856 // nothing to do if one input is already opened for this profile
2857 size_t input_index;
2858 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2859 desc = mInputs.valueAt(input_index);
2860 if (desc->mProfile == profile) {
2861 break;
2862 }
2863 }
2864 if (input_index != mInputs.size()) {
2865 continue;
2866 }
2867
2868 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2869 desc = new AudioInputDescriptor(profile);
2870 desc->mDevice = device;
2871
2872 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2873 &desc->mDevice,
2874 &desc->mSamplingRate,
2875 &desc->mFormat,
2876 &desc->mChannelMask);
2877
2878 if (input != 0) {
2879 if (!address.isEmpty()) {
2880 mpClientInterface->setParameters(input, addressToParameter(device, address));
2881 }
2882
2883 // Here is where we step through and resolve any "dynamic" fields
2884 String8 reply;
2885 char *value;
2886 if (profile->mSamplingRates[0] == 0) {
2887 reply = mpClientInterface->getParameters(input,
2888 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2889 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2890 reply.string());
2891 value = strpbrk((char *)reply.string(), "=");
2892 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002893 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002894 }
2895 }
2896 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2897 reply = mpClientInterface->getParameters(input,
2898 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2899 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2900 value = strpbrk((char *)reply.string(), "=");
2901 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002902 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002903 }
2904 }
2905 if (profile->mChannelMasks[0] == 0) {
2906 reply = mpClientInterface->getParameters(input,
2907 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2908 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2909 reply.string());
2910 value = strpbrk((char *)reply.string(), "=");
2911 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002912 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002913 }
2914 }
2915 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2916 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2917 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2918 ALOGW("checkInputsForDevice() direct input missing param");
2919 mpClientInterface->closeInput(input);
2920 input = 0;
2921 }
2922
2923 if (input != 0) {
2924 addInput(input, desc);
2925 }
2926 } // endif input != 0
2927
2928 if (input == 0) {
2929 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07002930 profiles.removeAt(profile_index);
2931 profile_index--;
2932 } else {
2933 inputs.add(input);
2934 ALOGV("checkInputsForDevice(): adding input %d", input);
2935 }
2936 } // end scan profiles
2937
2938 if (profiles.isEmpty()) {
2939 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2940 return BAD_VALUE;
2941 }
2942 } else {
2943 // Disconnect
2944 // check if one opened input is not needed any more after disconnecting one device
2945 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2946 desc = mInputs.valueAt(input_index);
2947 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2948 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2949 mInputs.keyAt(input_index));
2950 inputs.add(mInputs.keyAt(input_index));
2951 }
2952 }
2953 // Clear any profiles associated with the disconnected device.
2954 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2955 if (mHwModules[module_index]->mHandle == 0) {
2956 continue;
2957 }
2958 for (size_t profile_index = 0;
2959 profile_index < mHwModules[module_index]->mInputProfiles.size();
2960 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002961 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002962 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002963 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002964 profile_index, module_index);
2965 if (profile->mSamplingRates[0] == 0) {
2966 profile->mSamplingRates.clear();
2967 profile->mSamplingRates.add(0);
2968 }
2969 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2970 profile->mFormats.clear();
2971 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2972 }
2973 if (profile->mChannelMasks[0] == 0) {
2974 profile->mChannelMasks.clear();
2975 profile->mChannelMasks.add(0);
2976 }
2977 }
2978 }
2979 }
2980 } // end disconnect
2981
2982 return NO_ERROR;
2983}
2984
2985
Eric Laurente0720872014-03-11 09:30:41 -07002986void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002987{
2988 ALOGV("closeOutput(%d)", output);
2989
Eric Laurent1f2f2232014-06-02 12:01:23 -07002990 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07002991 if (outputDesc == NULL) {
2992 ALOGW("closeOutput() unknown output %d", output);
2993 return;
2994 }
2995
2996 // look for duplicated outputs connected to the output being removed.
2997 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002998 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002999 if (dupOutputDesc->isDuplicated() &&
3000 (dupOutputDesc->mOutput1 == outputDesc ||
3001 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003002 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003003 if (dupOutputDesc->mOutput1 == outputDesc) {
3004 outputDesc2 = dupOutputDesc->mOutput2;
3005 } else {
3006 outputDesc2 = dupOutputDesc->mOutput1;
3007 }
3008 // As all active tracks on duplicated output will be deleted,
3009 // and as they were also referenced on the other output, the reference
3010 // count for their stream type must be adjusted accordingly on
3011 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003012 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003013 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003014 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003015 }
3016 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3017 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3018
3019 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003020 mOutputs.removeItem(duplicatedOutput);
3021 }
3022 }
3023
3024 AudioParameter param;
3025 param.add(String8("closing"), String8("true"));
3026 mpClientInterface->setParameters(output, param.toString());
3027
3028 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003029 mOutputs.removeItem(output);
3030 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003031 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003032}
3033
Eric Laurente0720872014-03-11 09:30:41 -07003034SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003035 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003036{
3037 SortedVector<audio_io_handle_t> outputs;
3038
3039 ALOGVV("getOutputsForDevice() device %04x", device);
3040 for (size_t i = 0; i < openOutputs.size(); i++) {
3041 ALOGVV("output %d isDuplicated=%d device=%04x",
3042 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3043 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3044 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3045 outputs.add(openOutputs.keyAt(i));
3046 }
3047 }
3048 return outputs;
3049}
3050
Eric Laurente0720872014-03-11 09:30:41 -07003051bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003052 SortedVector<audio_io_handle_t>& outputs2)
3053{
3054 if (outputs1.size() != outputs2.size()) {
3055 return false;
3056 }
3057 for (size_t i = 0; i < outputs1.size(); i++) {
3058 if (outputs1[i] != outputs2[i]) {
3059 return false;
3060 }
3061 }
3062 return true;
3063}
3064
Eric Laurente0720872014-03-11 09:30:41 -07003065void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003066{
3067 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3068 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3069 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3070 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3071
3072 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3073 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3074 strategy, srcOutputs[0], dstOutputs[0]);
3075 // mute strategy while moving tracks from one output to another
3076 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003077 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003078 if (desc->isStrategyActive(strategy)) {
3079 setStrategyMute(strategy, true, srcOutputs[i]);
3080 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3081 }
3082 }
3083
3084 // Move effects associated to this strategy from previous output to new output
3085 if (strategy == STRATEGY_MEDIA) {
3086 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3087 SortedVector<audio_io_handle_t> moved;
3088 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003089 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3090 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3091 effectDesc->mIo != fxOutput) {
3092 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003093 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3094 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003095 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003096 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003097 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003098 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003099 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003100 }
3101 }
3102 }
3103 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003104 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3105 if (getStrategy((audio_stream_type_t)i) == strategy) {
3106 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003107 }
3108 }
3109 }
3110}
3111
Eric Laurente0720872014-03-11 09:30:41 -07003112void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003113{
3114 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3115 checkOutputForStrategy(STRATEGY_PHONE);
3116 checkOutputForStrategy(STRATEGY_SONIFICATION);
3117 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3118 checkOutputForStrategy(STRATEGY_MEDIA);
3119 checkOutputForStrategy(STRATEGY_DTMF);
3120}
3121
Eric Laurente0720872014-03-11 09:30:41 -07003122audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003123{
Eric Laurente552edb2014-03-10 17:42:56 -07003124 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003125 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003126 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3127 return mOutputs.keyAt(i);
3128 }
3129 }
3130
3131 return 0;
3132}
3133
Eric Laurente0720872014-03-11 09:30:41 -07003134void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003135{
Eric Laurente552edb2014-03-10 17:42:56 -07003136 audio_io_handle_t a2dpOutput = getA2dpOutput();
3137 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003138 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003139 return;
3140 }
3141
Eric Laurent3a4311c2014-03-17 12:00:47 -07003142 bool isScoConnected =
3143 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003144 // suspend A2DP output if:
3145 // (NOT already suspended) &&
3146 // ((SCO device is connected &&
3147 // (forced usage for communication || for record is SCO))) ||
3148 // (phone state is ringing || in call)
3149 //
3150 // restore A2DP output if:
3151 // (Already suspended) &&
3152 // ((SCO device is NOT connected ||
3153 // (forced usage NOT for communication && NOT for record is SCO))) &&
3154 // (phone state is NOT ringing && NOT in call)
3155 //
3156 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003157 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003158 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3159 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3160 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3161 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003162
3163 mpClientInterface->restoreOutput(a2dpOutput);
3164 mA2dpSuspended = false;
3165 }
3166 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003167 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003168 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3169 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3170 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3171 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003172
3173 mpClientInterface->suspendOutput(a2dpOutput);
3174 mA2dpSuspended = true;
3175 }
3176 }
3177}
3178
Eric Laurent1c333e22014-05-20 10:48:17 -07003179audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003180{
3181 audio_devices_t device = AUDIO_DEVICE_NONE;
3182
Eric Laurent1f2f2232014-06-02 12:01:23 -07003183 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003184
3185 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3186 if (index >= 0) {
3187 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3188 if (patchDesc->mUid != mUidCached) {
3189 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3190 outputDesc->device(), outputDesc->mPatchHandle);
3191 return outputDesc->device();
3192 }
3193 }
3194
Eric Laurente552edb2014-03-10 17:42:56 -07003195 // check the following by order of priority to request a routing change if necessary:
3196 // 1: the strategy enforced audible is active on the output:
3197 // use device for strategy enforced audible
3198 // 2: we are in call or the strategy phone is active on the output:
3199 // use device for strategy phone
3200 // 3: the strategy sonification is active on the output:
3201 // use device for strategy sonification
3202 // 4: the strategy "respectful" sonification is active on the output:
3203 // use device for strategy "respectful" sonification
3204 // 5: the strategy media is active on the output:
3205 // use device for strategy media
3206 // 6: the strategy DTMF is active on the output:
3207 // use device for strategy DTMF
3208 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3209 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3210 } else if (isInCall() ||
3211 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3212 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3213 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3214 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3215 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3216 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3217 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3218 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3219 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3220 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3221 }
3222
Eric Laurent1c333e22014-05-20 10:48:17 -07003223 ALOGV("getNewOutputDevice() selected device %x", device);
3224 return device;
3225}
3226
3227audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3228{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003229 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003230
3231 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3232 if (index >= 0) {
3233 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3234 if (patchDesc->mUid != mUidCached) {
3235 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3236 inputDesc->mDevice, inputDesc->mPatchHandle);
3237 return inputDesc->mDevice;
3238 }
3239 }
3240
Eric Laurent1c333e22014-05-20 10:48:17 -07003241 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3242
3243 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003244 return device;
3245}
3246
Eric Laurente0720872014-03-11 09:30:41 -07003247uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003248 return (uint32_t)getStrategy(stream);
3249}
3250
Eric Laurente0720872014-03-11 09:30:41 -07003251audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003252 // By checking the range of stream before calling getStrategy, we avoid
3253 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3254 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003255 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003256 return AUDIO_DEVICE_NONE;
3257 }
3258 audio_devices_t devices;
3259 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3260 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3261 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3262 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003263 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003264 if (outputDesc->isStrategyActive(strategy)) {
3265 devices = outputDesc->device();
3266 break;
3267 }
Eric Laurente552edb2014-03-10 17:42:56 -07003268 }
3269 return devices;
3270}
3271
Eric Laurente0720872014-03-11 09:30:41 -07003272AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003273 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003274 // stream to strategy mapping
3275 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003276 case AUDIO_STREAM_VOICE_CALL:
3277 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003278 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003279 case AUDIO_STREAM_RING:
3280 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003281 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003282 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003283 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003284 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003285 return STRATEGY_DTMF;
3286 default:
3287 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003288 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003289 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3290 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003291 case AUDIO_STREAM_TTS:
3292 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003293 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003294 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003295 return STRATEGY_ENFORCED_AUDIBLE;
3296 }
3297}
3298
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003299uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3300 // flags to strategy mapping
3301 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3302 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3303 }
3304
3305 // usage to strategy mapping
3306 switch (attr->usage) {
3307 case AUDIO_USAGE_MEDIA:
3308 case AUDIO_USAGE_GAME:
3309 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3310 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3311 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3312 return (uint32_t) STRATEGY_MEDIA;
3313
3314 case AUDIO_USAGE_VOICE_COMMUNICATION:
3315 return (uint32_t) STRATEGY_PHONE;
3316
3317 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3318 return (uint32_t) STRATEGY_DTMF;
3319
3320 case AUDIO_USAGE_ALARM:
3321 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3322 return (uint32_t) STRATEGY_SONIFICATION;
3323
3324 case AUDIO_USAGE_NOTIFICATION:
3325 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3326 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3327 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3328 case AUDIO_USAGE_NOTIFICATION_EVENT:
3329 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3330
3331 case AUDIO_USAGE_UNKNOWN:
3332 default:
3333 return (uint32_t) STRATEGY_MEDIA;
3334 }
3335}
3336
Eric Laurente0720872014-03-11 09:30:41 -07003337void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003338 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003339 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003340 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3341 updateDevicesAndOutputs();
3342 break;
3343 default:
3344 break;
3345 }
3346}
3347
Eric Laurente0720872014-03-11 09:30:41 -07003348audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003349 bool fromCache)
3350{
3351 uint32_t device = AUDIO_DEVICE_NONE;
3352
3353 if (fromCache) {
3354 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3355 strategy, mDeviceForStrategy[strategy]);
3356 return mDeviceForStrategy[strategy];
3357 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003358 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003359 switch (strategy) {
3360
3361 case STRATEGY_SONIFICATION_RESPECTFUL:
3362 if (isInCall()) {
3363 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003364 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003365 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3366 // while media is playing on a remote device, use the the sonification behavior.
3367 // Note that we test this usecase before testing if media is playing because
3368 // the isStreamActive() method only informs about the activity of a stream, not
3369 // if it's for local playback. Note also that we use the same delay between both tests
3370 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003371 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003372 // while media is playing (or has recently played), use the same device
3373 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3374 } else {
3375 // when media is not playing anymore, fall back on the sonification behavior
3376 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3377 }
3378
3379 break;
3380
3381 case STRATEGY_DTMF:
3382 if (!isInCall()) {
3383 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3384 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3385 break;
3386 }
3387 // when in call, DTMF and PHONE strategies follow the same rules
3388 // FALL THROUGH
3389
3390 case STRATEGY_PHONE:
3391 // for phone strategy, we first consider the forced use and then the available devices by order
3392 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003393 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3394 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003395 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003396 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003397 if (device) break;
3398 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003399 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003400 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003401 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003402 if (device) break;
3403 // if SCO device is requested but no SCO device is available, fall back to default case
3404 // FALL THROUGH
3405
3406 default: // FORCE_NONE
3407 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003408 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003409 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003410 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003411 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003412 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003413 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003414 if (device) break;
3415 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003416 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003417 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003418 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003419 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003420 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003421 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003422 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003423 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003424 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003425 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003426 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003427 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003428 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003429 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003430 if (device) break;
3431 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003432 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003433 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003434 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003435 if (device == AUDIO_DEVICE_NONE) {
3436 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3437 }
3438 break;
3439
Eric Laurent3b73df72014-03-11 09:06:29 -07003440 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003441 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3442 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003443 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003444 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003445 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003446 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003447 if (device) break;
3448 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003449 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003450 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003451 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003452 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003453 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003454 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003455 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003456 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003457 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003458 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003459 if (device) break;
3460 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003461 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003462 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003463 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003464 if (device == AUDIO_DEVICE_NONE) {
3465 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3466 }
3467 break;
3468 }
3469 break;
3470
3471 case STRATEGY_SONIFICATION:
3472
3473 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3474 // handleIncallSonification().
3475 if (isInCall()) {
3476 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3477 break;
3478 }
3479 // FALL THROUGH
3480
3481 case STRATEGY_ENFORCED_AUDIBLE:
3482 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3483 // except:
3484 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3485 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3486
3487 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003488 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003489 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003490 if (device == AUDIO_DEVICE_NONE) {
3491 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3492 }
3493 }
3494 // The second device used for sonification is the same as the device used by media strategy
3495 // FALL THROUGH
3496
3497 case STRATEGY_MEDIA: {
3498 uint32_t device2 = AUDIO_DEVICE_NONE;
3499 if (strategy != STRATEGY_SONIFICATION) {
3500 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003501 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003502 }
3503 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003504 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003505 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003506 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003507 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003508 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003509 }
3510 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003511 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003512 }
3513 }
3514 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003515 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003516 }
3517 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003518 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003519 }
3520 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003521 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003522 }
3523 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003524 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003525 }
3526 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003527 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003528 }
3529 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3530 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003531 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003532 }
3533 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003534 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003535 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003536 }
3537 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003538 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003539 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003540 int device3 = AUDIO_DEVICE_NONE;
3541 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang0c943092014-07-08 22:11:24 +09003542 // ARC, SPDIF and LINE can co-exist with others.
3543 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3544 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
3545 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003546 }
Eric Laurente552edb2014-03-10 17:42:56 -07003547
Jungshik Jang839e4f32014-06-26 17:23:40 +09003548 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003549 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3550 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3551 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003552
Eric Laurente552edb2014-03-10 17:42:56 -07003553 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003554 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003555 if (device == AUDIO_DEVICE_NONE) {
3556 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3557 }
3558 } break;
3559
3560 default:
3561 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3562 break;
3563 }
3564
3565 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3566 return device;
3567}
3568
Eric Laurente0720872014-03-11 09:30:41 -07003569void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003570{
3571 for (int i = 0; i < NUM_STRATEGIES; i++) {
3572 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3573 }
3574 mPreviousOutputs = mOutputs;
3575}
3576
Eric Laurent1f2f2232014-06-02 12:01:23 -07003577uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003578 audio_devices_t prevDevice,
3579 uint32_t delayMs)
3580{
3581 // mute/unmute strategies using an incompatible device combination
3582 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3583 // if unmuting, unmute only after the specified delay
3584 if (outputDesc->isDuplicated()) {
3585 return 0;
3586 }
3587
3588 uint32_t muteWaitMs = 0;
3589 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003590 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003591
3592 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3593 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3594 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3595 bool doMute = false;
3596
3597 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3598 doMute = true;
3599 outputDesc->mStrategyMutedByDevice[i] = true;
3600 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3601 doMute = true;
3602 outputDesc->mStrategyMutedByDevice[i] = false;
3603 }
Eric Laurent99401132014-05-07 19:48:15 -07003604 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003605 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003606 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003607 // skip output if it does not share any device with current output
3608 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3609 == AUDIO_DEVICE_NONE) {
3610 continue;
3611 }
3612 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3613 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3614 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3615 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3616 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003617 if (mute) {
3618 // FIXME: should not need to double latency if volume could be applied
3619 // immediately by the audioflinger mixer. We must account for the delay
3620 // between now and the next time the audioflinger thread for this output
3621 // will process a buffer (which corresponds to one buffer size,
3622 // usually 1/2 or 1/4 of the latency).
3623 if (muteWaitMs < desc->latency() * 2) {
3624 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003625 }
3626 }
3627 }
3628 }
3629 }
3630 }
3631
Eric Laurent99401132014-05-07 19:48:15 -07003632 // temporary mute output if device selection changes to avoid volume bursts due to
3633 // different per device volumes
3634 if (outputDesc->isActive() && (device != prevDevice)) {
3635 if (muteWaitMs < outputDesc->latency() * 2) {
3636 muteWaitMs = outputDesc->latency() * 2;
3637 }
3638 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3639 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003640 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003641 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003642 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003643 muteWaitMs *2, device);
3644 }
3645 }
3646 }
3647
Eric Laurente552edb2014-03-10 17:42:56 -07003648 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3649 if (muteWaitMs > delayMs) {
3650 muteWaitMs -= delayMs;
3651 usleep(muteWaitMs * 1000);
3652 return muteWaitMs;
3653 }
3654 return 0;
3655}
3656
Eric Laurente0720872014-03-11 09:30:41 -07003657uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003658 audio_devices_t device,
3659 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003660 int delayMs,
3661 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003662{
3663 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003664 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003665 AudioParameter param;
3666 uint32_t muteWaitMs;
3667
3668 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003669 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3670 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003671 return muteWaitMs;
3672 }
3673 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3674 // output profile
3675 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003676 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003677 return 0;
3678 }
3679
3680 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003681 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003682
3683 audio_devices_t prevDevice = outputDesc->mDevice;
3684
3685 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3686
3687 if (device != AUDIO_DEVICE_NONE) {
3688 outputDesc->mDevice = device;
3689 }
3690 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3691
3692 // Do not change the routing if:
3693 // - the requested device is AUDIO_DEVICE_NONE
3694 // - the requested device is the same as current device and force is not specified.
3695 // Doing this check here allows the caller to call setOutputDevice() without conditions
3696 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3697 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3698 return muteWaitMs;
3699 }
3700
3701 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003702
Eric Laurente552edb2014-03-10 17:42:56 -07003703 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003704 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003705 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003706 } else {
3707 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3708 if (!deviceList.isEmpty()) {
3709 struct audio_patch patch;
3710 outputDesc->toAudioPortConfig(&patch.sources[0]);
3711 patch.num_sources = 1;
3712 patch.num_sinks = 0;
3713 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3714 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003715 patch.num_sinks++;
3716 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003717 ssize_t index;
3718 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3719 index = mAudioPatches.indexOfKey(*patchHandle);
3720 } else {
3721 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3722 }
3723 sp< AudioPatch> patchDesc;
3724 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3725 if (index >= 0) {
3726 patchDesc = mAudioPatches.valueAt(index);
3727 afPatchHandle = patchDesc->mAfPatchHandle;
3728 }
3729
Eric Laurent1c333e22014-05-20 10:48:17 -07003730 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003731 &afPatchHandle,
3732 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003733 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3734 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003735 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003736 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003737 if (index < 0) {
3738 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3739 &patch, mUidCached);
3740 addAudioPatch(patchDesc->mHandle, patchDesc);
3741 } else {
3742 patchDesc->mPatch = patch;
3743 }
3744 patchDesc->mAfPatchHandle = afPatchHandle;
3745 patchDesc->mUid = mUidCached;
3746 if (patchHandle) {
3747 *patchHandle = patchDesc->mHandle;
3748 }
3749 outputDesc->mPatchHandle = patchDesc->mHandle;
3750 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003751 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003752 }
3753 }
3754 }
Eric Laurente552edb2014-03-10 17:42:56 -07003755
3756 // update stream volumes according to new device
3757 applyStreamVolumes(output, device, delayMs);
3758
3759 return muteWaitMs;
3760}
3761
Eric Laurent1c333e22014-05-20 10:48:17 -07003762status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003763 int delayMs,
3764 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003765{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003766 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003767 ssize_t index;
3768 if (patchHandle) {
3769 index = mAudioPatches.indexOfKey(*patchHandle);
3770 } else {
3771 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3772 }
3773 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003774 return INVALID_OPERATION;
3775 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003776 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3777 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003778 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3779 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003780 removeAudioPatch(patchDesc->mHandle);
3781 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003782 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003783 return status;
3784}
3785
3786status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3787 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003788 bool force,
3789 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003790{
3791 status_t status = NO_ERROR;
3792
Eric Laurent1f2f2232014-06-02 12:01:23 -07003793 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003794 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3795 inputDesc->mDevice = device;
3796
3797 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3798 if (!deviceList.isEmpty()) {
3799 struct audio_patch patch;
3800 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3801 patch.num_sinks = 1;
3802 //only one input device for now
3803 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003804 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003805 ssize_t index;
3806 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3807 index = mAudioPatches.indexOfKey(*patchHandle);
3808 } else {
3809 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3810 }
3811 sp< AudioPatch> patchDesc;
3812 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3813 if (index >= 0) {
3814 patchDesc = mAudioPatches.valueAt(index);
3815 afPatchHandle = patchDesc->mAfPatchHandle;
3816 }
3817
Eric Laurent1c333e22014-05-20 10:48:17 -07003818 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003819 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003820 0);
3821 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003822 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003823 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003824 if (index < 0) {
3825 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3826 &patch, mUidCached);
3827 addAudioPatch(patchDesc->mHandle, patchDesc);
3828 } else {
3829 patchDesc->mPatch = patch;
3830 }
3831 patchDesc->mAfPatchHandle = afPatchHandle;
3832 patchDesc->mUid = mUidCached;
3833 if (patchHandle) {
3834 *patchHandle = patchDesc->mHandle;
3835 }
3836 inputDesc->mPatchHandle = patchDesc->mHandle;
3837 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003838 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003839 }
3840 }
3841 }
3842 return status;
3843}
3844
Eric Laurent6a94d692014-05-20 11:18:06 -07003845status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3846 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003847{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003848 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003849 ssize_t index;
3850 if (patchHandle) {
3851 index = mAudioPatches.indexOfKey(*patchHandle);
3852 } else {
3853 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3854 }
3855 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003856 return INVALID_OPERATION;
3857 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003858 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3859 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003860 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3861 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003862 removeAudioPatch(patchDesc->mHandle);
3863 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003864 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003865 return status;
3866}
3867
3868sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003869 uint32_t samplingRate,
3870 audio_format_t format,
3871 audio_channel_mask_t channelMask)
3872{
3873 // Choose an input profile based on the requested capture parameters: select the first available
3874 // profile supporting all requested parameters.
3875
3876 for (size_t i = 0; i < mHwModules.size(); i++)
3877 {
3878 if (mHwModules[i]->mHandle == 0) {
3879 continue;
3880 }
3881 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3882 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003883 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003884 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003885 if (profile->isCompatibleProfile(device, samplingRate, format,
3886 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3887 return profile;
3888 }
3889 }
3890 }
3891 return NULL;
3892}
3893
Eric Laurente0720872014-03-11 09:30:41 -07003894audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003895{
3896 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003897 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3898 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003899 switch (inputSource) {
3900 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003901 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003902 device = AUDIO_DEVICE_IN_VOICE_CALL;
3903 break;
3904 }
3905 // FALL THROUGH
3906
3907 case AUDIO_SOURCE_DEFAULT:
3908 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003909 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3910 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3911 break;
3912 }
3913 // FALL THROUGH
3914
Eric Laurente552edb2014-03-10 17:42:56 -07003915 case AUDIO_SOURCE_VOICE_RECOGNITION:
3916 case AUDIO_SOURCE_HOTWORD:
3917 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003918 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003919 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003920 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003921 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003922 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003923 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3924 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003925 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003926 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3927 }
3928 break;
3929 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003930 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003931 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003932 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003933 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3934 }
3935 break;
3936 case AUDIO_SOURCE_VOICE_DOWNLINK:
3937 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003938 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003939 device = AUDIO_DEVICE_IN_VOICE_CALL;
3940 }
3941 break;
3942 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003943 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003944 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3945 }
3946 break;
3947 default:
3948 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3949 break;
3950 }
3951 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3952 return device;
3953}
3954
Eric Laurente0720872014-03-11 09:30:41 -07003955bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003956{
3957 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3958 device &= ~AUDIO_DEVICE_BIT_IN;
3959 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3960 return true;
3961 }
3962 return false;
3963}
3964
Eric Laurente0720872014-03-11 09:30:41 -07003965audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003966{
3967 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003968 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003969 if ((input_descriptor->mRefCount > 0)
3970 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3971 return mInputs.keyAt(i);
3972 }
3973 }
3974 return 0;
3975}
3976
3977
Eric Laurente0720872014-03-11 09:30:41 -07003978audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003979{
3980 if (device == AUDIO_DEVICE_NONE) {
3981 // this happens when forcing a route update and no track is active on an output.
3982 // In this case the returned category is not important.
3983 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003984 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003985 // Multiple device selection is either:
3986 // - speaker + one other device: give priority to speaker in this case.
3987 // - one A2DP device + another device: happens with duplicated output. In this case
3988 // retain the device on the A2DP output as the other must not correspond to an active
3989 // selection if not the speaker.
3990 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3991 device = AUDIO_DEVICE_OUT_SPEAKER;
3992 } else {
3993 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3994 }
3995 }
3996
Eric Laurent3b73df72014-03-11 09:06:29 -07003997 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003998 "getDeviceForVolume() invalid device combination: %08x",
3999 device);
4000
4001 return device;
4002}
4003
Eric Laurente0720872014-03-11 09:30:41 -07004004AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004005{
4006 switch(getDeviceForVolume(device)) {
4007 case AUDIO_DEVICE_OUT_EARPIECE:
4008 return DEVICE_CATEGORY_EARPIECE;
4009 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4010 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4011 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4012 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4013 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4014 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4015 return DEVICE_CATEGORY_HEADSET;
4016 case AUDIO_DEVICE_OUT_SPEAKER:
4017 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4018 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4019 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4020 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4021 case AUDIO_DEVICE_OUT_USB_DEVICE:
4022 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4023 default:
4024 return DEVICE_CATEGORY_SPEAKER;
4025 }
4026}
4027
Eric Laurente0720872014-03-11 09:30:41 -07004028float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004029 int indexInUi)
4030{
4031 device_category deviceCategory = getDeviceCategory(device);
4032 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4033
4034 // the volume index in the UI is relative to the min and max volume indices for this stream type
4035 int nbSteps = 1 + curve[VOLMAX].mIndex -
4036 curve[VOLMIN].mIndex;
4037 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4038 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4039
4040 // find what part of the curve this index volume belongs to, or if it's out of bounds
4041 int segment = 0;
4042 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4043 return 0.0f;
4044 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4045 segment = 0;
4046 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4047 segment = 1;
4048 } else if (volIdx <= curve[VOLMAX].mIndex) {
4049 segment = 2;
4050 } else { // out of bounds
4051 return 1.0f;
4052 }
4053
4054 // linear interpolation in the attenuation table in dB
4055 float decibels = curve[segment].mDBAttenuation +
4056 ((float)(volIdx - curve[segment].mIndex)) *
4057 ( (curve[segment+1].mDBAttenuation -
4058 curve[segment].mDBAttenuation) /
4059 ((float)(curve[segment+1].mIndex -
4060 curve[segment].mIndex)) );
4061
4062 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4063
4064 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4065 curve[segment].mIndex, volIdx,
4066 curve[segment+1].mIndex,
4067 curve[segment].mDBAttenuation,
4068 decibels,
4069 curve[segment+1].mDBAttenuation,
4070 amplification);
4071
4072 return amplification;
4073}
4074
Eric Laurente0720872014-03-11 09:30:41 -07004075const AudioPolicyManager::VolumeCurvePoint
4076 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004077 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4078};
4079
Eric Laurente0720872014-03-11 09:30:41 -07004080const AudioPolicyManager::VolumeCurvePoint
4081 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004082 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4083};
4084
Eric Laurente0720872014-03-11 09:30:41 -07004085const AudioPolicyManager::VolumeCurvePoint
4086 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004087 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4088};
4089
Eric Laurente0720872014-03-11 09:30:41 -07004090const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004091 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004092 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004093};
4094
4095const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004096 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004097 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4098};
4099
Eric Laurente0720872014-03-11 09:30:41 -07004100const AudioPolicyManager::VolumeCurvePoint
4101 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004102 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4103};
4104
4105// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4106// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4107// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4108// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4109
Eric Laurente0720872014-03-11 09:30:41 -07004110const AudioPolicyManager::VolumeCurvePoint
4111 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004112 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4113};
4114
Eric Laurente0720872014-03-11 09:30:41 -07004115const AudioPolicyManager::VolumeCurvePoint
4116 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004117 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4118};
4119
Eric Laurente0720872014-03-11 09:30:41 -07004120const AudioPolicyManager::VolumeCurvePoint
4121 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004122 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4123};
4124
Eric Laurente0720872014-03-11 09:30:41 -07004125const AudioPolicyManager::VolumeCurvePoint
4126 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004127 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4128};
4129
Eric Laurente0720872014-03-11 09:30:41 -07004130const AudioPolicyManager::VolumeCurvePoint
4131 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004132 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4133};
4134
Eric Laurente0720872014-03-11 09:30:41 -07004135const AudioPolicyManager::VolumeCurvePoint
4136 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4137 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004138 { // AUDIO_STREAM_VOICE_CALL
4139 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4140 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4141 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4142 },
4143 { // AUDIO_STREAM_SYSTEM
4144 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4145 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4146 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4147 },
4148 { // AUDIO_STREAM_RING
4149 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4150 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4151 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4152 },
4153 { // AUDIO_STREAM_MUSIC
4154 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4155 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4156 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4157 },
4158 { // AUDIO_STREAM_ALARM
4159 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4160 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4161 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4162 },
4163 { // AUDIO_STREAM_NOTIFICATION
4164 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4165 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4166 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4167 },
4168 { // AUDIO_STREAM_BLUETOOTH_SCO
4169 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4170 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4171 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4172 },
4173 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4174 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4175 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4176 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4177 },
4178 { // AUDIO_STREAM_DTMF
4179 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4180 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4181 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4182 },
4183 { // AUDIO_STREAM_TTS
4184 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4185 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4186 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4187 },
4188};
4189
Eric Laurente0720872014-03-11 09:30:41 -07004190void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004191{
4192 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4193 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4194 mStreams[i].mVolumeCurve[j] =
4195 sVolumeProfiles[i][j];
4196 }
4197 }
4198
4199 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4200 if (mSpeakerDrcEnabled) {
4201 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4202 sDefaultSystemVolumeCurveDrc;
4203 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4204 sSpeakerSonificationVolumeCurveDrc;
4205 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4206 sSpeakerSonificationVolumeCurveDrc;
4207 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4208 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004209 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4210 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004211 }
4212}
4213
Eric Laurente0720872014-03-11 09:30:41 -07004214float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004215 int index,
4216 audio_io_handle_t output,
4217 audio_devices_t device)
4218{
4219 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004220 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004221 StreamDescriptor &streamDesc = mStreams[stream];
4222
4223 if (device == AUDIO_DEVICE_NONE) {
4224 device = outputDesc->device();
4225 }
4226
4227 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004228 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004229 index != mStreams[stream].mIndexMin &&
4230 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
Paul McLeanb919dd32014-06-26 13:16:44 -07004231 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004232 return 1.0;
4233 }
4234
4235 volume = volIndexToAmpl(device, streamDesc, index);
4236
4237 // if a headset is connected, apply the following rules to ring tones and notifications
4238 // to avoid sound level bursts in user's ears:
4239 // - always attenuate ring tones and notifications volume by 6dB
4240 // - if music is playing, always limit the volume to current music volume,
4241 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004242 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004243 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4244 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4245 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4246 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4247 ((stream_strategy == STRATEGY_SONIFICATION)
4248 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004249 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004250 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004251 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004252 streamDesc.mCanBeMuted) {
4253 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4254 // when the phone is ringing we must consider that music could have been paused just before
4255 // by the music application and behave as if music was active if the last music track was
4256 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004257 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004258 mLimitRingtoneVolume) {
4259 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004260 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4261 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004262 output,
4263 musicDevice);
4264 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4265 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4266 if (volume > minVol) {
4267 volume = minVol;
4268 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4269 }
4270 }
4271 }
4272
4273 return volume;
4274}
4275
Eric Laurente0720872014-03-11 09:30:41 -07004276status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004277 int index,
4278 audio_io_handle_t output,
4279 audio_devices_t device,
4280 int delayMs,
4281 bool force)
4282{
4283
4284 // do not change actual stream volume if the stream is muted
4285 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4286 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4287 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4288 return NO_ERROR;
4289 }
4290
4291 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004292 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4293 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4294 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4295 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004296 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004297 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004298 return INVALID_OPERATION;
4299 }
4300
4301 float volume = computeVolume(stream, index, output, device);
4302 // We actually change the volume if:
4303 // - the float value returned by computeVolume() changed
4304 // - the force flag is set
4305 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4306 force) {
4307 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4308 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4309 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4310 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004311 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4312 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004313 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004314 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004315 }
4316
Eric Laurent3b73df72014-03-11 09:06:29 -07004317 if (stream == AUDIO_STREAM_VOICE_CALL ||
4318 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004319 float voiceVolume;
4320 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004321 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004322 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4323 } else {
4324 voiceVolume = 1.0;
4325 }
4326
4327 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4328 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4329 mLastVoiceVolume = voiceVolume;
4330 }
4331 }
4332
4333 return NO_ERROR;
4334}
4335
Eric Laurente0720872014-03-11 09:30:41 -07004336void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004337 audio_devices_t device,
4338 int delayMs,
4339 bool force)
4340{
4341 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4342
Eric Laurent3b73df72014-03-11 09:06:29 -07004343 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4344 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004345 mStreams[stream].getVolumeIndex(device),
4346 output,
4347 device,
4348 delayMs,
4349 force);
4350 }
4351}
4352
Eric Laurente0720872014-03-11 09:30:41 -07004353void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004354 bool on,
4355 audio_io_handle_t output,
4356 int delayMs,
4357 audio_devices_t device)
4358{
4359 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004360 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4361 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4362 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004363 }
4364 }
4365}
4366
Eric Laurente0720872014-03-11 09:30:41 -07004367void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004368 bool on,
4369 audio_io_handle_t output,
4370 int delayMs,
4371 audio_devices_t device)
4372{
4373 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004374 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004375 if (device == AUDIO_DEVICE_NONE) {
4376 device = outputDesc->device();
4377 }
4378
4379 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4380 stream, on, output, outputDesc->mMuteCount[stream], device);
4381
4382 if (on) {
4383 if (outputDesc->mMuteCount[stream] == 0) {
4384 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004385 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4386 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004387 checkAndSetVolume(stream, 0, output, device, delayMs);
4388 }
4389 }
4390 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4391 outputDesc->mMuteCount[stream]++;
4392 } else {
4393 if (outputDesc->mMuteCount[stream] == 0) {
4394 ALOGV("setStreamMute() unmuting non muted stream!");
4395 return;
4396 }
4397 if (--outputDesc->mMuteCount[stream] == 0) {
4398 checkAndSetVolume(stream,
4399 streamDesc.getVolumeIndex(device),
4400 output,
4401 device,
4402 delayMs);
4403 }
4404 }
4405}
4406
Eric Laurente0720872014-03-11 09:30:41 -07004407void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004408 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004409{
4410 // if the stream pertains to sonification strategy and we are in call we must
4411 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4412 // in the device used for phone strategy and play the tone if the selected device does not
4413 // interfere with the device used for phone strategy
4414 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4415 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004416 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004417 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4418 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004419 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004420 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4421 stream, starting, outputDesc->mDevice, stateChange);
4422 if (outputDesc->mRefCount[stream]) {
4423 int muteCount = 1;
4424 if (stateChange) {
4425 muteCount = outputDesc->mRefCount[stream];
4426 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004427 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004428 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4429 for (int i = 0; i < muteCount; i++) {
4430 setStreamMute(stream, starting, mPrimaryOutput);
4431 }
4432 } else {
4433 ALOGV("handleIncallSonification() high visibility");
4434 if (outputDesc->device() &
4435 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4436 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4437 for (int i = 0; i < muteCount; i++) {
4438 setStreamMute(stream, starting, mPrimaryOutput);
4439 }
4440 }
4441 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004442 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4443 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004444 } else {
4445 mpClientInterface->stopTone();
4446 }
4447 }
4448 }
4449 }
4450}
4451
Eric Laurente0720872014-03-11 09:30:41 -07004452bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004453{
4454 return isStateInCall(mPhoneState);
4455}
4456
Eric Laurente0720872014-03-11 09:30:41 -07004457bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004458 return ((state == AUDIO_MODE_IN_CALL) ||
4459 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004460}
4461
Eric Laurente0720872014-03-11 09:30:41 -07004462uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004463{
4464 return MAX_EFFECTS_CPU_LOAD;
4465}
4466
Eric Laurente0720872014-03-11 09:30:41 -07004467uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004468{
4469 return MAX_EFFECTS_MEMORY;
4470}
4471
Eric Laurent6a94d692014-05-20 11:18:06 -07004472
Eric Laurente552edb2014-03-10 17:42:56 -07004473// --- AudioOutputDescriptor class implementation
4474
Eric Laurente0720872014-03-11 09:30:41 -07004475AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004476 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004477 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004478 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004479 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4480{
4481 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004482 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004483 mRefCount[i] = 0;
4484 mCurVolume[i] = -1.0;
4485 mMuteCount[i] = 0;
4486 mStopTime[i] = 0;
4487 }
4488 for (int i = 0; i < NUM_STRATEGIES; i++) {
4489 mStrategyMutedByDevice[i] = false;
4490 }
4491 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004492 mAudioPort = profile;
Eric Laurente552edb2014-03-10 17:42:56 -07004493 mSamplingRate = profile->mSamplingRates[0];
4494 mFormat = profile->mFormats[0];
4495 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004496 if (profile->mGains.size() > 0) {
4497 profile->mGains[0]->getDefaultConfig(&mGain);
4498 }
Eric Laurente552edb2014-03-10 17:42:56 -07004499 mFlags = profile->mFlags;
4500 }
4501}
4502
Eric Laurente0720872014-03-11 09:30:41 -07004503audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004504{
4505 if (isDuplicated()) {
4506 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4507 } else {
4508 return mDevice;
4509 }
4510}
4511
Eric Laurente0720872014-03-11 09:30:41 -07004512uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004513{
4514 if (isDuplicated()) {
4515 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4516 } else {
4517 return mLatency;
4518 }
4519}
4520
Eric Laurente0720872014-03-11 09:30:41 -07004521bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004522 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004523{
4524 if (isDuplicated()) {
4525 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4526 } else if (outputDesc->isDuplicated()){
4527 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4528 } else {
4529 return (mProfile->mModule == outputDesc->mProfile->mModule);
4530 }
4531}
4532
Eric Laurente0720872014-03-11 09:30:41 -07004533void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004534 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004535{
4536 // forward usage count change to attached outputs
4537 if (isDuplicated()) {
4538 mOutput1->changeRefCount(stream, delta);
4539 mOutput2->changeRefCount(stream, delta);
4540 }
4541 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004542 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4543 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004544 mRefCount[stream] = 0;
4545 return;
4546 }
4547 mRefCount[stream] += delta;
4548 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4549}
4550
Eric Laurente0720872014-03-11 09:30:41 -07004551audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004552{
4553 if (isDuplicated()) {
4554 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4555 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004556 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004557 }
4558}
4559
Eric Laurente0720872014-03-11 09:30:41 -07004560bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004561{
4562 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4563}
4564
Eric Laurente0720872014-03-11 09:30:41 -07004565bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004566 uint32_t inPastMs,
4567 nsecs_t sysTime) const
4568{
4569 if ((sysTime == 0) && (inPastMs != 0)) {
4570 sysTime = systemTime();
4571 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004572 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4573 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004574 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004575 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004576 return true;
4577 }
4578 }
4579 return false;
4580}
4581
Eric Laurente0720872014-03-11 09:30:41 -07004582bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004583 uint32_t inPastMs,
4584 nsecs_t sysTime) const
4585{
4586 if (mRefCount[stream] != 0) {
4587 return true;
4588 }
4589 if (inPastMs == 0) {
4590 return false;
4591 }
4592 if (sysTime == 0) {
4593 sysTime = systemTime();
4594 }
4595 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4596 return true;
4597 }
4598 return false;
4599}
4600
Eric Laurent1c333e22014-05-20 10:48:17 -07004601void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004602 struct audio_port_config *dstConfig,
4603 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004604{
Eric Laurent84c70242014-06-23 08:46:27 -07004605 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4606
Eric Laurent1f2f2232014-06-02 12:01:23 -07004607 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4608 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4609 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004610 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004611 }
4612 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4613
Eric Laurent6a94d692014-05-20 11:18:06 -07004614 dstConfig->id = mId;
4615 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4616 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004617 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4618 dstConfig->ext.mix.handle = mIoHandle;
4619 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004620}
4621
4622void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4623 struct audio_port *port) const
4624{
Eric Laurent84c70242014-06-23 08:46:27 -07004625 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004626 mProfile->toAudioPort(port);
4627 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004628 toAudioPortConfig(&port->active_config);
4629 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004630 port->ext.mix.handle = mIoHandle;
4631 port->ext.mix.latency_class =
4632 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4633}
Eric Laurente552edb2014-03-10 17:42:56 -07004634
Eric Laurente0720872014-03-11 09:30:41 -07004635status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004636{
4637 const size_t SIZE = 256;
4638 char buffer[SIZE];
4639 String8 result;
4640
4641 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4642 result.append(buffer);
4643 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4644 result.append(buffer);
4645 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4646 result.append(buffer);
4647 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4648 result.append(buffer);
4649 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4650 result.append(buffer);
4651 snprintf(buffer, SIZE, " Devices %08x\n", device());
4652 result.append(buffer);
4653 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4654 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004655 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4656 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4657 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004658 result.append(buffer);
4659 }
4660 write(fd, result.string(), result.size());
4661
4662 return NO_ERROR;
4663}
4664
4665// --- AudioInputDescriptor class implementation
4666
Eric Laurent1c333e22014-05-20 10:48:17 -07004667AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004668 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004669 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004670 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004671{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004672 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004673 mAudioPort = profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004674 mSamplingRate = profile->mSamplingRates[0];
4675 mFormat = profile->mFormats[0];
4676 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004677 if (profile->mGains.size() > 0) {
4678 profile->mGains[0]->getDefaultConfig(&mGain);
4679 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004680 } else {
4681 mSamplingRate = 0;
4682 mFormat = AUDIO_FORMAT_DEFAULT;
4683 mChannelMask = 0;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004684 }
Eric Laurente552edb2014-03-10 17:42:56 -07004685}
4686
Eric Laurent1c333e22014-05-20 10:48:17 -07004687void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 struct audio_port_config *dstConfig,
4689 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004690{
Eric Laurent84c70242014-06-23 08:46:27 -07004691 ALOG_ASSERT(mProfile != 0,
4692 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004693 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4694 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4695 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004696 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004697 }
4698
4699 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4700
Eric Laurent6a94d692014-05-20 11:18:06 -07004701 dstConfig->id = mId;
4702 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4703 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004704 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4705 dstConfig->ext.mix.handle = mIoHandle;
4706 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004707}
4708
4709void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4710 struct audio_port *port) const
4711{
Eric Laurent84c70242014-06-23 08:46:27 -07004712 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4713
Eric Laurent1c333e22014-05-20 10:48:17 -07004714 mProfile->toAudioPort(port);
4715 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004716 toAudioPortConfig(&port->active_config);
4717 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004718 port->ext.mix.handle = mIoHandle;
4719 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4720}
4721
Eric Laurente0720872014-03-11 09:30:41 -07004722status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004723{
4724 const size_t SIZE = 256;
4725 char buffer[SIZE];
4726 String8 result;
4727
4728 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4729 result.append(buffer);
4730 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4731 result.append(buffer);
4732 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4733 result.append(buffer);
4734 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4735 result.append(buffer);
4736 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4737 result.append(buffer);
4738 write(fd, result.string(), result.size());
4739
4740 return NO_ERROR;
4741}
4742
4743// --- StreamDescriptor class implementation
4744
Eric Laurente0720872014-03-11 09:30:41 -07004745AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004746 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4747{
4748 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4749}
4750
Eric Laurente0720872014-03-11 09:30:41 -07004751int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004752{
Eric Laurente0720872014-03-11 09:30:41 -07004753 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004754 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4755 if (mIndexCur.indexOfKey(device) < 0) {
4756 device = AUDIO_DEVICE_OUT_DEFAULT;
4757 }
4758 return mIndexCur.valueFor(device);
4759}
4760
Eric Laurente0720872014-03-11 09:30:41 -07004761void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004762{
4763 const size_t SIZE = 256;
4764 char buffer[SIZE];
4765 String8 result;
4766
4767 snprintf(buffer, SIZE, "%s %02d %02d ",
4768 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4769 result.append(buffer);
4770 for (size_t i = 0; i < mIndexCur.size(); i++) {
4771 snprintf(buffer, SIZE, "%04x : %02d, ",
4772 mIndexCur.keyAt(i),
4773 mIndexCur.valueAt(i));
4774 result.append(buffer);
4775 }
4776 result.append("\n");
4777
4778 write(fd, result.string(), result.size());
4779}
4780
4781// --- EffectDescriptor class implementation
4782
Eric Laurente0720872014-03-11 09:30:41 -07004783status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004784{
4785 const size_t SIZE = 256;
4786 char buffer[SIZE];
4787 String8 result;
4788
4789 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4790 result.append(buffer);
4791 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4792 result.append(buffer);
4793 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4794 result.append(buffer);
4795 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4796 result.append(buffer);
4797 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4798 result.append(buffer);
4799 write(fd, result.string(), result.size());
4800
4801 return NO_ERROR;
4802}
4803
Eric Laurent1c333e22014-05-20 10:48:17 -07004804// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004805
Eric Laurente0720872014-03-11 09:30:41 -07004806AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004807 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4808 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004809{
4810}
4811
Eric Laurente0720872014-03-11 09:30:41 -07004812AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004813{
4814 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004815 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004816 }
4817 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004818 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004819 }
4820 free((void *)mName);
4821}
4822
Eric Laurent1afeecb2014-05-14 08:52:28 -07004823status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4824{
4825 cnode *node = root->first_child;
4826
4827 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4828
4829 while (node) {
4830 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4831 profile->loadSamplingRates((char *)node->value);
4832 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4833 profile->loadFormats((char *)node->value);
4834 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4835 profile->loadInChannels((char *)node->value);
4836 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4837 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4838 mDeclaredDevices);
4839 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4840 profile->loadGains(node);
4841 }
4842 node = node->next;
4843 }
4844 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4845 "loadInput() invalid supported devices");
4846 ALOGW_IF(profile->mChannelMasks.size() == 0,
4847 "loadInput() invalid supported channel masks");
4848 ALOGW_IF(profile->mSamplingRates.size() == 0,
4849 "loadInput() invalid supported sampling rates");
4850 ALOGW_IF(profile->mFormats.size() == 0,
4851 "loadInput() invalid supported formats");
4852 if (!profile->mSupportedDevices.isEmpty() &&
4853 (profile->mChannelMasks.size() != 0) &&
4854 (profile->mSamplingRates.size() != 0) &&
4855 (profile->mFormats.size() != 0)) {
4856
4857 ALOGV("loadInput() adding input Supported Devices %04x",
4858 profile->mSupportedDevices.types());
4859
4860 mInputProfiles.add(profile);
4861 return NO_ERROR;
4862 } else {
4863 return BAD_VALUE;
4864 }
4865}
4866
4867status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4868{
4869 cnode *node = root->first_child;
4870
4871 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4872
4873 while (node) {
4874 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4875 profile->loadSamplingRates((char *)node->value);
4876 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4877 profile->loadFormats((char *)node->value);
4878 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4879 profile->loadOutChannels((char *)node->value);
4880 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4881 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4882 mDeclaredDevices);
4883 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4884 profile->mFlags = parseFlagNames((char *)node->value);
4885 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4886 profile->loadGains(node);
4887 }
4888 node = node->next;
4889 }
4890 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4891 "loadOutput() invalid supported devices");
4892 ALOGW_IF(profile->mChannelMasks.size() == 0,
4893 "loadOutput() invalid supported channel masks");
4894 ALOGW_IF(profile->mSamplingRates.size() == 0,
4895 "loadOutput() invalid supported sampling rates");
4896 ALOGW_IF(profile->mFormats.size() == 0,
4897 "loadOutput() invalid supported formats");
4898 if (!profile->mSupportedDevices.isEmpty() &&
4899 (profile->mChannelMasks.size() != 0) &&
4900 (profile->mSamplingRates.size() != 0) &&
4901 (profile->mFormats.size() != 0)) {
4902
4903 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4904 profile->mSupportedDevices.types(), profile->mFlags);
4905
4906 mOutputProfiles.add(profile);
4907 return NO_ERROR;
4908 } else {
4909 return BAD_VALUE;
4910 }
4911}
4912
4913status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4914{
4915 cnode *node = root->first_child;
4916
4917 audio_devices_t type = AUDIO_DEVICE_NONE;
4918 while (node) {
4919 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4920 type = parseDeviceNames((char *)node->value);
4921 break;
4922 }
4923 node = node->next;
4924 }
4925 if (type == AUDIO_DEVICE_NONE ||
4926 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4927 ALOGW("loadDevice() bad type %08x", type);
4928 return BAD_VALUE;
4929 }
4930 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4931 deviceDesc->mModule = this;
4932
4933 node = root->first_child;
4934 while (node) {
4935 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4936 deviceDesc->mAddress = String8((char *)node->value);
4937 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4938 if (audio_is_input_device(type)) {
4939 deviceDesc->loadInChannels((char *)node->value);
4940 } else {
4941 deviceDesc->loadOutChannels((char *)node->value);
4942 }
4943 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4944 deviceDesc->loadGains(node);
4945 }
4946 node = node->next;
4947 }
4948
4949 ALOGV("loadDevice() adding device name %s type %08x address %s",
4950 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4951
4952 mDeclaredDevices.add(deviceDesc);
4953
4954 return NO_ERROR;
4955}
4956
Eric Laurente0720872014-03-11 09:30:41 -07004957void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004958{
4959 const size_t SIZE = 256;
4960 char buffer[SIZE];
4961 String8 result;
4962
4963 snprintf(buffer, SIZE, " - name: %s\n", mName);
4964 result.append(buffer);
4965 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4966 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07004967 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
4968 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07004969 write(fd, result.string(), result.size());
4970 if (mOutputProfiles.size()) {
4971 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4972 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004973 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004974 write(fd, buffer, strlen(buffer));
4975 mOutputProfiles[i]->dump(fd);
4976 }
4977 }
4978 if (mInputProfiles.size()) {
4979 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4980 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004981 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004982 write(fd, buffer, strlen(buffer));
4983 mInputProfiles[i]->dump(fd);
4984 }
4985 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07004986 if (mDeclaredDevices.size()) {
4987 write(fd, " - devices:\n", strlen(" - devices:\n"));
4988 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
4989 mDeclaredDevices[i]->dump(fd, 4, i);
4990 }
4991 }
Eric Laurente552edb2014-03-10 17:42:56 -07004992}
4993
Eric Laurent1c333e22014-05-20 10:48:17 -07004994// --- AudioPort class implementation
4995
Eric Laurenta121f902014-06-03 13:32:54 -07004996
4997AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
4998 audio_port_role_t role, const sp<HwModule>& module) :
4999 mName(name), mType(type), mRole(role), mModule(module)
5000{
5001 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5002 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5003}
5004
Eric Laurent1c333e22014-05-20 10:48:17 -07005005void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5006{
5007 port->role = mRole;
5008 port->type = mType;
5009 unsigned int i;
5010 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5011 port->sample_rates[i] = mSamplingRates[i];
5012 }
5013 port->num_sample_rates = i;
5014 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5015 port->channel_masks[i] = mChannelMasks[i];
5016 }
5017 port->num_channel_masks = i;
5018 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5019 port->formats[i] = mFormats[i];
5020 }
5021 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005022
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005023 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005024
5025 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5026 port->gains[i] = mGains[i]->mGain;
5027 }
5028 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005029}
5030
5031
5032void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5033{
5034 char *str = strtok(name, "|");
5035
5036 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5037 // rates should be read from the output stream after it is opened for the first time
5038 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5039 mSamplingRates.add(0);
5040 return;
5041 }
5042
5043 while (str != NULL) {
5044 uint32_t rate = atoi(str);
5045 if (rate != 0) {
5046 ALOGV("loadSamplingRates() adding rate %d", rate);
5047 mSamplingRates.add(rate);
5048 }
5049 str = strtok(NULL, "|");
5050 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005051}
5052
5053void AudioPolicyManager::AudioPort::loadFormats(char *name)
5054{
5055 char *str = strtok(name, "|");
5056
5057 // by convention, "0' in the first entry in mFormats indicates the supported formats
5058 // should be read from the output stream after it is opened for the first time
5059 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5060 mFormats.add(AUDIO_FORMAT_DEFAULT);
5061 return;
5062 }
5063
5064 while (str != NULL) {
5065 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5066 ARRAY_SIZE(sFormatNameToEnumTable),
5067 str);
5068 if (format != AUDIO_FORMAT_DEFAULT) {
5069 mFormats.add(format);
5070 }
5071 str = strtok(NULL, "|");
5072 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005073}
5074
5075void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5076{
5077 const char *str = strtok(name, "|");
5078
5079 ALOGV("loadInChannels() %s", name);
5080
5081 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5082 mChannelMasks.add(0);
5083 return;
5084 }
5085
5086 while (str != NULL) {
5087 audio_channel_mask_t channelMask =
5088 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5089 ARRAY_SIZE(sInChannelsNameToEnumTable),
5090 str);
5091 if (channelMask != 0) {
5092 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5093 mChannelMasks.add(channelMask);
5094 }
5095 str = strtok(NULL, "|");
5096 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005097}
5098
5099void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5100{
5101 const char *str = strtok(name, "|");
5102
5103 ALOGV("loadOutChannels() %s", name);
5104
5105 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5106 // masks should be read from the output stream after it is opened for the first time
5107 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5108 mChannelMasks.add(0);
5109 return;
5110 }
5111
5112 while (str != NULL) {
5113 audio_channel_mask_t channelMask =
5114 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5115 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5116 str);
5117 if (channelMask != 0) {
5118 mChannelMasks.add(channelMask);
5119 }
5120 str = strtok(NULL, "|");
5121 }
5122 return;
5123}
5124
Eric Laurent1afeecb2014-05-14 08:52:28 -07005125audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5126{
5127 const char *str = strtok(name, "|");
5128
5129 ALOGV("loadGainMode() %s", name);
5130 audio_gain_mode_t mode = 0;
5131 while (str != NULL) {
5132 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5133 ARRAY_SIZE(sGainModeNameToEnumTable),
5134 str);
5135 str = strtok(NULL, "|");
5136 }
5137 return mode;
5138}
5139
Eric Laurenta121f902014-06-03 13:32:54 -07005140void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005141{
5142 cnode *node = root->first_child;
5143
Eric Laurenta121f902014-06-03 13:32:54 -07005144 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005145
5146 while (node) {
5147 if (strcmp(node->name, GAIN_MODE) == 0) {
5148 gain->mGain.mode = loadGainMode((char *)node->value);
5149 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005150 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005151 gain->mGain.channel_mask =
5152 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5153 ARRAY_SIZE(sInChannelsNameToEnumTable),
5154 (char *)node->value);
5155 } else {
5156 gain->mGain.channel_mask =
5157 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5158 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5159 (char *)node->value);
5160 }
5161 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5162 gain->mGain.min_value = atoi((char *)node->value);
5163 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5164 gain->mGain.max_value = atoi((char *)node->value);
5165 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5166 gain->mGain.default_value = atoi((char *)node->value);
5167 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5168 gain->mGain.step_value = atoi((char *)node->value);
5169 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5170 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5171 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5172 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5173 }
5174 node = node->next;
5175 }
5176
5177 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5178 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5179
5180 if (gain->mGain.mode == 0) {
5181 return;
5182 }
5183 mGains.add(gain);
5184}
5185
5186void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5187{
5188 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005189 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005190 while (node) {
5191 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005192 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005193 node = node->next;
5194 }
5195}
5196
Eric Laurenta121f902014-06-03 13:32:54 -07005197status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const
5198{
5199 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5200 if (mSamplingRates[i] == samplingRate) {
5201 return NO_ERROR;
5202 }
5203 }
5204 return BAD_VALUE;
5205}
5206
5207status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const
5208{
5209 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5210 if (mChannelMasks[i] == channelMask) {
5211 return NO_ERROR;
5212 }
5213 }
5214 return BAD_VALUE;
5215}
5216
5217status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5218{
5219 for (size_t i = 0; i < mFormats.size(); i ++) {
5220 if (mFormats[i] == format) {
5221 return NO_ERROR;
5222 }
5223 }
5224 return BAD_VALUE;
5225}
5226
5227status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5228 int index) const
5229{
5230 if (index < 0 || (size_t)index >= mGains.size()) {
5231 return BAD_VALUE;
5232 }
5233 return mGains[index]->checkConfig(gainConfig);
5234}
5235
Eric Laurent1afeecb2014-05-14 08:52:28 -07005236void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5237{
5238 const size_t SIZE = 256;
5239 char buffer[SIZE];
5240 String8 result;
5241
5242 if (mName.size() != 0) {
5243 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5244 result.append(buffer);
5245 }
5246
5247 if (mSamplingRates.size() != 0) {
5248 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5249 result.append(buffer);
5250 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5251 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5252 result.append(buffer);
5253 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5254 }
5255 result.append("\n");
5256 }
5257
5258 if (mChannelMasks.size() != 0) {
5259 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5260 result.append(buffer);
5261 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5262 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5263 result.append(buffer);
5264 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5265 }
5266 result.append("\n");
5267 }
5268
5269 if (mFormats.size() != 0) {
5270 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5271 result.append(buffer);
5272 for (size_t i = 0; i < mFormats.size(); i++) {
5273 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5274 ARRAY_SIZE(sFormatNameToEnumTable),
5275 mFormats[i]));
5276 result.append(buffer);
5277 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5278 }
5279 result.append("\n");
5280 }
5281 write(fd, result.string(), result.size());
5282 if (mGains.size() != 0) {
5283 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5284 write(fd, buffer, strlen(buffer) + 1);
5285 result.append(buffer);
5286 for (size_t i = 0; i < mGains.size(); i++) {
5287 mGains[i]->dump(fd, spaces + 2, i);
5288 }
5289 }
5290}
5291
5292// --- AudioGain class implementation
5293
Eric Laurenta121f902014-06-03 13:32:54 -07005294AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005295{
Eric Laurenta121f902014-06-03 13:32:54 -07005296 mIndex = index;
5297 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005298 memset(&mGain, 0, sizeof(struct audio_gain));
5299}
5300
Eric Laurenta121f902014-06-03 13:32:54 -07005301void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5302{
5303 config->index = mIndex;
5304 config->mode = mGain.mode;
5305 config->channel_mask = mGain.channel_mask;
5306 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5307 config->values[0] = mGain.default_value;
5308 } else {
5309 uint32_t numValues;
5310 if (mUseInChannelMask) {
5311 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5312 } else {
5313 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5314 }
5315 for (size_t i = 0; i < numValues; i++) {
5316 config->values[i] = mGain.default_value;
5317 }
5318 }
5319 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5320 config->ramp_duration_ms = mGain.min_ramp_ms;
5321 }
5322}
5323
5324status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5325{
5326 if ((config->mode & ~mGain.mode) != 0) {
5327 return BAD_VALUE;
5328 }
5329 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5330 if ((config->values[0] < mGain.min_value) ||
5331 (config->values[0] > mGain.max_value)) {
5332 return BAD_VALUE;
5333 }
5334 } else {
5335 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5336 return BAD_VALUE;
5337 }
5338 uint32_t numValues;
5339 if (mUseInChannelMask) {
5340 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5341 } else {
5342 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5343 }
5344 for (size_t i = 0; i < numValues; i++) {
5345 if ((config->values[i] < mGain.min_value) ||
5346 (config->values[i] > mGain.max_value)) {
5347 return BAD_VALUE;
5348 }
5349 }
5350 }
5351 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5352 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5353 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5354 return BAD_VALUE;
5355 }
5356 }
5357 return NO_ERROR;
5358}
5359
Eric Laurent1afeecb2014-05-14 08:52:28 -07005360void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5361{
5362 const size_t SIZE = 256;
5363 char buffer[SIZE];
5364 String8 result;
5365
5366 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5367 result.append(buffer);
5368 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5369 result.append(buffer);
5370 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5371 result.append(buffer);
5372 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5373 result.append(buffer);
5374 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5375 result.append(buffer);
5376 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5377 result.append(buffer);
5378 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5379 result.append(buffer);
5380 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5381 result.append(buffer);
5382 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5383 result.append(buffer);
5384
5385 write(fd, result.string(), result.size());
5386}
5387
Eric Laurent1f2f2232014-06-02 12:01:23 -07005388// --- AudioPortConfig class implementation
5389
5390AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5391{
5392 mSamplingRate = 0;
5393 mChannelMask = AUDIO_CHANNEL_NONE;
5394 mFormat = AUDIO_FORMAT_INVALID;
5395 mGain.index = -1;
5396}
5397
Eric Laurenta121f902014-06-03 13:32:54 -07005398status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5399 const struct audio_port_config *config,
5400 struct audio_port_config *backupConfig)
5401{
5402 struct audio_port_config localBackupConfig;
5403 status_t status = NO_ERROR;
5404
5405 localBackupConfig.config_mask = config->config_mask;
5406 toAudioPortConfig(&localBackupConfig);
5407
5408 if (mAudioPort == 0) {
5409 status = NO_INIT;
5410 goto exit;
5411 }
5412 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5413 status = mAudioPort->checkSamplingRate(config->sample_rate);
5414 if (status != NO_ERROR) {
5415 goto exit;
5416 }
5417 mSamplingRate = config->sample_rate;
5418 }
5419 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5420 status = mAudioPort->checkChannelMask(config->channel_mask);
5421 if (status != NO_ERROR) {
5422 goto exit;
5423 }
5424 mChannelMask = config->channel_mask;
5425 }
5426 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5427 status = mAudioPort->checkFormat(config->format);
5428 if (status != NO_ERROR) {
5429 goto exit;
5430 }
5431 mFormat = config->format;
5432 }
5433 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5434 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5435 if (status != NO_ERROR) {
5436 goto exit;
5437 }
5438 mGain = config->gain;
5439 }
5440
5441exit:
5442 if (status != NO_ERROR) {
5443 applyAudioPortConfig(&localBackupConfig);
5444 }
5445 if (backupConfig != NULL) {
5446 *backupConfig = localBackupConfig;
5447 }
5448 return status;
5449}
5450
Eric Laurent1f2f2232014-06-02 12:01:23 -07005451void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5452 struct audio_port_config *dstConfig,
5453 const struct audio_port_config *srcConfig) const
5454{
5455 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5456 dstConfig->sample_rate = mSamplingRate;
5457 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5458 dstConfig->sample_rate = srcConfig->sample_rate;
5459 }
5460 } else {
5461 dstConfig->sample_rate = 0;
5462 }
5463 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5464 dstConfig->channel_mask = mChannelMask;
5465 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5466 dstConfig->channel_mask = srcConfig->channel_mask;
5467 }
5468 } else {
5469 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5470 }
5471 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5472 dstConfig->format = mFormat;
5473 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5474 dstConfig->format = srcConfig->format;
5475 }
5476 } else {
5477 dstConfig->format = AUDIO_FORMAT_INVALID;
5478 }
5479 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5480 dstConfig->gain = mGain;
5481 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5482 dstConfig->gain = srcConfig->gain;
5483 }
5484 } else {
5485 dstConfig->gain.index = -1;
5486 }
5487 if (dstConfig->gain.index != -1) {
5488 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5489 } else {
5490 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5491 }
5492}
5493
Eric Laurent1c333e22014-05-20 10:48:17 -07005494// --- IOProfile class implementation
5495
Eric Laurent1afeecb2014-05-14 08:52:28 -07005496AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005497 const sp<HwModule>& module)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005498 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005499{
5500}
5501
Eric Laurente0720872014-03-11 09:30:41 -07005502AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005503{
5504}
5505
5506// checks if the IO profile is compatible with specified parameters.
5507// Sampling rate, format and channel mask must be specified in order to
5508// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005509bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005510 uint32_t samplingRate,
5511 audio_format_t format,
5512 audio_channel_mask_t channelMask,
5513 audio_output_flags_t flags) const
5514{
5515 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5516 return false;
5517 }
5518
Eric Laurent3a4311c2014-03-17 12:00:47 -07005519 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005520 return false;
5521 }
5522 if ((mFlags & flags) != flags) {
5523 return false;
5524 }
Eric Laurenta121f902014-06-03 13:32:54 -07005525 if (checkSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005526 return false;
5527 }
Eric Laurenta121f902014-06-03 13:32:54 -07005528 if (checkChannelMask(channelMask) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005529 return false;
5530 }
Eric Laurenta121f902014-06-03 13:32:54 -07005531 if (checkFormat(format) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005532 return false;
5533 }
5534 return true;
5535}
5536
Eric Laurente0720872014-03-11 09:30:41 -07005537void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005538{
5539 const size_t SIZE = 256;
5540 char buffer[SIZE];
5541 String8 result;
5542
Eric Laurent1afeecb2014-05-14 08:52:28 -07005543 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005544
Eric Laurente552edb2014-03-10 17:42:56 -07005545 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5546 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005547 snprintf(buffer, SIZE, " - devices:\n");
5548 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005549 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005550 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5551 mSupportedDevices[i]->dump(fd, 6, i);
5552 }
Eric Laurente552edb2014-03-10 17:42:56 -07005553}
5554
Eric Laurentd4692962014-05-05 18:13:44 -07005555void AudioPolicyManager::IOProfile::log()
5556{
5557 const size_t SIZE = 256;
5558 char buffer[SIZE];
5559 String8 result;
5560
5561 ALOGV(" - sampling rates: ");
5562 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5563 ALOGV(" %d", mSamplingRates[i]);
5564 }
5565
5566 ALOGV(" - channel masks: ");
5567 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5568 ALOGV(" 0x%04x", mChannelMasks[i]);
5569 }
5570
5571 ALOGV(" - formats: ");
5572 for (size_t i = 0; i < mFormats.size(); i++) {
5573 ALOGV(" 0x%08x", mFormats[i]);
5574 }
5575
5576 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5577 ALOGV(" - flags: 0x%04x\n", mFlags);
5578}
5579
5580
Eric Laurent3a4311c2014-03-17 12:00:47 -07005581// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005582
Eric Laurent1f2f2232014-06-02 12:01:23 -07005583
5584AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5585 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5586 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5587 AUDIO_PORT_ROLE_SOURCE,
5588 NULL),
5589 mDeviceType(type), mAddress(""),
5590 mChannelMask(AUDIO_CHANNEL_NONE), mId(0)
5591{
5592 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005593 if (mGains.size() > 0) {
5594 mGains[0]->getDefaultConfig(&mGain);
5595 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005596}
5597
Eric Laurent3a4311c2014-03-17 12:00:47 -07005598bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005599{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005600 // Devices are considered equal if they:
5601 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5602 // - have the same address or one device does not specify the address
5603 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005604 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005605 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005606 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005607 mChannelMask == other->mChannelMask);
5608}
5609
5610void AudioPolicyManager::DeviceVector::refreshTypes()
5611{
Eric Laurent1c333e22014-05-20 10:48:17 -07005612 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005613 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005614 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005615 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005616 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005617}
5618
5619ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5620{
5621 for(size_t i = 0; i < size(); i++) {
5622 if (item->equals(itemAt(i))) {
5623 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005624 }
5625 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005626 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005627}
5628
Eric Laurent3a4311c2014-03-17 12:00:47 -07005629ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005630{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005631 ssize_t ret = indexOf(item);
5632
5633 if (ret < 0) {
5634 ret = SortedVector::add(item);
5635 if (ret >= 0) {
5636 refreshTypes();
5637 }
5638 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005639 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005640 ret = -1;
5641 }
5642 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005643}
5644
Eric Laurent3a4311c2014-03-17 12:00:47 -07005645ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5646{
5647 size_t i;
5648 ssize_t ret = indexOf(item);
5649
5650 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005651 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005652 } else {
5653 ret = SortedVector::removeAt(ret);
5654 if (ret >= 0) {
5655 refreshTypes();
5656 }
5657 }
5658 return ret;
5659}
5660
5661void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5662{
5663 DeviceVector deviceList;
5664
5665 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5666 types &= ~role_bit;
5667
5668 while (types) {
5669 uint32_t i = 31 - __builtin_clz(types);
5670 uint32_t type = 1 << i;
5671 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005672 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005673 }
5674}
5675
Eric Laurent1afeecb2014-05-14 08:52:28 -07005676void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5677 const DeviceVector& declaredDevices)
5678{
5679 char *devName = strtok(name, "|");
5680 while (devName != NULL) {
5681 if (strlen(devName) != 0) {
5682 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5683 ARRAY_SIZE(sDeviceNameToEnumTable),
5684 devName);
5685 if (type != AUDIO_DEVICE_NONE) {
5686 add(new DeviceDescriptor(String8(""), type));
5687 } else {
5688 sp<DeviceDescriptor> deviceDesc =
5689 declaredDevices.getDeviceFromName(String8(devName));
5690 if (deviceDesc != 0) {
5691 add(deviceDesc);
5692 }
5693 }
5694 }
5695 devName = strtok(NULL, "|");
5696 }
5697}
5698
Eric Laurent1c333e22014-05-20 10:48:17 -07005699sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5700 audio_devices_t type, String8 address) const
5701{
5702 sp<DeviceDescriptor> device;
5703 for (size_t i = 0; i < size(); i++) {
5704 if (itemAt(i)->mDeviceType == type) {
5705 device = itemAt(i);
5706 if (itemAt(i)->mAddress = address) {
5707 break;
5708 }
5709 }
5710 }
5711 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5712 type, address.string(), device.get());
5713 return device;
5714}
5715
Eric Laurent6a94d692014-05-20 11:18:06 -07005716sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5717 audio_port_handle_t id) const
5718{
5719 sp<DeviceDescriptor> device;
5720 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005721 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07005722 if (itemAt(i)->mId == id) {
5723 device = itemAt(i);
5724 break;
5725 }
5726 }
5727 return device;
5728}
5729
Eric Laurent1c333e22014-05-20 10:48:17 -07005730AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5731 audio_devices_t type) const
5732{
5733 DeviceVector devices;
5734 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5735 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5736 devices.add(itemAt(i));
5737 type &= ~itemAt(i)->mDeviceType;
5738 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5739 itemAt(i)->mDeviceType, itemAt(i).get());
5740 }
5741 }
5742 return devices;
5743}
5744
Eric Laurent1afeecb2014-05-14 08:52:28 -07005745sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5746 const String8& name) const
5747{
5748 sp<DeviceDescriptor> device;
5749 for (size_t i = 0; i < size(); i++) {
5750 if (itemAt(i)->mName == name) {
5751 device = itemAt(i);
5752 break;
5753 }
5754 }
5755 return device;
5756}
5757
Eric Laurent6a94d692014-05-20 11:18:06 -07005758void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5759 struct audio_port_config *dstConfig,
5760 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005761{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005762 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
5763 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005764 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005765 }
5766
5767 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5768
Eric Laurent6a94d692014-05-20 11:18:06 -07005769 dstConfig->id = mId;
5770 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005771 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005772 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005773 dstConfig->ext.device.type = mDeviceType;
5774 dstConfig->ext.device.hw_module = mModule->mHandle;
5775 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005776}
5777
5778void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5779{
Eric Laurente1715a42014-05-20 11:30:42 -07005780 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07005781 AudioPort::toAudioPort(port);
5782 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005783 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005784 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005785 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005786 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5787}
5788
Eric Laurent1afeecb2014-05-14 08:52:28 -07005789status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005790{
5791 const size_t SIZE = 256;
5792 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005793 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005794
Eric Laurent1afeecb2014-05-14 08:52:28 -07005795 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5796 result.append(buffer);
5797 if (mId != 0) {
5798 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5799 result.append(buffer);
5800 }
5801 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5802 enumToString(sDeviceNameToEnumTable,
5803 ARRAY_SIZE(sDeviceNameToEnumTable),
5804 mDeviceType));
5805 result.append(buffer);
5806 if (mAddress.size() != 0) {
5807 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5808 result.append(buffer);
5809 }
5810 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5811 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5812 result.append(buffer);
5813 }
5814 write(fd, result.string(), result.size());
5815 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005816
5817 return NO_ERROR;
5818}
5819
5820
5821// --- audio_policy.conf file parsing
5822
Eric Laurente0720872014-03-11 09:30:41 -07005823audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005824{
5825 uint32_t flag = 0;
5826
5827 // it is OK to cast name to non const here as we are not going to use it after
5828 // strtok() modifies it
5829 char *flagName = strtok(name, "|");
5830 while (flagName != NULL) {
5831 if (strlen(flagName) != 0) {
5832 flag |= stringToEnum(sFlagNameToEnumTable,
5833 ARRAY_SIZE(sFlagNameToEnumTable),
5834 flagName);
5835 }
5836 flagName = strtok(NULL, "|");
5837 }
5838 //force direct flag if offload flag is set: offloading implies a direct output stream
5839 // and all common behaviors are driven by checking only the direct flag
5840 // this should normally be set appropriately in the policy configuration file
5841 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5842 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5843 }
5844
5845 return (audio_output_flags_t)flag;
5846}
5847
Eric Laurente0720872014-03-11 09:30:41 -07005848audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005849{
5850 uint32_t device = 0;
5851
5852 char *devName = strtok(name, "|");
5853 while (devName != NULL) {
5854 if (strlen(devName) != 0) {
5855 device |= stringToEnum(sDeviceNameToEnumTable,
5856 ARRAY_SIZE(sDeviceNameToEnumTable),
5857 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005858 }
Eric Laurente552edb2014-03-10 17:42:56 -07005859 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005860 }
Eric Laurente552edb2014-03-10 17:42:56 -07005861 return device;
5862}
5863
Eric Laurente0720872014-03-11 09:30:41 -07005864void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005865{
Eric Laurente552edb2014-03-10 17:42:56 -07005866 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005867 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005868 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07005869
Eric Laurent1afeecb2014-05-14 08:52:28 -07005870 node = config_find(root, DEVICES_TAG);
5871 if (node != NULL) {
5872 node = node->first_child;
5873 while (node) {
5874 ALOGV("loadHwModule() loading device %s", node->name);
5875 status_t tmpStatus = module->loadDevice(node);
5876 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5877 status = tmpStatus;
5878 }
5879 node = node->next;
5880 }
5881 }
5882 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005883 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005884 node = node->first_child;
5885 while (node) {
5886 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005887 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005888 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5889 status = tmpStatus;
5890 }
5891 node = node->next;
5892 }
5893 }
5894 node = config_find(root, INPUTS_TAG);
5895 if (node != NULL) {
5896 node = node->first_child;
5897 while (node) {
5898 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005899 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005900 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5901 status = tmpStatus;
5902 }
5903 node = node->next;
5904 }
5905 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005906 loadGlobalConfig(root, module);
5907
Eric Laurente552edb2014-03-10 17:42:56 -07005908 if (status == NO_ERROR) {
5909 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07005910 }
5911}
5912
Eric Laurente0720872014-03-11 09:30:41 -07005913void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005914{
5915 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5916 if (node == NULL) {
5917 return;
5918 }
5919
5920 node = node->first_child;
5921 while (node) {
5922 ALOGV("loadHwModules() loading module %s", node->name);
5923 loadHwModule(node);
5924 node = node->next;
5925 }
5926}
5927
Eric Laurent1f2f2232014-06-02 12:01:23 -07005928void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07005929{
5930 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07005931
Eric Laurente552edb2014-03-10 17:42:56 -07005932 if (node == NULL) {
5933 return;
5934 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005935 DeviceVector declaredDevices;
5936 if (module != NULL) {
5937 declaredDevices = module->mDeclaredDevices;
5938 }
5939
Eric Laurente552edb2014-03-10 17:42:56 -07005940 node = node->first_child;
5941 while (node) {
5942 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005943 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5944 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005945 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5946 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005947 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005948 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005949 ARRAY_SIZE(sDeviceNameToEnumTable),
5950 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005951 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005952 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005953 } else {
5954 ALOGW("loadGlobalConfig() default device not specified");
5955 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005956 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005957 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005958 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5959 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005960 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005961 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5962 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5963 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07005964 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
5965 uint32_t major, minor;
5966 sscanf((char *)node->value, "%u.%u", &major, &minor);
5967 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
5968 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
5969 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07005970 }
5971 node = node->next;
5972 }
5973}
5974
Eric Laurente0720872014-03-11 09:30:41 -07005975status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005976{
5977 cnode *root;
5978 char *data;
5979
5980 data = (char *)load_file(path, NULL);
5981 if (data == NULL) {
5982 return -ENODEV;
5983 }
5984 root = config_node("", "");
5985 config_load(root, data);
5986
Eric Laurente552edb2014-03-10 17:42:56 -07005987 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005988 // legacy audio_policy.conf files have one global_configuration section
5989 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07005990 config_free(root);
5991 free(root);
5992 free(data);
5993
5994 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5995
5996 return NO_ERROR;
5997}
5998
Eric Laurente0720872014-03-11 09:30:41 -07005999void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006000{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006001 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006002 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006003 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6004 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006005 mAvailableOutputDevices.add(mDefaultOutputDevice);
6006 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006007
6008 module = new HwModule("primary");
6009
Eric Laurent1afeecb2014-05-14 08:52:28 -07006010 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006011 profile->mSamplingRates.add(44100);
6012 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6013 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006014 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006015 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6016 module->mOutputProfiles.add(profile);
6017
Eric Laurent1afeecb2014-05-14 08:52:28 -07006018 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006019 profile->mSamplingRates.add(8000);
6020 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6021 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006022 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006023 module->mInputProfiles.add(profile);
6024
6025 mHwModules.add(module);
6026}
6027
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006028audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6029{
6030 // flags to stream type mapping
6031 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6032 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6033 }
6034 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6035 return AUDIO_STREAM_BLUETOOTH_SCO;
6036 }
6037
6038 // usage to stream type mapping
6039 switch (attr->usage) {
6040 case AUDIO_USAGE_MEDIA:
6041 case AUDIO_USAGE_GAME:
6042 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6043 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6044 return AUDIO_STREAM_MUSIC;
6045 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6046 return AUDIO_STREAM_SYSTEM;
6047 case AUDIO_USAGE_VOICE_COMMUNICATION:
6048 return AUDIO_STREAM_VOICE_CALL;
6049
6050 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6051 return AUDIO_STREAM_DTMF;
6052
6053 case AUDIO_USAGE_ALARM:
6054 return AUDIO_STREAM_ALARM;
6055 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6056 return AUDIO_STREAM_RING;
6057
6058 case AUDIO_USAGE_NOTIFICATION:
6059 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6060 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6061 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6062 case AUDIO_USAGE_NOTIFICATION_EVENT:
6063 return AUDIO_STREAM_NOTIFICATION;
6064
6065 case AUDIO_USAGE_UNKNOWN:
6066 default:
6067 return AUDIO_STREAM_MUSIC;
6068 }
6069}
Eric Laurente552edb2014-03-10 17:42:56 -07006070}; // namespace android