blob: bb3bce8a215940dfd20e39fd81a3d30fc0f18840 [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 Jang839e4f32014-06-26 17:23:40 +0900520 config != AUDIO_POLICY_FORCE_NO_BT_A2DP &&
521 config != AUDIO_POLICY_FORCE_SYSTEM_AUDIO_HDMI_ARC &&
522 config != AUDIO_POLICY_FORCE_SYSTEM_AUDIO_SPDIF &&
523 config != AUDIO_POLICY_FORCE_SYSTEM_AUDIO_LINE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700524 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
525 return;
526 }
527 mForceUse[usage] = config;
528 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700529 case AUDIO_POLICY_FORCE_FOR_RECORD:
530 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
531 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700532 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
533 return;
534 }
535 mForceUse[usage] = config;
536 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700537 case AUDIO_POLICY_FORCE_FOR_DOCK:
538 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
539 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
540 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
541 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
542 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700543 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
544 }
545 forceVolumeReeval = true;
546 mForceUse[usage] = config;
547 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700548 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
549 if (config != AUDIO_POLICY_FORCE_NONE &&
550 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700551 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
552 }
553 forceVolumeReeval = true;
554 mForceUse[usage] = config;
555 break;
556 default:
557 ALOGW("setForceUse() invalid usage %d", usage);
558 break;
559 }
560
561 // check for device and output changes triggered by new force usage
562 checkA2dpSuspend();
563 checkOutputForAllStrategies();
564 updateDevicesAndOutputs();
565 for (size_t i = 0; i < mOutputs.size(); i++) {
566 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700567 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700568 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
569 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
570 applyStreamVolumes(output, newDevice, 0, true);
571 }
572 }
573
574 audio_io_handle_t activeInput = getActiveInput();
575 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700576 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700577 }
578
579}
580
Eric Laurente0720872014-03-11 09:30:41 -0700581audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700582{
583 return mForceUse[usage];
584}
585
Eric Laurente0720872014-03-11 09:30:41 -0700586void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700587{
588 ALOGV("setSystemProperty() property %s, value %s", property, value);
589}
590
591// Find a direct output profile compatible with the parameters passed, even if the input flags do
592// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700593sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700594 audio_devices_t device,
595 uint32_t samplingRate,
596 audio_format_t format,
597 audio_channel_mask_t channelMask,
598 audio_output_flags_t flags)
599{
600 for (size_t i = 0; i < mHwModules.size(); i++) {
601 if (mHwModules[i]->mHandle == 0) {
602 continue;
603 }
604 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700605 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700606 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700607 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
608 if (profile->isCompatibleProfile(device, samplingRate, format,
609 channelMask,
610 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700611 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700612 }
613 } else {
614 if (profile->isCompatibleProfile(device, samplingRate, format,
615 channelMask,
616 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700617 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700618 }
619 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700620 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
621 return profile;
622 }
Eric Laurente552edb2014-03-10 17:42:56 -0700623 }
624 }
625 return 0;
626}
627
Eric Laurente0720872014-03-11 09:30:41 -0700628audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700629 uint32_t samplingRate,
630 audio_format_t format,
631 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700632 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700633 const audio_offload_info_t *offloadInfo)
634{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700635
Eric Laurent3b73df72014-03-11 09:06:29 -0700636 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700637 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
638 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
639 device, stream, samplingRate, format, channelMask, flags);
640
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700641 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
642 offloadInfo);
643}
644
645audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
646 uint32_t samplingRate,
647 audio_format_t format,
648 audio_channel_mask_t channelMask,
649 audio_output_flags_t flags,
650 const audio_offload_info_t *offloadInfo)
651{
652 if (attr == NULL) {
653 ALOGE("getOutputForAttr() called with NULL audio attributes");
654 return 0;
655 }
656 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
657 attr->usage, attr->content_type, attr->tags);
658
659 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
660 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
661 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
662 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
663 device, samplingRate, format, channelMask, flags);
664
665 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
666 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
667 offloadInfo);
668}
669
670audio_io_handle_t AudioPolicyManager::getOutputForDevice(
671 audio_devices_t device,
672 audio_stream_type_t stream,
673 uint32_t samplingRate,
674 audio_format_t format,
675 audio_channel_mask_t channelMask,
676 audio_output_flags_t flags,
677 const audio_offload_info_t *offloadInfo)
678{
679 audio_io_handle_t output = 0;
680 uint32_t latency = 0;
681
Eric Laurente552edb2014-03-10 17:42:56 -0700682#ifdef AUDIO_POLICY_TEST
683 if (mCurOutput != 0) {
684 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
685 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
686
687 if (mTestOutputs[mCurOutput] == 0) {
688 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700689 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700690 outputDesc->mDevice = mTestDevice;
691 outputDesc->mSamplingRate = mTestSamplingRate;
692 outputDesc->mFormat = mTestFormat;
693 outputDesc->mChannelMask = mTestChannels;
694 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700695 outputDesc->mFlags =
696 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700697 outputDesc->mRefCount[stream] = 0;
698 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
699 &outputDesc->mSamplingRate,
700 &outputDesc->mFormat,
701 &outputDesc->mChannelMask,
702 &outputDesc->mLatency,
703 outputDesc->mFlags,
704 offloadInfo);
705 if (mTestOutputs[mCurOutput]) {
706 AudioParameter outputCmd = AudioParameter();
707 outputCmd.addInt(String8("set_id"),mCurOutput);
708 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
709 addOutput(mTestOutputs[mCurOutput], outputDesc);
710 }
711 }
712 return mTestOutputs[mCurOutput];
713 }
714#endif //AUDIO_POLICY_TEST
715
716 // open a direct output if required by specified parameters
717 //force direct flag if offload flag is set: offloading implies a direct output stream
718 // and all common behaviors are driven by checking only the direct flag
719 // this should normally be set appropriately in the policy configuration file
720 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700721 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700722 }
723
724 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
725 // creating an offloaded track and tearing it down immediately after start when audioflinger
726 // detects there is an active non offloadable effect.
727 // FIXME: We should check the audio session here but we do not have it in this context.
728 // This may prevent offloading in rare situations where effects are left active by apps
729 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700730 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700731 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
732 !isNonOffloadableEffectEnabled()) {
733 profile = getProfileForDirectOutput(device,
734 samplingRate,
735 format,
736 channelMask,
737 (audio_output_flags_t)flags);
738 }
739
Eric Laurent1c333e22014-05-20 10:48:17 -0700740 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700741 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700742
743 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700744 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700745 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
746 outputDesc = desc;
747 // reuse direct output if currently open and configured with same parameters
748 if ((samplingRate == outputDesc->mSamplingRate) &&
749 (format == outputDesc->mFormat) &&
750 (channelMask == outputDesc->mChannelMask)) {
751 outputDesc->mDirectOpenCount++;
752 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
753 return mOutputs.keyAt(i);
754 }
755 }
756 }
757 // close direct output if currently open and configured with different parameters
758 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700759 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700760 }
761 outputDesc = new AudioOutputDescriptor(profile);
762 outputDesc->mDevice = device;
763 outputDesc->mSamplingRate = samplingRate;
764 outputDesc->mFormat = format;
765 outputDesc->mChannelMask = channelMask;
766 outputDesc->mLatency = 0;
767 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
768 outputDesc->mRefCount[stream] = 0;
769 outputDesc->mStopTime[stream] = 0;
770 outputDesc->mDirectOpenCount = 1;
771 output = mpClientInterface->openOutput(profile->mModule->mHandle,
772 &outputDesc->mDevice,
773 &outputDesc->mSamplingRate,
774 &outputDesc->mFormat,
775 &outputDesc->mChannelMask,
776 &outputDesc->mLatency,
777 outputDesc->mFlags,
778 offloadInfo);
779
780 // only accept an output with the requested parameters
781 if (output == 0 ||
782 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
783 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
784 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
785 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
786 "format %d %d, channelMask %04x %04x", output, samplingRate,
787 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
788 outputDesc->mChannelMask);
789 if (output != 0) {
790 mpClientInterface->closeOutput(output);
791 }
Eric Laurente552edb2014-03-10 17:42:56 -0700792 return 0;
793 }
794 audio_io_handle_t srcOutput = getOutputForEffect();
795 addOutput(output, outputDesc);
796 audio_io_handle_t dstOutput = getOutputForEffect();
797 if (dstOutput == output) {
798 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
799 }
800 mPreviousOutputs = mOutputs;
801 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700802 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700803 return output;
804 }
805
806 // ignoring channel mask due to downmix capability in mixer
807
808 // open a non direct output
809
810 // for non direct outputs, only PCM is supported
811 if (audio_is_linear_pcm(format)) {
812 // get which output is suitable for the specified stream. The actual
813 // routing change will happen when startOutput() will be called
814 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
815
816 output = selectOutput(outputs, flags);
817 }
818 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
819 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
820
821 ALOGV("getOutput() returns output %d", output);
822
823 return output;
824}
825
Eric Laurente0720872014-03-11 09:30:41 -0700826audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700827 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700828{
829 // select one output among several that provide a path to a particular device or set of
830 // devices (the list was previously build by getOutputsForDevice()).
831 // The priority is as follows:
832 // 1: the output with the highest number of requested policy flags
833 // 2: the primary output
834 // 3: the first output in the list
835
836 if (outputs.size() == 0) {
837 return 0;
838 }
839 if (outputs.size() == 1) {
840 return outputs[0];
841 }
842
843 int maxCommonFlags = 0;
844 audio_io_handle_t outputFlags = 0;
845 audio_io_handle_t outputPrimary = 0;
846
847 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700848 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700849 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700850 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700851 if (commonFlags > maxCommonFlags) {
852 outputFlags = outputs[i];
853 maxCommonFlags = commonFlags;
854 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
855 }
856 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
857 outputPrimary = outputs[i];
858 }
859 }
860 }
861
862 if (outputFlags != 0) {
863 return outputFlags;
864 }
865 if (outputPrimary != 0) {
866 return outputPrimary;
867 }
868
869 return outputs[0];
870}
871
Eric Laurente0720872014-03-11 09:30:41 -0700872status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700873 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700874 int session)
875{
876 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
877 ssize_t index = mOutputs.indexOfKey(output);
878 if (index < 0) {
879 ALOGW("startOutput() unknown output %d", output);
880 return BAD_VALUE;
881 }
882
Eric Laurent1f2f2232014-06-02 12:01:23 -0700883 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700884
885 // increment usage count for this stream on the requested output:
886 // NOTE that the usage count is the same for duplicated output and hardware output which is
887 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
888 outputDesc->changeRefCount(stream, 1);
889
890 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700891 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700892 routing_strategy strategy = getStrategy(stream);
893 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
894 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
895 uint32_t waitMs = 0;
896 bool force = false;
897 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700898 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700899 if (desc != outputDesc) {
900 // force a device change if any other output is managed by the same hw
901 // module and has a current device selection that differs from selected device.
902 // In this case, the audio HAL must receive the new device selection so that it can
903 // change the device currently selected by the other active output.
904 if (outputDesc->sharesHwModuleWith(desc) &&
905 desc->device() != newDevice) {
906 force = true;
907 }
908 // wait for audio on other active outputs to be presented when starting
909 // a notification so that audio focus effect can propagate.
910 uint32_t latency = desc->latency();
911 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
912 waitMs = latency;
913 }
914 }
915 }
916 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
917
918 // handle special case for sonification while in call
919 if (isInCall()) {
920 handleIncallSonification(stream, true, false);
921 }
922
923 // apply volume rules for current stream and device if necessary
924 checkAndSetVolume(stream,
925 mStreams[stream].getVolumeIndex(newDevice),
926 output,
927 newDevice);
928
929 // update the outputs if starting an output with a stream that can affect notification
930 // routing
931 handleNotificationRoutingForStream(stream);
932 if (waitMs > muteWaitMs) {
933 usleep((waitMs - muteWaitMs) * 2 * 1000);
934 }
935 }
936 return NO_ERROR;
937}
938
939
Eric Laurente0720872014-03-11 09:30:41 -0700940status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700941 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700942 int session)
943{
944 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
945 ssize_t index = mOutputs.indexOfKey(output);
946 if (index < 0) {
947 ALOGW("stopOutput() unknown output %d", output);
948 return BAD_VALUE;
949 }
950
Eric Laurent1f2f2232014-06-02 12:01:23 -0700951 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700952
953 // handle special case for sonification while in call
954 if (isInCall()) {
955 handleIncallSonification(stream, false, false);
956 }
957
958 if (outputDesc->mRefCount[stream] > 0) {
959 // decrement usage count of this stream on the output
960 outputDesc->changeRefCount(stream, -1);
961 // store time at which the stream was stopped - see isStreamActive()
962 if (outputDesc->mRefCount[stream] == 0) {
963 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700964 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700965 // delay the device switch by twice the latency because stopOutput() is executed when
966 // the track stop() command is received and at that time the audio track buffer can
967 // still contain data that needs to be drained. The latency only covers the audio HAL
968 // and kernel buffers. Also the latency does not always include additional delay in the
969 // audio path (audio DSP, CODEC ...)
970 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
971
972 // force restoring the device selection on other active outputs if it differs from the
973 // one being selected for this output
974 for (size_t i = 0; i < mOutputs.size(); i++) {
975 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700976 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700977 if (curOutput != output &&
978 desc->isActive() &&
979 outputDesc->sharesHwModuleWith(desc) &&
980 (newDevice != desc->device())) {
981 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700982 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700983 true,
984 outputDesc->mLatency*2);
985 }
986 }
987 // update the outputs if stopping one with a stream that can affect notification routing
988 handleNotificationRoutingForStream(stream);
989 }
990 return NO_ERROR;
991 } else {
992 ALOGW("stopOutput() refcount is already 0 for output %d", output);
993 return INVALID_OPERATION;
994 }
995}
996
Eric Laurente0720872014-03-11 09:30:41 -0700997void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700998{
999 ALOGV("releaseOutput() %d", output);
1000 ssize_t index = mOutputs.indexOfKey(output);
1001 if (index < 0) {
1002 ALOGW("releaseOutput() releasing unknown output %d", output);
1003 return;
1004 }
1005
1006#ifdef AUDIO_POLICY_TEST
1007 int testIndex = testOutputIndex(output);
1008 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001009 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001010 if (outputDesc->isActive()) {
1011 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001012 mOutputs.removeItem(output);
1013 mTestOutputs[testIndex] = 0;
1014 }
1015 return;
1016 }
1017#endif //AUDIO_POLICY_TEST
1018
Eric Laurent1f2f2232014-06-02 12:01:23 -07001019 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001020 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001021 if (desc->mDirectOpenCount <= 0) {
1022 ALOGW("releaseOutput() invalid open count %d for output %d",
1023 desc->mDirectOpenCount, output);
1024 return;
1025 }
1026 if (--desc->mDirectOpenCount == 0) {
1027 closeOutput(output);
1028 // If effects where present on the output, audioflinger moved them to the primary
1029 // output by default: move them back to the appropriate output.
1030 audio_io_handle_t dstOutput = getOutputForEffect();
1031 if (dstOutput != mPrimaryOutput) {
1032 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1033 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001034 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001035 }
1036 }
1037}
1038
1039
Eric Laurente0720872014-03-11 09:30:41 -07001040audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001041 uint32_t samplingRate,
1042 audio_format_t format,
1043 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001044 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001045{
1046 audio_io_handle_t input = 0;
1047 audio_devices_t device = getDeviceForInputSource(inputSource);
1048
1049 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1050 inputSource, samplingRate, format, channelMask, acoustics);
1051
1052 if (device == AUDIO_DEVICE_NONE) {
1053 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1054 return 0;
1055 }
1056
1057 // adapt channel selection to input source
1058 switch(inputSource) {
1059 case AUDIO_SOURCE_VOICE_UPLINK:
1060 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1061 break;
1062 case AUDIO_SOURCE_VOICE_DOWNLINK:
1063 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1064 break;
1065 case AUDIO_SOURCE_VOICE_CALL:
1066 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1067 break;
1068 default:
1069 break;
1070 }
1071
Eric Laurent1c333e22014-05-20 10:48:17 -07001072 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001073 samplingRate,
1074 format,
1075 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001076 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001077 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1078 "channelMask %04x",
1079 device, samplingRate, format, channelMask);
1080 return 0;
1081 }
1082
1083 if (profile->mModule->mHandle == 0) {
1084 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1085 return 0;
1086 }
1087
Eric Laurent1f2f2232014-06-02 12:01:23 -07001088 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001089
1090 inputDesc->mInputSource = inputSource;
1091 inputDesc->mDevice = device;
1092 inputDesc->mSamplingRate = samplingRate;
1093 inputDesc->mFormat = format;
1094 inputDesc->mChannelMask = channelMask;
1095 inputDesc->mRefCount = 0;
1096 input = mpClientInterface->openInput(profile->mModule->mHandle,
1097 &inputDesc->mDevice,
1098 &inputDesc->mSamplingRate,
1099 &inputDesc->mFormat,
1100 &inputDesc->mChannelMask);
1101
1102 // only accept input with the exact requested set of parameters
1103 if (input == 0 ||
1104 (samplingRate != inputDesc->mSamplingRate) ||
1105 (format != inputDesc->mFormat) ||
1106 (channelMask != inputDesc->mChannelMask)) {
1107 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1108 samplingRate, format, channelMask);
1109 if (input != 0) {
1110 mpClientInterface->closeInput(input);
1111 }
Eric Laurente552edb2014-03-10 17:42:56 -07001112 return 0;
1113 }
Eric Laurentd4692962014-05-05 18:13:44 -07001114 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001115 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001116 return input;
1117}
1118
Eric Laurente0720872014-03-11 09:30:41 -07001119status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001120{
1121 ALOGV("startInput() input %d", input);
1122 ssize_t index = mInputs.indexOfKey(input);
1123 if (index < 0) {
1124 ALOGW("startInput() unknown input %d", input);
1125 return BAD_VALUE;
1126 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001127 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001128
1129#ifdef AUDIO_POLICY_TEST
1130 if (mTestInput == 0)
1131#endif //AUDIO_POLICY_TEST
1132 {
1133 // refuse 2 active AudioRecord clients at the same time except if the active input
1134 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1135 audio_io_handle_t activeInput = getActiveInput();
1136 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001137 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001138 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1139 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1140 stopInput(activeInput);
1141 releaseInput(activeInput);
1142 } else {
1143 ALOGW("startInput() input %d failed: other input already started", input);
1144 return INVALID_OPERATION;
1145 }
1146 }
1147 }
1148
Eric Laurent1c333e22014-05-20 10:48:17 -07001149 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001150
1151 // automatically enable the remote submix output when input is started
1152 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1153 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001154 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001155 }
1156
Eric Laurente552edb2014-03-10 17:42:56 -07001157 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1158
Eric Laurente552edb2014-03-10 17:42:56 -07001159 inputDesc->mRefCount = 1;
1160 return NO_ERROR;
1161}
1162
Eric Laurente0720872014-03-11 09:30:41 -07001163status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001164{
1165 ALOGV("stopInput() input %d", input);
1166 ssize_t index = mInputs.indexOfKey(input);
1167 if (index < 0) {
1168 ALOGW("stopInput() unknown input %d", input);
1169 return BAD_VALUE;
1170 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001171 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001172
1173 if (inputDesc->mRefCount == 0) {
1174 ALOGW("stopInput() input %d already stopped", input);
1175 return INVALID_OPERATION;
1176 } else {
1177 // automatically disable the remote submix output when input is stopped
1178 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1179 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001180 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001181 }
1182
Eric Laurent1c333e22014-05-20 10:48:17 -07001183 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001184 inputDesc->mRefCount = 0;
1185 return NO_ERROR;
1186 }
1187}
1188
Eric Laurente0720872014-03-11 09:30:41 -07001189void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001190{
1191 ALOGV("releaseInput() %d", input);
1192 ssize_t index = mInputs.indexOfKey(input);
1193 if (index < 0) {
1194 ALOGW("releaseInput() releasing unknown input %d", input);
1195 return;
1196 }
1197 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001198 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001199 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001200 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001201 ALOGV("releaseInput() exit");
1202}
1203
Eric Laurentd4692962014-05-05 18:13:44 -07001204void AudioPolicyManager::closeAllInputs() {
1205 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1206 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1207 }
1208 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001209 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001210}
1211
Eric Laurente0720872014-03-11 09:30:41 -07001212void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001213 int indexMin,
1214 int indexMax)
1215{
1216 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1217 if (indexMin < 0 || indexMin >= indexMax) {
1218 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1219 return;
1220 }
1221 mStreams[stream].mIndexMin = indexMin;
1222 mStreams[stream].mIndexMax = indexMax;
1223}
1224
Eric Laurente0720872014-03-11 09:30:41 -07001225status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001226 int index,
1227 audio_devices_t device)
1228{
1229
1230 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1231 return BAD_VALUE;
1232 }
1233 if (!audio_is_output_device(device)) {
1234 return BAD_VALUE;
1235 }
1236
1237 // Force max volume if stream cannot be muted
1238 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1239
1240 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1241 stream, device, index);
1242
1243 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1244 // clear all device specific values
1245 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1246 mStreams[stream].mIndexCur.clear();
1247 }
1248 mStreams[stream].mIndexCur.add(device, index);
1249
1250 // compute and apply stream volume on all outputs according to connected device
1251 status_t status = NO_ERROR;
1252 for (size_t i = 0; i < mOutputs.size(); i++) {
1253 audio_devices_t curDevice =
1254 getDeviceForVolume(mOutputs.valueAt(i)->device());
1255 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1256 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1257 if (volStatus != NO_ERROR) {
1258 status = volStatus;
1259 }
1260 }
1261 }
1262 return status;
1263}
1264
Eric Laurente0720872014-03-11 09:30:41 -07001265status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001266 int *index,
1267 audio_devices_t device)
1268{
1269 if (index == NULL) {
1270 return BAD_VALUE;
1271 }
1272 if (!audio_is_output_device(device)) {
1273 return BAD_VALUE;
1274 }
1275 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1276 // the strategy the stream belongs to.
1277 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1278 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1279 }
1280 device = getDeviceForVolume(device);
1281
1282 *index = mStreams[stream].getVolumeIndex(device);
1283 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1284 return NO_ERROR;
1285}
1286
Eric Laurente0720872014-03-11 09:30:41 -07001287audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001288 const SortedVector<audio_io_handle_t>& outputs)
1289{
1290 // select one output among several suitable for global effects.
1291 // The priority is as follows:
1292 // 1: An offloaded output. If the effect ends up not being offloadable,
1293 // AudioFlinger will invalidate the track and the offloaded output
1294 // will be closed causing the effect to be moved to a PCM output.
1295 // 2: A deep buffer output
1296 // 3: the first output in the list
1297
1298 if (outputs.size() == 0) {
1299 return 0;
1300 }
1301
1302 audio_io_handle_t outputOffloaded = 0;
1303 audio_io_handle_t outputDeepBuffer = 0;
1304
1305 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001306 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001307 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001308 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1309 outputOffloaded = outputs[i];
1310 }
1311 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1312 outputDeepBuffer = outputs[i];
1313 }
1314 }
1315
1316 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1317 outputOffloaded, outputDeepBuffer);
1318 if (outputOffloaded != 0) {
1319 return outputOffloaded;
1320 }
1321 if (outputDeepBuffer != 0) {
1322 return outputDeepBuffer;
1323 }
1324
1325 return outputs[0];
1326}
1327
Eric Laurente0720872014-03-11 09:30:41 -07001328audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001329{
1330 // apply simple rule where global effects are attached to the same output as MUSIC streams
1331
Eric Laurent3b73df72014-03-11 09:06:29 -07001332 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001333 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1334 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1335
1336 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1337 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1338 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1339
1340 return output;
1341}
1342
Eric Laurente0720872014-03-11 09:30:41 -07001343status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001344 audio_io_handle_t io,
1345 uint32_t strategy,
1346 int session,
1347 int id)
1348{
1349 ssize_t index = mOutputs.indexOfKey(io);
1350 if (index < 0) {
1351 index = mInputs.indexOfKey(io);
1352 if (index < 0) {
1353 ALOGW("registerEffect() unknown io %d", io);
1354 return INVALID_OPERATION;
1355 }
1356 }
1357
1358 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1359 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1360 desc->name, desc->memoryUsage);
1361 return INVALID_OPERATION;
1362 }
1363 mTotalEffectsMemory += desc->memoryUsage;
1364 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1365 desc->name, io, strategy, session, id);
1366 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1367
Eric Laurent1f2f2232014-06-02 12:01:23 -07001368 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1369 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1370 effectDesc->mIo = io;
1371 effectDesc->mStrategy = (routing_strategy)strategy;
1372 effectDesc->mSession = session;
1373 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001374
Eric Laurent1f2f2232014-06-02 12:01:23 -07001375 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001376
1377 return NO_ERROR;
1378}
1379
Eric Laurente0720872014-03-11 09:30:41 -07001380status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001381{
1382 ssize_t index = mEffects.indexOfKey(id);
1383 if (index < 0) {
1384 ALOGW("unregisterEffect() unknown effect ID %d", id);
1385 return INVALID_OPERATION;
1386 }
1387
Eric Laurent1f2f2232014-06-02 12:01:23 -07001388 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001389
Eric Laurent1f2f2232014-06-02 12:01:23 -07001390 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001391
Eric Laurent1f2f2232014-06-02 12:01:23 -07001392 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001393 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001394 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1395 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001396 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001397 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001398 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001399 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001400
1401 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001402
1403 return NO_ERROR;
1404}
1405
Eric Laurente0720872014-03-11 09:30:41 -07001406status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001407{
1408 ssize_t index = mEffects.indexOfKey(id);
1409 if (index < 0) {
1410 ALOGW("unregisterEffect() unknown effect ID %d", id);
1411 return INVALID_OPERATION;
1412 }
1413
1414 return setEffectEnabled(mEffects.valueAt(index), enabled);
1415}
1416
Eric Laurent1f2f2232014-06-02 12:01:23 -07001417status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001418{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001419 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001420 ALOGV("setEffectEnabled(%s) effect already %s",
1421 enabled?"true":"false", enabled?"enabled":"disabled");
1422 return INVALID_OPERATION;
1423 }
1424
1425 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001426 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001427 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001428 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001429 return INVALID_OPERATION;
1430 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001431 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001432 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1433 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001434 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001435 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001436 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1437 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001438 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001439 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001440 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1441 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001442 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001443 return NO_ERROR;
1444}
1445
Eric Laurente0720872014-03-11 09:30:41 -07001446bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001447{
1448 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001449 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1450 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1451 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001452 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001453 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001454 return true;
1455 }
1456 }
1457 return false;
1458}
1459
Eric Laurente0720872014-03-11 09:30:41 -07001460bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001461{
1462 nsecs_t sysTime = systemTime();
1463 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001464 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001465 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001466 return true;
1467 }
1468 }
1469 return false;
1470}
1471
Eric Laurente0720872014-03-11 09:30:41 -07001472bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001473 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001474{
1475 nsecs_t sysTime = systemTime();
1476 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001477 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001478 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001479 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001480 return true;
1481 }
1482 }
1483 return false;
1484}
1485
Eric Laurente0720872014-03-11 09:30:41 -07001486bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001487{
1488 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001489 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001490 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001491 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001492 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1493 && (inputDescriptor->mRefCount > 0)) {
1494 return true;
1495 }
1496 }
1497 return false;
1498}
1499
1500
Eric Laurente0720872014-03-11 09:30:41 -07001501status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001502{
1503 const size_t SIZE = 256;
1504 char buffer[SIZE];
1505 String8 result;
1506
1507 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1508 result.append(buffer);
1509
1510 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1511 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001512 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1513 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001514 snprintf(buffer, SIZE, " Force use for communications %d\n",
1515 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001516 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001517 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001518 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001519 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001520 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001521 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001522 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001523 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001524 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001525
Eric Laurent3a4311c2014-03-17 12:00:47 -07001526 snprintf(buffer, SIZE, " Available output devices:\n");
1527 result.append(buffer);
1528 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001529 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001530 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001531 }
1532 snprintf(buffer, SIZE, "\n Available input devices:\n");
1533 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001534 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001535 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001536 }
Eric Laurente552edb2014-03-10 17:42:56 -07001537
1538 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1539 write(fd, buffer, strlen(buffer));
1540 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001541 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001542 write(fd, buffer, strlen(buffer));
1543 mHwModules[i]->dump(fd);
1544 }
1545
1546 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1547 write(fd, buffer, strlen(buffer));
1548 for (size_t i = 0; i < mOutputs.size(); i++) {
1549 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1550 write(fd, buffer, strlen(buffer));
1551 mOutputs.valueAt(i)->dump(fd);
1552 }
1553
1554 snprintf(buffer, SIZE, "\nInputs dump:\n");
1555 write(fd, buffer, strlen(buffer));
1556 for (size_t i = 0; i < mInputs.size(); i++) {
1557 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1558 write(fd, buffer, strlen(buffer));
1559 mInputs.valueAt(i)->dump(fd);
1560 }
1561
1562 snprintf(buffer, SIZE, "\nStreams dump:\n");
1563 write(fd, buffer, strlen(buffer));
1564 snprintf(buffer, SIZE,
1565 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1566 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001567 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001568 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001569 write(fd, buffer, strlen(buffer));
1570 mStreams[i].dump(fd);
1571 }
1572
1573 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1574 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1575 write(fd, buffer, strlen(buffer));
1576
1577 snprintf(buffer, SIZE, "Registered effects:\n");
1578 write(fd, buffer, strlen(buffer));
1579 for (size_t i = 0; i < mEffects.size(); i++) {
1580 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1581 write(fd, buffer, strlen(buffer));
1582 mEffects.valueAt(i)->dump(fd);
1583 }
1584
1585
1586 return NO_ERROR;
1587}
1588
1589// This function checks for the parameters which can be offloaded.
1590// This can be enhanced depending on the capability of the DSP and policy
1591// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001592bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001593{
1594 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001595 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001596 offloadInfo.sample_rate, offloadInfo.channel_mask,
1597 offloadInfo.format,
1598 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1599 offloadInfo.has_video);
1600
1601 // Check if offload has been disabled
1602 char propValue[PROPERTY_VALUE_MAX];
1603 if (property_get("audio.offload.disable", propValue, "0")) {
1604 if (atoi(propValue) != 0) {
1605 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1606 return false;
1607 }
1608 }
1609
1610 // Check if stream type is music, then only allow offload as of now.
1611 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1612 {
1613 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1614 return false;
1615 }
1616
1617 //TODO: enable audio offloading with video when ready
1618 if (offloadInfo.has_video)
1619 {
1620 ALOGV("isOffloadSupported: has_video == true, returning false");
1621 return false;
1622 }
1623
1624 //If duration is less than minimum value defined in property, return false
1625 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1626 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1627 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1628 return false;
1629 }
1630 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1631 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1632 return false;
1633 }
1634
1635 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1636 // creating an offloaded track and tearing it down immediately after start when audioflinger
1637 // detects there is an active non offloadable effect.
1638 // FIXME: We should check the audio session here but we do not have it in this context.
1639 // This may prevent offloading in rare situations where effects are left active by apps
1640 // in the background.
1641 if (isNonOffloadableEffectEnabled()) {
1642 return false;
1643 }
1644
1645 // See if there is a profile to support this.
1646 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001647 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001648 offloadInfo.sample_rate,
1649 offloadInfo.format,
1650 offloadInfo.channel_mask,
1651 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001652 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1653 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001654}
1655
Eric Laurent6a94d692014-05-20 11:18:06 -07001656status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1657 audio_port_type_t type,
1658 unsigned int *num_ports,
1659 struct audio_port *ports,
1660 unsigned int *generation)
1661{
1662 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1663 generation == NULL) {
1664 return BAD_VALUE;
1665 }
1666 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1667 if (ports == NULL) {
1668 *num_ports = 0;
1669 }
1670
1671 size_t portsWritten = 0;
1672 size_t portsMax = *num_ports;
1673 *num_ports = 0;
1674 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1675 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1676 for (size_t i = 0;
1677 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1678 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1679 }
1680 *num_ports += mAvailableOutputDevices.size();
1681 }
1682 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1683 for (size_t i = 0;
1684 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1685 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1686 }
1687 *num_ports += mAvailableInputDevices.size();
1688 }
1689 }
1690 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1691 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1692 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1693 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1694 }
1695 *num_ports += mInputs.size();
1696 }
1697 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001698 size_t numOutputs = 0;
1699 for (size_t i = 0; i < mOutputs.size(); i++) {
1700 if (!mOutputs[i]->isDuplicated()) {
1701 numOutputs++;
1702 if (portsWritten < portsMax) {
1703 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1704 }
1705 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001706 }
Eric Laurent84c70242014-06-23 08:46:27 -07001707 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001708 }
1709 }
1710 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001711 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001712 return NO_ERROR;
1713}
1714
1715status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1716{
1717 return NO_ERROR;
1718}
1719
Eric Laurent1f2f2232014-06-02 12:01:23 -07001720sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001721 audio_port_handle_t id) const
1722{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001723 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001724 for (size_t i = 0; i < mOutputs.size(); i++) {
1725 outputDesc = mOutputs.valueAt(i);
1726 if (outputDesc->mId == id) {
1727 break;
1728 }
1729 }
1730 return outputDesc;
1731}
1732
Eric Laurent1f2f2232014-06-02 12:01:23 -07001733sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001734 audio_port_handle_t id) const
1735{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001736 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001737 for (size_t i = 0; i < mInputs.size(); i++) {
1738 inputDesc = mInputs.valueAt(i);
1739 if (inputDesc->mId == id) {
1740 break;
1741 }
1742 }
1743 return inputDesc;
1744}
1745
Eric Laurent1f2f2232014-06-02 12:01:23 -07001746sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1747 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001748{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001749 sp <HwModule> module;
1750
Eric Laurent6a94d692014-05-20 11:18:06 -07001751 for (size_t i = 0; i < mHwModules.size(); i++) {
1752 if (mHwModules[i]->mHandle == 0) {
1753 continue;
1754 }
1755 if (audio_is_output_device(device)) {
1756 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1757 {
1758 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1759 return mHwModules[i];
1760 }
1761 }
1762 } else {
1763 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1764 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1765 device & ~AUDIO_DEVICE_BIT_IN) {
1766 return mHwModules[i];
1767 }
1768 }
1769 }
1770 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001771 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001772}
1773
Eric Laurent1f2f2232014-06-02 12:01:23 -07001774sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001775{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001776 sp <HwModule> module;
1777
Eric Laurent1afeecb2014-05-14 08:52:28 -07001778 for (size_t i = 0; i < mHwModules.size(); i++)
1779 {
1780 if (strcmp(mHwModules[i]->mName, name) == 0) {
1781 return mHwModules[i];
1782 }
1783 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001784 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001785}
1786
1787
Eric Laurent6a94d692014-05-20 11:18:06 -07001788status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1789 audio_patch_handle_t *handle,
1790 uid_t uid)
1791{
1792 ALOGV("createAudioPatch()");
1793
1794 if (handle == NULL || patch == NULL) {
1795 return BAD_VALUE;
1796 }
1797 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1798
1799 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1800 return INVALID_OPERATION;
1801 }
1802 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1803 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1804 return INVALID_OPERATION;
1805 }
1806
1807 sp<AudioPatch> patchDesc;
1808 ssize_t index = mAudioPatches.indexOfKey(*handle);
1809
1810 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1811 patch->sinks[0].type);
1812 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1813 patch->sources[0].role,
1814 patch->sources[0].type);
1815
1816 if (index >= 0) {
1817 patchDesc = mAudioPatches.valueAt(index);
1818 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1819 mUidCached, patchDesc->mUid, uid);
1820 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1821 return INVALID_OPERATION;
1822 }
1823 } else {
1824 *handle = 0;
1825 }
1826
1827 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1828 // TODO add support for mix to mix connection
1829 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1830 ALOGV("createAudioPatch() source mix sink not device");
1831 return BAD_VALUE;
1832 }
1833 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001834 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001835 if (outputDesc == NULL) {
1836 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1837 return BAD_VALUE;
1838 }
Eric Laurent84c70242014-06-23 08:46:27 -07001839 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1840 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001841 if (patchDesc != 0) {
1842 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1843 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1844 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1845 return BAD_VALUE;
1846 }
1847 }
1848 sp<DeviceDescriptor> devDesc =
1849 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1850 if (devDesc == 0) {
1851 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1852 return BAD_VALUE;
1853 }
1854
Eric Laurent84c70242014-06-23 08:46:27 -07001855 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001856 patch->sources[0].sample_rate,
1857 patch->sources[0].format,
1858 patch->sources[0].channel_mask,
1859 AUDIO_OUTPUT_FLAG_NONE)) {
1860 return INVALID_OPERATION;
1861 }
1862 // TODO: reconfigure output format and channels here
1863 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001864 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001865 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001866 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001867 true,
1868 0,
1869 handle);
1870 index = mAudioPatches.indexOfKey(*handle);
1871 if (index >= 0) {
1872 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1873 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1874 }
1875 patchDesc = mAudioPatches.valueAt(index);
1876 patchDesc->mUid = uid;
1877 ALOGV("createAudioPatch() success");
1878 } else {
1879 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1880 return INVALID_OPERATION;
1881 }
1882 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1883 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1884 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001885 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001886 if (inputDesc == NULL) {
1887 return BAD_VALUE;
1888 }
1889 if (patchDesc != 0) {
1890 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1891 return BAD_VALUE;
1892 }
1893 }
1894 sp<DeviceDescriptor> devDesc =
1895 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1896 if (devDesc == 0) {
1897 return BAD_VALUE;
1898 }
1899
Eric Laurent84c70242014-06-23 08:46:27 -07001900 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001901 patch->sinks[0].sample_rate,
1902 patch->sinks[0].format,
1903 patch->sinks[0].channel_mask,
1904 AUDIO_OUTPUT_FLAG_NONE)) {
1905 return INVALID_OPERATION;
1906 }
1907 // TODO: reconfigure output format and channels here
1908 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001909 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001910 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001911 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001912 true,
1913 handle);
1914 index = mAudioPatches.indexOfKey(*handle);
1915 if (index >= 0) {
1916 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1917 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1918 }
1919 patchDesc = mAudioPatches.valueAt(index);
1920 patchDesc->mUid = uid;
1921 ALOGV("createAudioPatch() success");
1922 } else {
1923 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1924 return INVALID_OPERATION;
1925 }
1926 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1927 // device to device connection
1928 if (patchDesc != 0) {
1929 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1930 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1931 return BAD_VALUE;
1932 }
1933 }
1934
1935 sp<DeviceDescriptor> srcDeviceDesc =
1936 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1937 sp<DeviceDescriptor> sinkDeviceDesc =
1938 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1939 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1940 return BAD_VALUE;
1941 }
1942 //update source and sink with our own data as the data passed in the patch may
1943 // be incomplete.
1944 struct audio_patch newPatch = *patch;
1945 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1946 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1947
1948 // TODO: add support for devices on different HW modules
1949 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1950 return INVALID_OPERATION;
1951 }
1952 // TODO: check from routing capabilities in config file and other conflicting patches
1953
1954 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1955 if (index >= 0) {
1956 afPatchHandle = patchDesc->mAfPatchHandle;
1957 }
1958
1959 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1960 &afPatchHandle,
1961 0);
1962 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1963 status, afPatchHandle);
1964 if (status == NO_ERROR) {
1965 if (index < 0) {
1966 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1967 &newPatch, uid);
1968 addAudioPatch(patchDesc->mHandle, patchDesc);
1969 } else {
1970 patchDesc->mPatch = newPatch;
1971 }
1972 patchDesc->mAfPatchHandle = afPatchHandle;
1973 *handle = patchDesc->mHandle;
1974 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001975 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001976 } else {
1977 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1978 status);
1979 return INVALID_OPERATION;
1980 }
1981 } else {
1982 return BAD_VALUE;
1983 }
1984 } else {
1985 return BAD_VALUE;
1986 }
1987 return NO_ERROR;
1988}
1989
1990status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1991 uid_t uid)
1992{
1993 ALOGV("releaseAudioPatch() patch %d", handle);
1994
1995 ssize_t index = mAudioPatches.indexOfKey(handle);
1996
1997 if (index < 0) {
1998 return BAD_VALUE;
1999 }
2000 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2001 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2002 mUidCached, patchDesc->mUid, uid);
2003 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2004 return INVALID_OPERATION;
2005 }
2006
2007 struct audio_patch *patch = &patchDesc->mPatch;
2008 patchDesc->mUid = mUidCached;
2009 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002010 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002011 if (outputDesc == NULL) {
2012 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2013 return BAD_VALUE;
2014 }
2015
2016 setOutputDevice(outputDesc->mIoHandle,
2017 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2018 true,
2019 0,
2020 NULL);
2021 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2022 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002023 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002024 if (inputDesc == NULL) {
2025 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2026 return BAD_VALUE;
2027 }
2028 setInputDevice(inputDesc->mIoHandle,
2029 getNewInputDevice(inputDesc->mIoHandle),
2030 true,
2031 NULL);
2032 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2033 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2034 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2035 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2036 status, patchDesc->mAfPatchHandle);
2037 removeAudioPatch(patchDesc->mHandle);
2038 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002039 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002040 } else {
2041 return BAD_VALUE;
2042 }
2043 } else {
2044 return BAD_VALUE;
2045 }
2046 return NO_ERROR;
2047}
2048
2049status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2050 struct audio_patch *patches,
2051 unsigned int *generation)
2052{
2053 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2054 generation == NULL) {
2055 return BAD_VALUE;
2056 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002057 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002058 *num_patches, patches, mAudioPatches.size());
2059 if (patches == NULL) {
2060 *num_patches = 0;
2061 }
2062
2063 size_t patchesWritten = 0;
2064 size_t patchesMax = *num_patches;
2065 for (size_t i = 0;
2066 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2067 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2068 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002069 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002070 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2071 }
2072 *num_patches = mAudioPatches.size();
2073
2074 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002075 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002076 return NO_ERROR;
2077}
2078
Eric Laurente1715a42014-05-20 11:30:42 -07002079status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002080{
Eric Laurente1715a42014-05-20 11:30:42 -07002081 ALOGV("setAudioPortConfig()");
2082
2083 if (config == NULL) {
2084 return BAD_VALUE;
2085 }
2086 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2087 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002088 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2089 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002090 }
2091
Eric Laurenta121f902014-06-03 13:32:54 -07002092 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002093 if (config->type == AUDIO_PORT_TYPE_MIX) {
2094 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002095 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002096 if (outputDesc == NULL) {
2097 return BAD_VALUE;
2098 }
Eric Laurent84c70242014-06-23 08:46:27 -07002099 ALOG_ASSERT(!outputDesc->isDuplicated(),
2100 "setAudioPortConfig() called on duplicated output %d",
2101 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002102 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002103 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002104 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002105 if (inputDesc == NULL) {
2106 return BAD_VALUE;
2107 }
Eric Laurenta121f902014-06-03 13:32:54 -07002108 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002109 } else {
2110 return BAD_VALUE;
2111 }
2112 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2113 sp<DeviceDescriptor> deviceDesc;
2114 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2115 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2116 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2117 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2118 } else {
2119 return BAD_VALUE;
2120 }
2121 if (deviceDesc == NULL) {
2122 return BAD_VALUE;
2123 }
Eric Laurenta121f902014-06-03 13:32:54 -07002124 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002125 } else {
2126 return BAD_VALUE;
2127 }
2128
Eric Laurenta121f902014-06-03 13:32:54 -07002129 struct audio_port_config backupConfig;
2130 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2131 if (status == NO_ERROR) {
2132 struct audio_port_config newConfig;
2133 audioPortConfig->toAudioPortConfig(&newConfig, config);
2134 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002135 }
Eric Laurenta121f902014-06-03 13:32:54 -07002136 if (status != NO_ERROR) {
2137 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002138 }
Eric Laurente1715a42014-05-20 11:30:42 -07002139
2140 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002141}
2142
2143void AudioPolicyManager::clearAudioPatches(uid_t uid)
2144{
2145 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2146 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2147 if (patchDesc->mUid == uid) {
2148 // releaseAudioPatch() removes the patch from mAudioPatches
2149 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2150 i--;
2151 }
2152 }
2153 }
2154}
2155
2156status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2157 const sp<AudioPatch>& patch)
2158{
2159 ssize_t index = mAudioPatches.indexOfKey(handle);
2160
2161 if (index >= 0) {
2162 ALOGW("addAudioPatch() patch %d already in", handle);
2163 return ALREADY_EXISTS;
2164 }
2165 mAudioPatches.add(handle, patch);
2166 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2167 "sink handle %d",
2168 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2169 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2170 return NO_ERROR;
2171}
2172
2173status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2174{
2175 ssize_t index = mAudioPatches.indexOfKey(handle);
2176
2177 if (index < 0) {
2178 ALOGW("removeAudioPatch() patch %d not in", handle);
2179 return ALREADY_EXISTS;
2180 }
2181 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2182 mAudioPatches.valueAt(index)->mAfPatchHandle);
2183 mAudioPatches.removeItemsAt(index);
2184 return NO_ERROR;
2185}
2186
Eric Laurente552edb2014-03-10 17:42:56 -07002187// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002188// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002189// ----------------------------------------------------------------------------
2190
Eric Laurent3a4311c2014-03-17 12:00:47 -07002191uint32_t AudioPolicyManager::nextUniqueId()
2192{
2193 return android_atomic_inc(&mNextUniqueId);
2194}
2195
Eric Laurent6a94d692014-05-20 11:18:06 -07002196uint32_t AudioPolicyManager::nextAudioPortGeneration()
2197{
2198 return android_atomic_inc(&mAudioPortGeneration);
2199}
2200
Eric Laurente0720872014-03-11 09:30:41 -07002201AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002202 :
2203#ifdef AUDIO_POLICY_TEST
2204 Thread(false),
2205#endif //AUDIO_POLICY_TEST
2206 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002207 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002208 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2209 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002210 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002211 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2212 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002213{
Eric Laurent6a94d692014-05-20 11:18:06 -07002214 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002215 mpClientInterface = clientInterface;
2216
Eric Laurent3b73df72014-03-11 09:06:29 -07002217 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2218 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002219 }
2220
Eric Laurent1afeecb2014-05-14 08:52:28 -07002221 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002222 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2223 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2224 ALOGE("could not load audio policy configuration file, setting defaults");
2225 defaultAudioPolicyConfig();
2226 }
2227 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002228 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002229
2230 // must be done after reading the policy
2231 initializeVolumeCurves();
2232
2233 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002234 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2235 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002236 for (size_t i = 0; i < mHwModules.size(); i++) {
2237 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2238 if (mHwModules[i]->mHandle == 0) {
2239 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2240 continue;
2241 }
2242 // open all output streams needed to access attached devices
2243 // except for direct output streams that are only opened when they are actually
2244 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002245 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002246 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2247 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002248 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002249
Eric Laurent3a4311c2014-03-17 12:00:47 -07002250 if (outProfile->mSupportedDevices.isEmpty()) {
2251 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2252 continue;
2253 }
2254
2255 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2256 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002257 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002258 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002259
Eric Laurent1c333e22014-05-20 10:48:17 -07002260 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002261 audio_io_handle_t output = mpClientInterface->openOutput(
2262 outProfile->mModule->mHandle,
2263 &outputDesc->mDevice,
2264 &outputDesc->mSamplingRate,
2265 &outputDesc->mFormat,
2266 &outputDesc->mChannelMask,
2267 &outputDesc->mLatency,
2268 outputDesc->mFlags);
2269 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002270 ALOGW("Cannot open output stream for device %08x on hw module %s",
2271 outputDesc->mDevice,
2272 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002273 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002274 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002275 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002276 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002277 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002278 // give a valid ID to an attached device once confirmed it is reachable
2279 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2280 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002281 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002282 }
2283 }
Eric Laurente552edb2014-03-10 17:42:56 -07002284 if (mPrimaryOutput == 0 &&
2285 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2286 mPrimaryOutput = output;
2287 }
2288 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002289 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002290 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002291 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002292 true);
2293 }
2294 }
2295 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002296 // open input streams needed to access attached devices to validate
2297 // mAvailableInputDevices list
2298 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2299 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002300 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002301
Eric Laurent3a4311c2014-03-17 12:00:47 -07002302 if (inProfile->mSupportedDevices.isEmpty()) {
2303 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2304 continue;
2305 }
2306
2307 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2308 if (profileTypes & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002309 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002310
2311 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002312 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002313 audio_io_handle_t input = mpClientInterface->openInput(
2314 inProfile->mModule->mHandle,
2315 &inputDesc->mDevice,
2316 &inputDesc->mSamplingRate,
2317 &inputDesc->mFormat,
2318 &inputDesc->mChannelMask);
2319
2320 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002321 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002322 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002323 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002324 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002325 // give a valid ID to an attached device once confirmed it is reachable
2326 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2327 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002328 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002329 }
2330 }
2331 mpClientInterface->closeInput(input);
2332 } else {
2333 ALOGW("Cannot open input stream for device %08x on hw module %s",
2334 inputDesc->mDevice,
2335 mHwModules[i]->mName);
2336 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002337 }
2338 }
2339 }
2340 // make sure all attached devices have been allocated a unique ID
2341 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2342 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002343 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002344 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2345 continue;
2346 }
2347 i++;
2348 }
2349 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2350 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002351 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002352 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2353 continue;
2354 }
2355 i++;
2356 }
2357 // make sure default device is reachable
2358 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002359 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002360 }
Eric Laurente552edb2014-03-10 17:42:56 -07002361
2362 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2363
2364 updateDevicesAndOutputs();
2365
2366#ifdef AUDIO_POLICY_TEST
2367 if (mPrimaryOutput != 0) {
2368 AudioParameter outputCmd = AudioParameter();
2369 outputCmd.addInt(String8("set_id"), 0);
2370 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2371
2372 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2373 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002374 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2375 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002376 mTestLatencyMs = 0;
2377 mCurOutput = 0;
2378 mDirectOutput = false;
2379 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2380 mTestOutputs[i] = 0;
2381 }
2382
2383 const size_t SIZE = 256;
2384 char buffer[SIZE];
2385 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2386 run(buffer, ANDROID_PRIORITY_AUDIO);
2387 }
2388#endif //AUDIO_POLICY_TEST
2389}
2390
Eric Laurente0720872014-03-11 09:30:41 -07002391AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002392{
2393#ifdef AUDIO_POLICY_TEST
2394 exit();
2395#endif //AUDIO_POLICY_TEST
2396 for (size_t i = 0; i < mOutputs.size(); i++) {
2397 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002398 }
2399 for (size_t i = 0; i < mInputs.size(); i++) {
2400 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002401 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002402 mAvailableOutputDevices.clear();
2403 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002404 mOutputs.clear();
2405 mInputs.clear();
2406 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002407}
2408
Eric Laurente0720872014-03-11 09:30:41 -07002409status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002410{
2411 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2412}
2413
2414#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002415bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002416{
2417 ALOGV("entering threadLoop()");
2418 while (!exitPending())
2419 {
2420 String8 command;
2421 int valueInt;
2422 String8 value;
2423
2424 Mutex::Autolock _l(mLock);
2425 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2426
2427 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2428 AudioParameter param = AudioParameter(command);
2429
2430 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2431 valueInt != 0) {
2432 ALOGV("Test command %s received", command.string());
2433 String8 target;
2434 if (param.get(String8("target"), target) != NO_ERROR) {
2435 target = "Manager";
2436 }
2437 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2438 param.remove(String8("test_cmd_policy_output"));
2439 mCurOutput = valueInt;
2440 }
2441 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2442 param.remove(String8("test_cmd_policy_direct"));
2443 if (value == "false") {
2444 mDirectOutput = false;
2445 } else if (value == "true") {
2446 mDirectOutput = true;
2447 }
2448 }
2449 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2450 param.remove(String8("test_cmd_policy_input"));
2451 mTestInput = valueInt;
2452 }
2453
2454 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2455 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002456 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002457 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002458 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002459 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002460 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002461 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002462 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002463 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002464 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002465 if (target == "Manager") {
2466 mTestFormat = format;
2467 } else if (mTestOutputs[mCurOutput] != 0) {
2468 AudioParameter outputParam = AudioParameter();
2469 outputParam.addInt(String8("format"), format);
2470 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2471 }
2472 }
2473 }
2474 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2475 param.remove(String8("test_cmd_policy_channels"));
2476 int channels = 0;
2477
2478 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002479 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002480 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002481 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002482 }
2483 if (channels != 0) {
2484 if (target == "Manager") {
2485 mTestChannels = channels;
2486 } else if (mTestOutputs[mCurOutput] != 0) {
2487 AudioParameter outputParam = AudioParameter();
2488 outputParam.addInt(String8("channels"), channels);
2489 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2490 }
2491 }
2492 }
2493 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2494 param.remove(String8("test_cmd_policy_sampleRate"));
2495 if (valueInt >= 0 && valueInt <= 96000) {
2496 int samplingRate = valueInt;
2497 if (target == "Manager") {
2498 mTestSamplingRate = samplingRate;
2499 } else if (mTestOutputs[mCurOutput] != 0) {
2500 AudioParameter outputParam = AudioParameter();
2501 outputParam.addInt(String8("sampling_rate"), samplingRate);
2502 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2503 }
2504 }
2505 }
2506
2507 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2508 param.remove(String8("test_cmd_policy_reopen"));
2509
Eric Laurent1f2f2232014-06-02 12:01:23 -07002510 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002511 mpClientInterface->closeOutput(mPrimaryOutput);
2512
2513 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2514
Eric Laurente552edb2014-03-10 17:42:56 -07002515 mOutputs.removeItem(mPrimaryOutput);
2516
Eric Laurent1f2f2232014-06-02 12:01:23 -07002517 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002518 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2519 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2520 &outputDesc->mDevice,
2521 &outputDesc->mSamplingRate,
2522 &outputDesc->mFormat,
2523 &outputDesc->mChannelMask,
2524 &outputDesc->mLatency,
2525 outputDesc->mFlags);
2526 if (mPrimaryOutput == 0) {
2527 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2528 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2529 } else {
2530 AudioParameter outputCmd = AudioParameter();
2531 outputCmd.addInt(String8("set_id"), 0);
2532 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2533 addOutput(mPrimaryOutput, outputDesc);
2534 }
2535 }
2536
2537
2538 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2539 }
2540 }
2541 return false;
2542}
2543
Eric Laurente0720872014-03-11 09:30:41 -07002544void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002545{
2546 {
2547 AutoMutex _l(mLock);
2548 requestExit();
2549 mWaitWorkCV.signal();
2550 }
2551 requestExitAndWait();
2552}
2553
Eric Laurente0720872014-03-11 09:30:41 -07002554int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002555{
2556 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2557 if (output == mTestOutputs[i]) return i;
2558 }
2559 return 0;
2560}
2561#endif //AUDIO_POLICY_TEST
2562
2563// ---
2564
Eric Laurent1f2f2232014-06-02 12:01:23 -07002565void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002566{
Eric Laurent1c333e22014-05-20 10:48:17 -07002567 outputDesc->mIoHandle = output;
2568 outputDesc->mId = nextUniqueId();
2569 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002570 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002571}
2572
Eric Laurent1f2f2232014-06-02 12:01:23 -07002573void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002574{
Eric Laurent1c333e22014-05-20 10:48:17 -07002575 inputDesc->mIoHandle = input;
2576 inputDesc->mId = nextUniqueId();
2577 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002578 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002579}
Eric Laurente552edb2014-03-10 17:42:56 -07002580
Eric Laurent3a4311c2014-03-17 12:00:47 -07002581String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2582{
2583 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2584 return String8("a2dp_sink_address=")+address;
2585 }
2586 return address;
2587}
2588
Eric Laurente0720872014-03-11 09:30:41 -07002589status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002590 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002591 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002592 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002593{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002594 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002595
Eric Laurent3b73df72014-03-11 09:06:29 -07002596 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002597 // first list already open outputs that can be routed to this device
2598 for (size_t i = 0; i < mOutputs.size(); i++) {
2599 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002600 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002601 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2602 outputs.add(mOutputs.keyAt(i));
2603 }
2604 }
2605 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002606 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002607 for (size_t i = 0; i < mHwModules.size(); i++)
2608 {
2609 if (mHwModules[i]->mHandle == 0) {
2610 continue;
2611 }
2612 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2613 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002614 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002615 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002616 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2617 }
2618 }
2619 }
2620
2621 if (profiles.isEmpty() && outputs.isEmpty()) {
2622 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2623 return BAD_VALUE;
2624 }
2625
2626 // open outputs for matching profiles if needed. Direct outputs are also opened to
2627 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2628 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002629 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002630
2631 // nothing to do if one output is already opened for this profile
2632 size_t j;
2633 for (j = 0; j < mOutputs.size(); j++) {
2634 desc = mOutputs.valueAt(j);
2635 if (!desc->isDuplicated() && desc->mProfile == profile) {
2636 break;
2637 }
2638 }
2639 if (j != mOutputs.size()) {
2640 continue;
2641 }
2642
Eric Laurent3a4311c2014-03-17 12:00:47 -07002643 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002644 desc = new AudioOutputDescriptor(profile);
2645 desc->mDevice = device;
2646 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2647 offloadInfo.sample_rate = desc->mSamplingRate;
2648 offloadInfo.format = desc->mFormat;
2649 offloadInfo.channel_mask = desc->mChannelMask;
2650
2651 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2652 &desc->mDevice,
2653 &desc->mSamplingRate,
2654 &desc->mFormat,
2655 &desc->mChannelMask,
2656 &desc->mLatency,
2657 desc->mFlags,
2658 &offloadInfo);
2659 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002660 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002661 if (!address.isEmpty()) {
2662 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002663 }
2664
Eric Laurentd4692962014-05-05 18:13:44 -07002665 // Here is where we step through and resolve any "dynamic" fields
2666 String8 reply;
2667 char *value;
2668 if (profile->mSamplingRates[0] == 0) {
2669 reply = mpClientInterface->getParameters(output,
2670 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2671 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2672 reply.string());
2673 value = strpbrk((char *)reply.string(), "=");
2674 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002675 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002676 }
Eric Laurentd4692962014-05-05 18:13:44 -07002677 }
2678 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2679 reply = mpClientInterface->getParameters(output,
2680 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2681 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2682 reply.string());
2683 value = strpbrk((char *)reply.string(), "=");
2684 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002685 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002686 }
Eric Laurentd4692962014-05-05 18:13:44 -07002687 }
2688 if (profile->mChannelMasks[0] == 0) {
2689 reply = mpClientInterface->getParameters(output,
2690 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2691 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2692 reply.string());
2693 value = strpbrk((char *)reply.string(), "=");
2694 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002695 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002696 }
Eric Laurentd4692962014-05-05 18:13:44 -07002697 }
2698 if (((profile->mSamplingRates[0] == 0) &&
2699 (profile->mSamplingRates.size() < 2)) ||
2700 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2701 (profile->mFormats.size() < 2)) ||
2702 ((profile->mChannelMasks[0] == 0) &&
2703 (profile->mChannelMasks.size() < 2))) {
2704 ALOGW("checkOutputsForDevice() direct output missing param");
2705 mpClientInterface->closeOutput(output);
2706 output = 0;
2707 } else if (profile->mSamplingRates[0] == 0) {
2708 mpClientInterface->closeOutput(output);
2709 desc->mSamplingRate = profile->mSamplingRates[1];
2710 offloadInfo.sample_rate = desc->mSamplingRate;
2711 output = mpClientInterface->openOutput(
2712 profile->mModule->mHandle,
2713 &desc->mDevice,
2714 &desc->mSamplingRate,
2715 &desc->mFormat,
2716 &desc->mChannelMask,
2717 &desc->mLatency,
2718 desc->mFlags,
2719 &offloadInfo);
2720 }
2721
2722 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002723 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002724 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2725 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002726
Eric Laurentd4692962014-05-05 18:13:44 -07002727 // set initial stream volume for device
2728 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002729
Eric Laurentd4692962014-05-05 18:13:44 -07002730 //TODO: configure audio effect output stage here
2731
2732 // open a duplicating output thread for the new output and the primary output
2733 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2734 mPrimaryOutput);
2735 if (duplicatedOutput != 0) {
2736 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002737 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002738 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2739 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2740 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2741 dupOutputDesc->mFormat = desc->mFormat;
2742 dupOutputDesc->mChannelMask = desc->mChannelMask;
2743 dupOutputDesc->mLatency = desc->mLatency;
2744 addOutput(duplicatedOutput, dupOutputDesc);
2745 applyStreamVolumes(duplicatedOutput, device, 0, true);
2746 } else {
2747 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2748 mPrimaryOutput, output);
2749 mpClientInterface->closeOutput(output);
2750 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002751 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002752 output = 0;
2753 }
Eric Laurente552edb2014-03-10 17:42:56 -07002754 }
2755 }
2756 }
2757 if (output == 0) {
2758 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002759 profiles.removeAt(profile_index);
2760 profile_index--;
2761 } else {
2762 outputs.add(output);
2763 ALOGV("checkOutputsForDevice(): adding output %d", output);
2764 }
2765 }
2766
2767 if (profiles.isEmpty()) {
2768 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2769 return BAD_VALUE;
2770 }
Eric Laurentd4692962014-05-05 18:13:44 -07002771 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002772 // check if one opened output is not needed any more after disconnecting one device
2773 for (size_t i = 0; i < mOutputs.size(); i++) {
2774 desc = mOutputs.valueAt(i);
2775 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002776 !(desc->mProfile->mSupportedDevices.types() &
2777 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002778 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2779 outputs.add(mOutputs.keyAt(i));
2780 }
2781 }
Eric Laurentd4692962014-05-05 18:13:44 -07002782 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002783 for (size_t i = 0; i < mHwModules.size(); i++)
2784 {
2785 if (mHwModules[i]->mHandle == 0) {
2786 continue;
2787 }
2788 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2789 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002790 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002791 if (profile->mSupportedDevices.types() & device) {
2792 ALOGV("checkOutputsForDevice(): "
2793 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002794 if (profile->mSamplingRates[0] == 0) {
2795 profile->mSamplingRates.clear();
2796 profile->mSamplingRates.add(0);
2797 }
2798 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2799 profile->mFormats.clear();
2800 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2801 }
2802 if (profile->mChannelMasks[0] == 0) {
2803 profile->mChannelMasks.clear();
2804 profile->mChannelMasks.add(0);
2805 }
2806 }
2807 }
2808 }
2809 }
2810 return NO_ERROR;
2811}
2812
Eric Laurentd4692962014-05-05 18:13:44 -07002813status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2814 audio_policy_dev_state_t state,
2815 SortedVector<audio_io_handle_t>& inputs,
2816 const String8 address)
2817{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002818 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002819 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2820 // first list already open inputs that can be routed to this device
2821 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2822 desc = mInputs.valueAt(input_index);
2823 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2824 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2825 inputs.add(mInputs.keyAt(input_index));
2826 }
2827 }
2828
2829 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002830 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002831 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2832 {
2833 if (mHwModules[module_idx]->mHandle == 0) {
2834 continue;
2835 }
2836 for (size_t profile_index = 0;
2837 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2838 profile_index++)
2839 {
2840 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2841 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002842 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002843 profile_index, module_idx);
2844 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2845 }
2846 }
2847 }
2848
2849 if (profiles.isEmpty() && inputs.isEmpty()) {
2850 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2851 return BAD_VALUE;
2852 }
2853
2854 // open inputs for matching profiles if needed. Direct inputs are also opened to
2855 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2856 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2857
Eric Laurent1c333e22014-05-20 10:48:17 -07002858 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002859 // nothing to do if one input is already opened for this profile
2860 size_t input_index;
2861 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2862 desc = mInputs.valueAt(input_index);
2863 if (desc->mProfile == profile) {
2864 break;
2865 }
2866 }
2867 if (input_index != mInputs.size()) {
2868 continue;
2869 }
2870
2871 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2872 desc = new AudioInputDescriptor(profile);
2873 desc->mDevice = device;
2874
2875 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2876 &desc->mDevice,
2877 &desc->mSamplingRate,
2878 &desc->mFormat,
2879 &desc->mChannelMask);
2880
2881 if (input != 0) {
2882 if (!address.isEmpty()) {
2883 mpClientInterface->setParameters(input, addressToParameter(device, address));
2884 }
2885
2886 // Here is where we step through and resolve any "dynamic" fields
2887 String8 reply;
2888 char *value;
2889 if (profile->mSamplingRates[0] == 0) {
2890 reply = mpClientInterface->getParameters(input,
2891 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2892 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2893 reply.string());
2894 value = strpbrk((char *)reply.string(), "=");
2895 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002896 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002897 }
2898 }
2899 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2900 reply = mpClientInterface->getParameters(input,
2901 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2902 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2903 value = strpbrk((char *)reply.string(), "=");
2904 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002905 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002906 }
2907 }
2908 if (profile->mChannelMasks[0] == 0) {
2909 reply = mpClientInterface->getParameters(input,
2910 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2911 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2912 reply.string());
2913 value = strpbrk((char *)reply.string(), "=");
2914 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002915 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002916 }
2917 }
2918 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2919 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2920 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2921 ALOGW("checkInputsForDevice() direct input missing param");
2922 mpClientInterface->closeInput(input);
2923 input = 0;
2924 }
2925
2926 if (input != 0) {
2927 addInput(input, desc);
2928 }
2929 } // endif input != 0
2930
2931 if (input == 0) {
2932 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07002933 profiles.removeAt(profile_index);
2934 profile_index--;
2935 } else {
2936 inputs.add(input);
2937 ALOGV("checkInputsForDevice(): adding input %d", input);
2938 }
2939 } // end scan profiles
2940
2941 if (profiles.isEmpty()) {
2942 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2943 return BAD_VALUE;
2944 }
2945 } else {
2946 // Disconnect
2947 // check if one opened input is not needed any more after disconnecting one device
2948 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2949 desc = mInputs.valueAt(input_index);
2950 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2951 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2952 mInputs.keyAt(input_index));
2953 inputs.add(mInputs.keyAt(input_index));
2954 }
2955 }
2956 // Clear any profiles associated with the disconnected device.
2957 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2958 if (mHwModules[module_index]->mHandle == 0) {
2959 continue;
2960 }
2961 for (size_t profile_index = 0;
2962 profile_index < mHwModules[module_index]->mInputProfiles.size();
2963 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002964 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002965 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002966 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002967 profile_index, module_index);
2968 if (profile->mSamplingRates[0] == 0) {
2969 profile->mSamplingRates.clear();
2970 profile->mSamplingRates.add(0);
2971 }
2972 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2973 profile->mFormats.clear();
2974 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2975 }
2976 if (profile->mChannelMasks[0] == 0) {
2977 profile->mChannelMasks.clear();
2978 profile->mChannelMasks.add(0);
2979 }
2980 }
2981 }
2982 }
2983 } // end disconnect
2984
2985 return NO_ERROR;
2986}
2987
2988
Eric Laurente0720872014-03-11 09:30:41 -07002989void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002990{
2991 ALOGV("closeOutput(%d)", output);
2992
Eric Laurent1f2f2232014-06-02 12:01:23 -07002993 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07002994 if (outputDesc == NULL) {
2995 ALOGW("closeOutput() unknown output %d", output);
2996 return;
2997 }
2998
2999 // look for duplicated outputs connected to the output being removed.
3000 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003001 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003002 if (dupOutputDesc->isDuplicated() &&
3003 (dupOutputDesc->mOutput1 == outputDesc ||
3004 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003005 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003006 if (dupOutputDesc->mOutput1 == outputDesc) {
3007 outputDesc2 = dupOutputDesc->mOutput2;
3008 } else {
3009 outputDesc2 = dupOutputDesc->mOutput1;
3010 }
3011 // As all active tracks on duplicated output will be deleted,
3012 // and as they were also referenced on the other output, the reference
3013 // count for their stream type must be adjusted accordingly on
3014 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003015 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003016 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003017 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003018 }
3019 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3020 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3021
3022 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003023 mOutputs.removeItem(duplicatedOutput);
3024 }
3025 }
3026
3027 AudioParameter param;
3028 param.add(String8("closing"), String8("true"));
3029 mpClientInterface->setParameters(output, param.toString());
3030
3031 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003032 mOutputs.removeItem(output);
3033 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003034 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003035}
3036
Eric Laurente0720872014-03-11 09:30:41 -07003037SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003038 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003039{
3040 SortedVector<audio_io_handle_t> outputs;
3041
3042 ALOGVV("getOutputsForDevice() device %04x", device);
3043 for (size_t i = 0; i < openOutputs.size(); i++) {
3044 ALOGVV("output %d isDuplicated=%d device=%04x",
3045 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3046 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3047 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3048 outputs.add(openOutputs.keyAt(i));
3049 }
3050 }
3051 return outputs;
3052}
3053
Eric Laurente0720872014-03-11 09:30:41 -07003054bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003055 SortedVector<audio_io_handle_t>& outputs2)
3056{
3057 if (outputs1.size() != outputs2.size()) {
3058 return false;
3059 }
3060 for (size_t i = 0; i < outputs1.size(); i++) {
3061 if (outputs1[i] != outputs2[i]) {
3062 return false;
3063 }
3064 }
3065 return true;
3066}
3067
Eric Laurente0720872014-03-11 09:30:41 -07003068void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003069{
3070 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3071 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3072 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3073 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3074
3075 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3076 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3077 strategy, srcOutputs[0], dstOutputs[0]);
3078 // mute strategy while moving tracks from one output to another
3079 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003080 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003081 if (desc->isStrategyActive(strategy)) {
3082 setStrategyMute(strategy, true, srcOutputs[i]);
3083 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3084 }
3085 }
3086
3087 // Move effects associated to this strategy from previous output to new output
3088 if (strategy == STRATEGY_MEDIA) {
3089 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3090 SortedVector<audio_io_handle_t> moved;
3091 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003092 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3093 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3094 effectDesc->mIo != fxOutput) {
3095 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003096 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3097 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003098 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003099 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003100 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003101 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003102 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003103 }
3104 }
3105 }
3106 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003107 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3108 if (getStrategy((audio_stream_type_t)i) == strategy) {
3109 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003110 }
3111 }
3112 }
3113}
3114
Eric Laurente0720872014-03-11 09:30:41 -07003115void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003116{
3117 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3118 checkOutputForStrategy(STRATEGY_PHONE);
3119 checkOutputForStrategy(STRATEGY_SONIFICATION);
3120 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3121 checkOutputForStrategy(STRATEGY_MEDIA);
3122 checkOutputForStrategy(STRATEGY_DTMF);
3123}
3124
Eric Laurente0720872014-03-11 09:30:41 -07003125audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003126{
Eric Laurente552edb2014-03-10 17:42:56 -07003127 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003128 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003129 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3130 return mOutputs.keyAt(i);
3131 }
3132 }
3133
3134 return 0;
3135}
3136
Eric Laurente0720872014-03-11 09:30:41 -07003137void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003138{
Eric Laurente552edb2014-03-10 17:42:56 -07003139 audio_io_handle_t a2dpOutput = getA2dpOutput();
3140 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003141 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003142 return;
3143 }
3144
Eric Laurent3a4311c2014-03-17 12:00:47 -07003145 bool isScoConnected =
3146 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003147 // suspend A2DP output if:
3148 // (NOT already suspended) &&
3149 // ((SCO device is connected &&
3150 // (forced usage for communication || for record is SCO))) ||
3151 // (phone state is ringing || in call)
3152 //
3153 // restore A2DP output if:
3154 // (Already suspended) &&
3155 // ((SCO device is NOT connected ||
3156 // (forced usage NOT for communication && NOT for record is SCO))) &&
3157 // (phone state is NOT ringing && NOT in call)
3158 //
3159 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003160 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003161 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3162 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3163 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3164 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003165
3166 mpClientInterface->restoreOutput(a2dpOutput);
3167 mA2dpSuspended = false;
3168 }
3169 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003170 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003171 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3172 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3173 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3174 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003175
3176 mpClientInterface->suspendOutput(a2dpOutput);
3177 mA2dpSuspended = true;
3178 }
3179 }
3180}
3181
Eric Laurent1c333e22014-05-20 10:48:17 -07003182audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003183{
3184 audio_devices_t device = AUDIO_DEVICE_NONE;
3185
Eric Laurent1f2f2232014-06-02 12:01:23 -07003186 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003187
3188 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3189 if (index >= 0) {
3190 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3191 if (patchDesc->mUid != mUidCached) {
3192 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3193 outputDesc->device(), outputDesc->mPatchHandle);
3194 return outputDesc->device();
3195 }
3196 }
3197
Eric Laurente552edb2014-03-10 17:42:56 -07003198 // check the following by order of priority to request a routing change if necessary:
3199 // 1: the strategy enforced audible is active on the output:
3200 // use device for strategy enforced audible
3201 // 2: we are in call or the strategy phone is active on the output:
3202 // use device for strategy phone
3203 // 3: the strategy sonification is active on the output:
3204 // use device for strategy sonification
3205 // 4: the strategy "respectful" sonification is active on the output:
3206 // use device for strategy "respectful" sonification
3207 // 5: the strategy media is active on the output:
3208 // use device for strategy media
3209 // 6: the strategy DTMF is active on the output:
3210 // use device for strategy DTMF
3211 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3212 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3213 } else if (isInCall() ||
3214 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3215 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3216 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3217 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3218 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3219 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3220 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3221 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3222 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3223 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3224 }
3225
Eric Laurent1c333e22014-05-20 10:48:17 -07003226 ALOGV("getNewOutputDevice() selected device %x", device);
3227 return device;
3228}
3229
3230audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3231{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003232 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003233
3234 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3235 if (index >= 0) {
3236 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3237 if (patchDesc->mUid != mUidCached) {
3238 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3239 inputDesc->mDevice, inputDesc->mPatchHandle);
3240 return inputDesc->mDevice;
3241 }
3242 }
3243
Eric Laurent1c333e22014-05-20 10:48:17 -07003244 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3245
3246 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003247 return device;
3248}
3249
Eric Laurente0720872014-03-11 09:30:41 -07003250uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003251 return (uint32_t)getStrategy(stream);
3252}
3253
Eric Laurente0720872014-03-11 09:30:41 -07003254audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003255 // By checking the range of stream before calling getStrategy, we avoid
3256 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3257 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003258 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003259 return AUDIO_DEVICE_NONE;
3260 }
3261 audio_devices_t devices;
3262 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3263 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3264 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3265 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003266 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003267 if (outputDesc->isStrategyActive(strategy)) {
3268 devices = outputDesc->device();
3269 break;
3270 }
Eric Laurente552edb2014-03-10 17:42:56 -07003271 }
3272 return devices;
3273}
3274
Eric Laurente0720872014-03-11 09:30:41 -07003275AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003276 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003277 // stream to strategy mapping
3278 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003279 case AUDIO_STREAM_VOICE_CALL:
3280 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003281 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003282 case AUDIO_STREAM_RING:
3283 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003284 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003285 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003286 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003287 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003288 return STRATEGY_DTMF;
3289 default:
3290 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003291 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003292 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3293 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003294 case AUDIO_STREAM_TTS:
3295 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003296 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003297 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003298 return STRATEGY_ENFORCED_AUDIBLE;
3299 }
3300}
3301
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003302uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3303 // flags to strategy mapping
3304 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3305 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3306 }
3307
3308 // usage to strategy mapping
3309 switch (attr->usage) {
3310 case AUDIO_USAGE_MEDIA:
3311 case AUDIO_USAGE_GAME:
3312 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3313 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3314 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3315 return (uint32_t) STRATEGY_MEDIA;
3316
3317 case AUDIO_USAGE_VOICE_COMMUNICATION:
3318 return (uint32_t) STRATEGY_PHONE;
3319
3320 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3321 return (uint32_t) STRATEGY_DTMF;
3322
3323 case AUDIO_USAGE_ALARM:
3324 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3325 return (uint32_t) STRATEGY_SONIFICATION;
3326
3327 case AUDIO_USAGE_NOTIFICATION:
3328 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3329 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3330 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3331 case AUDIO_USAGE_NOTIFICATION_EVENT:
3332 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3333
3334 case AUDIO_USAGE_UNKNOWN:
3335 default:
3336 return (uint32_t) STRATEGY_MEDIA;
3337 }
3338}
3339
Eric Laurente0720872014-03-11 09:30:41 -07003340void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003341 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003342 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003343 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3344 updateDevicesAndOutputs();
3345 break;
3346 default:
3347 break;
3348 }
3349}
3350
Eric Laurente0720872014-03-11 09:30:41 -07003351audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003352 bool fromCache)
3353{
3354 uint32_t device = AUDIO_DEVICE_NONE;
3355
3356 if (fromCache) {
3357 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3358 strategy, mDeviceForStrategy[strategy]);
3359 return mDeviceForStrategy[strategy];
3360 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003361 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003362 switch (strategy) {
3363
3364 case STRATEGY_SONIFICATION_RESPECTFUL:
3365 if (isInCall()) {
3366 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003367 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003368 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3369 // while media is playing on a remote device, use the the sonification behavior.
3370 // Note that we test this usecase before testing if media is playing because
3371 // the isStreamActive() method only informs about the activity of a stream, not
3372 // if it's for local playback. Note also that we use the same delay between both tests
3373 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003374 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003375 // while media is playing (or has recently played), use the same device
3376 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3377 } else {
3378 // when media is not playing anymore, fall back on the sonification behavior
3379 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3380 }
3381
3382 break;
3383
3384 case STRATEGY_DTMF:
3385 if (!isInCall()) {
3386 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3387 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3388 break;
3389 }
3390 // when in call, DTMF and PHONE strategies follow the same rules
3391 // FALL THROUGH
3392
3393 case STRATEGY_PHONE:
3394 // for phone strategy, we first consider the forced use and then the available devices by order
3395 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003396 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3397 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003398 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003399 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003400 if (device) break;
3401 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003402 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003403 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003404 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003405 if (device) break;
3406 // if SCO device is requested but no SCO device is available, fall back to default case
3407 // FALL THROUGH
3408
3409 default: // FORCE_NONE
3410 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003411 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003412 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003413 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003414 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003415 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003416 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003417 if (device) break;
3418 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003419 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003420 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003421 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003422 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003423 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003424 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003425 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003426 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003427 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003428 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003429 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003430 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003431 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003432 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003433 if (device) break;
3434 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003435 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003436 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003437 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003438 if (device == AUDIO_DEVICE_NONE) {
3439 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3440 }
3441 break;
3442
Eric Laurent3b73df72014-03-11 09:06:29 -07003443 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003444 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3445 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003446 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003447 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003448 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003449 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003450 if (device) break;
3451 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003452 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003453 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003454 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003455 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003456 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003457 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003458 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003459 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003460 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003461 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003462 if (device) break;
3463 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003464 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003465 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003466 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003467 if (device == AUDIO_DEVICE_NONE) {
3468 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3469 }
3470 break;
3471 }
3472 break;
3473
3474 case STRATEGY_SONIFICATION:
3475
3476 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3477 // handleIncallSonification().
3478 if (isInCall()) {
3479 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3480 break;
3481 }
3482 // FALL THROUGH
3483
3484 case STRATEGY_ENFORCED_AUDIBLE:
3485 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3486 // except:
3487 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3488 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3489
3490 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003491 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003492 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003493 if (device == AUDIO_DEVICE_NONE) {
3494 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3495 }
3496 }
3497 // The second device used for sonification is the same as the device used by media strategy
3498 // FALL THROUGH
3499
3500 case STRATEGY_MEDIA: {
3501 uint32_t device2 = AUDIO_DEVICE_NONE;
3502 if (strategy != STRATEGY_SONIFICATION) {
3503 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003504 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003505 }
3506 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003507 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003508 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003509 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003510 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003511 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003512 }
3513 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003514 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003515 }
3516 }
3517 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003518 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
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_WIRED_HEADSET;
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_ACCESSORY;
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_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003528 }
3529 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003530 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003531 }
3532 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3533 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003534 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003535 }
3536 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003537 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003538 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003539 }
3540 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003541 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003542 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003543 int device3 = AUDIO_DEVICE_NONE;
3544 if (strategy == STRATEGY_MEDIA) {
3545 // Hdmi system audio should use manually configured device type.
3546 if (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]
3547 == AUDIO_POLICY_FORCE_SYSTEM_AUDIO_HDMI_ARC) {
3548 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3549 } else if (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]
3550 == AUDIO_POLICY_FORCE_SYSTEM_AUDIO_SPDIF) {
3551 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF;
3552 } else if (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]
3553 == AUDIO_POLICY_FORCE_SYSTEM_AUDIO_LINE) {
3554 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3555 }
3556 }
Eric Laurente552edb2014-03-10 17:42:56 -07003557
Jungshik Jang839e4f32014-06-26 17:23:40 +09003558 // Merge hdmi cec system audio and existing device for media. If system audio is on,
3559 // internal speaker will be muted but others are not.
3560 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003561 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3562 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3563 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003564
3565 // If system audio mode is on and proper audio out is set, remove speaker from device.
3566 if (device3 != AUDIO_DEVICE_NONE) {
3567 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3568 }
Eric Laurente552edb2014-03-10 17:42:56 -07003569 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003570 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003571 if (device == AUDIO_DEVICE_NONE) {
3572 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3573 }
3574 } break;
3575
3576 default:
3577 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3578 break;
3579 }
3580
3581 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3582 return device;
3583}
3584
Eric Laurente0720872014-03-11 09:30:41 -07003585void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003586{
3587 for (int i = 0; i < NUM_STRATEGIES; i++) {
3588 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3589 }
3590 mPreviousOutputs = mOutputs;
3591}
3592
Eric Laurent1f2f2232014-06-02 12:01:23 -07003593uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003594 audio_devices_t prevDevice,
3595 uint32_t delayMs)
3596{
3597 // mute/unmute strategies using an incompatible device combination
3598 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3599 // if unmuting, unmute only after the specified delay
3600 if (outputDesc->isDuplicated()) {
3601 return 0;
3602 }
3603
3604 uint32_t muteWaitMs = 0;
3605 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003606 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003607
3608 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3609 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3610 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3611 bool doMute = false;
3612
3613 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3614 doMute = true;
3615 outputDesc->mStrategyMutedByDevice[i] = true;
3616 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3617 doMute = true;
3618 outputDesc->mStrategyMutedByDevice[i] = false;
3619 }
Eric Laurent99401132014-05-07 19:48:15 -07003620 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003621 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003622 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003623 // skip output if it does not share any device with current output
3624 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3625 == AUDIO_DEVICE_NONE) {
3626 continue;
3627 }
3628 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3629 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3630 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3631 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3632 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003633 if (mute) {
3634 // FIXME: should not need to double latency if volume could be applied
3635 // immediately by the audioflinger mixer. We must account for the delay
3636 // between now and the next time the audioflinger thread for this output
3637 // will process a buffer (which corresponds to one buffer size,
3638 // usually 1/2 or 1/4 of the latency).
3639 if (muteWaitMs < desc->latency() * 2) {
3640 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003641 }
3642 }
3643 }
3644 }
3645 }
3646 }
3647
Eric Laurent99401132014-05-07 19:48:15 -07003648 // temporary mute output if device selection changes to avoid volume bursts due to
3649 // different per device volumes
3650 if (outputDesc->isActive() && (device != prevDevice)) {
3651 if (muteWaitMs < outputDesc->latency() * 2) {
3652 muteWaitMs = outputDesc->latency() * 2;
3653 }
3654 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3655 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003656 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003657 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003658 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003659 muteWaitMs *2, device);
3660 }
3661 }
3662 }
3663
Eric Laurente552edb2014-03-10 17:42:56 -07003664 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3665 if (muteWaitMs > delayMs) {
3666 muteWaitMs -= delayMs;
3667 usleep(muteWaitMs * 1000);
3668 return muteWaitMs;
3669 }
3670 return 0;
3671}
3672
Eric Laurente0720872014-03-11 09:30:41 -07003673uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003674 audio_devices_t device,
3675 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003676 int delayMs,
3677 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003678{
3679 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003680 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003681 AudioParameter param;
3682 uint32_t muteWaitMs;
3683
3684 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003685 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3686 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003687 return muteWaitMs;
3688 }
3689 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3690 // output profile
3691 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003692 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003693 return 0;
3694 }
3695
3696 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003697 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003698
3699 audio_devices_t prevDevice = outputDesc->mDevice;
3700
3701 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3702
3703 if (device != AUDIO_DEVICE_NONE) {
3704 outputDesc->mDevice = device;
3705 }
3706 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3707
3708 // Do not change the routing if:
3709 // - the requested device is AUDIO_DEVICE_NONE
3710 // - the requested device is the same as current device and force is not specified.
3711 // Doing this check here allows the caller to call setOutputDevice() without conditions
3712 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3713 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3714 return muteWaitMs;
3715 }
3716
3717 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003718
Eric Laurente552edb2014-03-10 17:42:56 -07003719 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003720 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003721 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003722 } else {
3723 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3724 if (!deviceList.isEmpty()) {
3725 struct audio_patch patch;
3726 outputDesc->toAudioPortConfig(&patch.sources[0]);
3727 patch.num_sources = 1;
3728 patch.num_sinks = 0;
3729 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3730 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003731 patch.num_sinks++;
3732 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003733 ssize_t index;
3734 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3735 index = mAudioPatches.indexOfKey(*patchHandle);
3736 } else {
3737 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3738 }
3739 sp< AudioPatch> patchDesc;
3740 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3741 if (index >= 0) {
3742 patchDesc = mAudioPatches.valueAt(index);
3743 afPatchHandle = patchDesc->mAfPatchHandle;
3744 }
3745
Eric Laurent1c333e22014-05-20 10:48:17 -07003746 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003747 &afPatchHandle,
3748 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003749 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3750 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003751 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003752 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003753 if (index < 0) {
3754 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3755 &patch, mUidCached);
3756 addAudioPatch(patchDesc->mHandle, patchDesc);
3757 } else {
3758 patchDesc->mPatch = patch;
3759 }
3760 patchDesc->mAfPatchHandle = afPatchHandle;
3761 patchDesc->mUid = mUidCached;
3762 if (patchHandle) {
3763 *patchHandle = patchDesc->mHandle;
3764 }
3765 outputDesc->mPatchHandle = patchDesc->mHandle;
3766 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003767 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003768 }
3769 }
3770 }
Eric Laurente552edb2014-03-10 17:42:56 -07003771
3772 // update stream volumes according to new device
3773 applyStreamVolumes(output, device, delayMs);
3774
3775 return muteWaitMs;
3776}
3777
Eric Laurent1c333e22014-05-20 10:48:17 -07003778status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003779 int delayMs,
3780 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003781{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003782 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003783 ssize_t index;
3784 if (patchHandle) {
3785 index = mAudioPatches.indexOfKey(*patchHandle);
3786 } else {
3787 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3788 }
3789 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003790 return INVALID_OPERATION;
3791 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003792 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3793 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003794 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3795 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003796 removeAudioPatch(patchDesc->mHandle);
3797 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003798 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003799 return status;
3800}
3801
3802status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3803 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003804 bool force,
3805 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003806{
3807 status_t status = NO_ERROR;
3808
Eric Laurent1f2f2232014-06-02 12:01:23 -07003809 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003810 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3811 inputDesc->mDevice = device;
3812
3813 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3814 if (!deviceList.isEmpty()) {
3815 struct audio_patch patch;
3816 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3817 patch.num_sinks = 1;
3818 //only one input device for now
3819 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003820 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003821 ssize_t index;
3822 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3823 index = mAudioPatches.indexOfKey(*patchHandle);
3824 } else {
3825 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3826 }
3827 sp< AudioPatch> patchDesc;
3828 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3829 if (index >= 0) {
3830 patchDesc = mAudioPatches.valueAt(index);
3831 afPatchHandle = patchDesc->mAfPatchHandle;
3832 }
3833
Eric Laurent1c333e22014-05-20 10:48:17 -07003834 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003835 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003836 0);
3837 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003838 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003839 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003840 if (index < 0) {
3841 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3842 &patch, mUidCached);
3843 addAudioPatch(patchDesc->mHandle, patchDesc);
3844 } else {
3845 patchDesc->mPatch = patch;
3846 }
3847 patchDesc->mAfPatchHandle = afPatchHandle;
3848 patchDesc->mUid = mUidCached;
3849 if (patchHandle) {
3850 *patchHandle = patchDesc->mHandle;
3851 }
3852 inputDesc->mPatchHandle = patchDesc->mHandle;
3853 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003854 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003855 }
3856 }
3857 }
3858 return status;
3859}
3860
Eric Laurent6a94d692014-05-20 11:18:06 -07003861status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3862 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003863{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003864 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003865 ssize_t index;
3866 if (patchHandle) {
3867 index = mAudioPatches.indexOfKey(*patchHandle);
3868 } else {
3869 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3870 }
3871 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003872 return INVALID_OPERATION;
3873 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003874 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3875 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003876 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3877 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003878 removeAudioPatch(patchDesc->mHandle);
3879 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003880 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003881 return status;
3882}
3883
3884sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003885 uint32_t samplingRate,
3886 audio_format_t format,
3887 audio_channel_mask_t channelMask)
3888{
3889 // Choose an input profile based on the requested capture parameters: select the first available
3890 // profile supporting all requested parameters.
3891
3892 for (size_t i = 0; i < mHwModules.size(); i++)
3893 {
3894 if (mHwModules[i]->mHandle == 0) {
3895 continue;
3896 }
3897 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3898 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003899 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003900 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003901 if (profile->isCompatibleProfile(device, samplingRate, format,
3902 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3903 return profile;
3904 }
3905 }
3906 }
3907 return NULL;
3908}
3909
Eric Laurente0720872014-03-11 09:30:41 -07003910audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003911{
3912 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003913 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3914 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003915 switch (inputSource) {
3916 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003917 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003918 device = AUDIO_DEVICE_IN_VOICE_CALL;
3919 break;
3920 }
3921 // FALL THROUGH
3922
3923 case AUDIO_SOURCE_DEFAULT:
3924 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003925 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3926 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3927 break;
3928 }
3929 // FALL THROUGH
3930
Eric Laurente552edb2014-03-10 17:42:56 -07003931 case AUDIO_SOURCE_VOICE_RECOGNITION:
3932 case AUDIO_SOURCE_HOTWORD:
3933 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003934 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003935 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003936 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003938 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003939 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3940 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003941 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003942 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3943 }
3944 break;
3945 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003946 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003947 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003948 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003949 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3950 }
3951 break;
3952 case AUDIO_SOURCE_VOICE_DOWNLINK:
3953 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003954 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003955 device = AUDIO_DEVICE_IN_VOICE_CALL;
3956 }
3957 break;
3958 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003959 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003960 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3961 }
3962 break;
3963 default:
3964 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3965 break;
3966 }
3967 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3968 return device;
3969}
3970
Eric Laurente0720872014-03-11 09:30:41 -07003971bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003972{
3973 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3974 device &= ~AUDIO_DEVICE_BIT_IN;
3975 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3976 return true;
3977 }
3978 return false;
3979}
3980
Eric Laurente0720872014-03-11 09:30:41 -07003981audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003982{
3983 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003984 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003985 if ((input_descriptor->mRefCount > 0)
3986 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3987 return mInputs.keyAt(i);
3988 }
3989 }
3990 return 0;
3991}
3992
3993
Eric Laurente0720872014-03-11 09:30:41 -07003994audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003995{
3996 if (device == AUDIO_DEVICE_NONE) {
3997 // this happens when forcing a route update and no track is active on an output.
3998 // In this case the returned category is not important.
3999 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004000 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004001 // Multiple device selection is either:
4002 // - speaker + one other device: give priority to speaker in this case.
4003 // - one A2DP device + another device: happens with duplicated output. In this case
4004 // retain the device on the A2DP output as the other must not correspond to an active
4005 // selection if not the speaker.
4006 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4007 device = AUDIO_DEVICE_OUT_SPEAKER;
4008 } else {
4009 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4010 }
4011 }
4012
Eric Laurent3b73df72014-03-11 09:06:29 -07004013 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004014 "getDeviceForVolume() invalid device combination: %08x",
4015 device);
4016
4017 return device;
4018}
4019
Eric Laurente0720872014-03-11 09:30:41 -07004020AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004021{
4022 switch(getDeviceForVolume(device)) {
4023 case AUDIO_DEVICE_OUT_EARPIECE:
4024 return DEVICE_CATEGORY_EARPIECE;
4025 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4026 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4027 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4028 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4029 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4030 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4031 return DEVICE_CATEGORY_HEADSET;
4032 case AUDIO_DEVICE_OUT_SPEAKER:
4033 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4034 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4035 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4036 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4037 case AUDIO_DEVICE_OUT_USB_DEVICE:
4038 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4039 default:
4040 return DEVICE_CATEGORY_SPEAKER;
4041 }
4042}
4043
Eric Laurente0720872014-03-11 09:30:41 -07004044float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004045 int indexInUi)
4046{
4047 device_category deviceCategory = getDeviceCategory(device);
4048 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4049
4050 // the volume index in the UI is relative to the min and max volume indices for this stream type
4051 int nbSteps = 1 + curve[VOLMAX].mIndex -
4052 curve[VOLMIN].mIndex;
4053 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4054 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4055
4056 // find what part of the curve this index volume belongs to, or if it's out of bounds
4057 int segment = 0;
4058 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4059 return 0.0f;
4060 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4061 segment = 0;
4062 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4063 segment = 1;
4064 } else if (volIdx <= curve[VOLMAX].mIndex) {
4065 segment = 2;
4066 } else { // out of bounds
4067 return 1.0f;
4068 }
4069
4070 // linear interpolation in the attenuation table in dB
4071 float decibels = curve[segment].mDBAttenuation +
4072 ((float)(volIdx - curve[segment].mIndex)) *
4073 ( (curve[segment+1].mDBAttenuation -
4074 curve[segment].mDBAttenuation) /
4075 ((float)(curve[segment+1].mIndex -
4076 curve[segment].mIndex)) );
4077
4078 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4079
4080 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4081 curve[segment].mIndex, volIdx,
4082 curve[segment+1].mIndex,
4083 curve[segment].mDBAttenuation,
4084 decibels,
4085 curve[segment+1].mDBAttenuation,
4086 amplification);
4087
4088 return amplification;
4089}
4090
Eric Laurente0720872014-03-11 09:30:41 -07004091const AudioPolicyManager::VolumeCurvePoint
4092 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004093 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4094};
4095
Eric Laurente0720872014-03-11 09:30:41 -07004096const AudioPolicyManager::VolumeCurvePoint
4097 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004098 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4099};
4100
Eric Laurente0720872014-03-11 09:30:41 -07004101const AudioPolicyManager::VolumeCurvePoint
4102 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004103 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4104};
4105
Eric Laurente0720872014-03-11 09:30:41 -07004106const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004107 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004108 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004109};
4110
4111const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004112 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004113 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4114};
4115
Eric Laurente0720872014-03-11 09:30:41 -07004116const AudioPolicyManager::VolumeCurvePoint
4117 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004118 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4119};
4120
4121// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4122// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4123// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4124// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4125
Eric Laurente0720872014-03-11 09:30:41 -07004126const AudioPolicyManager::VolumeCurvePoint
4127 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004128 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4129};
4130
Eric Laurente0720872014-03-11 09:30:41 -07004131const AudioPolicyManager::VolumeCurvePoint
4132 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004133 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4134};
4135
Eric Laurente0720872014-03-11 09:30:41 -07004136const AudioPolicyManager::VolumeCurvePoint
4137 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004138 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4139};
4140
Eric Laurente0720872014-03-11 09:30:41 -07004141const AudioPolicyManager::VolumeCurvePoint
4142 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004143 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4144};
4145
Eric Laurente0720872014-03-11 09:30:41 -07004146const AudioPolicyManager::VolumeCurvePoint
4147 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004148 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4149};
4150
Eric Laurente0720872014-03-11 09:30:41 -07004151const AudioPolicyManager::VolumeCurvePoint
4152 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4153 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004154 { // AUDIO_STREAM_VOICE_CALL
4155 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4156 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4157 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4158 },
4159 { // AUDIO_STREAM_SYSTEM
4160 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4161 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4162 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4163 },
4164 { // AUDIO_STREAM_RING
4165 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4166 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4167 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4168 },
4169 { // AUDIO_STREAM_MUSIC
4170 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4171 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4172 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4173 },
4174 { // AUDIO_STREAM_ALARM
4175 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4176 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4177 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4178 },
4179 { // AUDIO_STREAM_NOTIFICATION
4180 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4181 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4182 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4183 },
4184 { // AUDIO_STREAM_BLUETOOTH_SCO
4185 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4186 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4187 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4188 },
4189 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4190 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4191 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4192 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4193 },
4194 { // AUDIO_STREAM_DTMF
4195 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4196 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4197 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4198 },
4199 { // AUDIO_STREAM_TTS
4200 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4201 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4202 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4203 },
4204};
4205
Eric Laurente0720872014-03-11 09:30:41 -07004206void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004207{
4208 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4209 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4210 mStreams[i].mVolumeCurve[j] =
4211 sVolumeProfiles[i][j];
4212 }
4213 }
4214
4215 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4216 if (mSpeakerDrcEnabled) {
4217 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4218 sDefaultSystemVolumeCurveDrc;
4219 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4220 sSpeakerSonificationVolumeCurveDrc;
4221 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4222 sSpeakerSonificationVolumeCurveDrc;
4223 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4224 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004225 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4226 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004227 }
4228}
4229
Eric Laurente0720872014-03-11 09:30:41 -07004230float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004231 int index,
4232 audio_io_handle_t output,
4233 audio_devices_t device)
4234{
4235 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004236 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004237 StreamDescriptor &streamDesc = mStreams[stream];
4238
4239 if (device == AUDIO_DEVICE_NONE) {
4240 device = outputDesc->device();
4241 }
4242
4243 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004244 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004245 index != mStreams[stream].mIndexMin &&
4246 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
Paul McLeanb919dd32014-06-26 13:16:44 -07004247 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004248 return 1.0;
4249 }
4250
4251 volume = volIndexToAmpl(device, streamDesc, index);
4252
4253 // if a headset is connected, apply the following rules to ring tones and notifications
4254 // to avoid sound level bursts in user's ears:
4255 // - always attenuate ring tones and notifications volume by 6dB
4256 // - if music is playing, always limit the volume to current music volume,
4257 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004258 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004259 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4260 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4261 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4262 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4263 ((stream_strategy == STRATEGY_SONIFICATION)
4264 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004265 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004266 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004267 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004268 streamDesc.mCanBeMuted) {
4269 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4270 // when the phone is ringing we must consider that music could have been paused just before
4271 // by the music application and behave as if music was active if the last music track was
4272 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004273 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004274 mLimitRingtoneVolume) {
4275 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004276 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4277 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004278 output,
4279 musicDevice);
4280 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4281 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4282 if (volume > minVol) {
4283 volume = minVol;
4284 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4285 }
4286 }
4287 }
4288
4289 return volume;
4290}
4291
Eric Laurente0720872014-03-11 09:30:41 -07004292status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004293 int index,
4294 audio_io_handle_t output,
4295 audio_devices_t device,
4296 int delayMs,
4297 bool force)
4298{
4299
4300 // do not change actual stream volume if the stream is muted
4301 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4302 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4303 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4304 return NO_ERROR;
4305 }
4306
4307 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004308 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4309 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4310 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4311 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004312 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004313 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004314 return INVALID_OPERATION;
4315 }
4316
4317 float volume = computeVolume(stream, index, output, device);
4318 // We actually change the volume if:
4319 // - the float value returned by computeVolume() changed
4320 // - the force flag is set
4321 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4322 force) {
4323 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4324 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4325 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4326 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004327 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4328 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004329 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004330 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004331 }
4332
Eric Laurent3b73df72014-03-11 09:06:29 -07004333 if (stream == AUDIO_STREAM_VOICE_CALL ||
4334 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004335 float voiceVolume;
4336 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004337 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004338 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4339 } else {
4340 voiceVolume = 1.0;
4341 }
4342
4343 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4344 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4345 mLastVoiceVolume = voiceVolume;
4346 }
4347 }
4348
4349 return NO_ERROR;
4350}
4351
Eric Laurente0720872014-03-11 09:30:41 -07004352void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004353 audio_devices_t device,
4354 int delayMs,
4355 bool force)
4356{
4357 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4358
Eric Laurent3b73df72014-03-11 09:06:29 -07004359 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4360 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004361 mStreams[stream].getVolumeIndex(device),
4362 output,
4363 device,
4364 delayMs,
4365 force);
4366 }
4367}
4368
Eric Laurente0720872014-03-11 09:30:41 -07004369void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004370 bool on,
4371 audio_io_handle_t output,
4372 int delayMs,
4373 audio_devices_t device)
4374{
4375 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004376 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4377 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4378 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004379 }
4380 }
4381}
4382
Eric Laurente0720872014-03-11 09:30:41 -07004383void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004384 bool on,
4385 audio_io_handle_t output,
4386 int delayMs,
4387 audio_devices_t device)
4388{
4389 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004390 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004391 if (device == AUDIO_DEVICE_NONE) {
4392 device = outputDesc->device();
4393 }
4394
4395 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4396 stream, on, output, outputDesc->mMuteCount[stream], device);
4397
4398 if (on) {
4399 if (outputDesc->mMuteCount[stream] == 0) {
4400 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004401 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4402 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004403 checkAndSetVolume(stream, 0, output, device, delayMs);
4404 }
4405 }
4406 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4407 outputDesc->mMuteCount[stream]++;
4408 } else {
4409 if (outputDesc->mMuteCount[stream] == 0) {
4410 ALOGV("setStreamMute() unmuting non muted stream!");
4411 return;
4412 }
4413 if (--outputDesc->mMuteCount[stream] == 0) {
4414 checkAndSetVolume(stream,
4415 streamDesc.getVolumeIndex(device),
4416 output,
4417 device,
4418 delayMs);
4419 }
4420 }
4421}
4422
Eric Laurente0720872014-03-11 09:30:41 -07004423void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004424 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004425{
4426 // if the stream pertains to sonification strategy and we are in call we must
4427 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4428 // in the device used for phone strategy and play the tone if the selected device does not
4429 // interfere with the device used for phone strategy
4430 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4431 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004432 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004433 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4434 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004435 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004436 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4437 stream, starting, outputDesc->mDevice, stateChange);
4438 if (outputDesc->mRefCount[stream]) {
4439 int muteCount = 1;
4440 if (stateChange) {
4441 muteCount = outputDesc->mRefCount[stream];
4442 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004443 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004444 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4445 for (int i = 0; i < muteCount; i++) {
4446 setStreamMute(stream, starting, mPrimaryOutput);
4447 }
4448 } else {
4449 ALOGV("handleIncallSonification() high visibility");
4450 if (outputDesc->device() &
4451 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4452 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4453 for (int i = 0; i < muteCount; i++) {
4454 setStreamMute(stream, starting, mPrimaryOutput);
4455 }
4456 }
4457 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004458 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4459 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004460 } else {
4461 mpClientInterface->stopTone();
4462 }
4463 }
4464 }
4465 }
4466}
4467
Eric Laurente0720872014-03-11 09:30:41 -07004468bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004469{
4470 return isStateInCall(mPhoneState);
4471}
4472
Eric Laurente0720872014-03-11 09:30:41 -07004473bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004474 return ((state == AUDIO_MODE_IN_CALL) ||
4475 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004476}
4477
Eric Laurente0720872014-03-11 09:30:41 -07004478uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004479{
4480 return MAX_EFFECTS_CPU_LOAD;
4481}
4482
Eric Laurente0720872014-03-11 09:30:41 -07004483uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004484{
4485 return MAX_EFFECTS_MEMORY;
4486}
4487
Eric Laurent6a94d692014-05-20 11:18:06 -07004488
Eric Laurente552edb2014-03-10 17:42:56 -07004489// --- AudioOutputDescriptor class implementation
4490
Eric Laurente0720872014-03-11 09:30:41 -07004491AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004492 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004493 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004494 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004495 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4496{
4497 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004498 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004499 mRefCount[i] = 0;
4500 mCurVolume[i] = -1.0;
4501 mMuteCount[i] = 0;
4502 mStopTime[i] = 0;
4503 }
4504 for (int i = 0; i < NUM_STRATEGIES; i++) {
4505 mStrategyMutedByDevice[i] = false;
4506 }
4507 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004508 mAudioPort = profile;
Eric Laurente552edb2014-03-10 17:42:56 -07004509 mSamplingRate = profile->mSamplingRates[0];
4510 mFormat = profile->mFormats[0];
4511 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004512 if (profile->mGains.size() > 0) {
4513 profile->mGains[0]->getDefaultConfig(&mGain);
4514 }
Eric Laurente552edb2014-03-10 17:42:56 -07004515 mFlags = profile->mFlags;
4516 }
4517}
4518
Eric Laurente0720872014-03-11 09:30:41 -07004519audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004520{
4521 if (isDuplicated()) {
4522 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4523 } else {
4524 return mDevice;
4525 }
4526}
4527
Eric Laurente0720872014-03-11 09:30:41 -07004528uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004529{
4530 if (isDuplicated()) {
4531 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4532 } else {
4533 return mLatency;
4534 }
4535}
4536
Eric Laurente0720872014-03-11 09:30:41 -07004537bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004538 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004539{
4540 if (isDuplicated()) {
4541 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4542 } else if (outputDesc->isDuplicated()){
4543 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4544 } else {
4545 return (mProfile->mModule == outputDesc->mProfile->mModule);
4546 }
4547}
4548
Eric Laurente0720872014-03-11 09:30:41 -07004549void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004550 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004551{
4552 // forward usage count change to attached outputs
4553 if (isDuplicated()) {
4554 mOutput1->changeRefCount(stream, delta);
4555 mOutput2->changeRefCount(stream, delta);
4556 }
4557 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004558 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4559 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004560 mRefCount[stream] = 0;
4561 return;
4562 }
4563 mRefCount[stream] += delta;
4564 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4565}
4566
Eric Laurente0720872014-03-11 09:30:41 -07004567audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004568{
4569 if (isDuplicated()) {
4570 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4571 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004573 }
4574}
4575
Eric Laurente0720872014-03-11 09:30:41 -07004576bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004577{
4578 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4579}
4580
Eric Laurente0720872014-03-11 09:30:41 -07004581bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004582 uint32_t inPastMs,
4583 nsecs_t sysTime) const
4584{
4585 if ((sysTime == 0) && (inPastMs != 0)) {
4586 sysTime = systemTime();
4587 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004588 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4589 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004590 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004591 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004592 return true;
4593 }
4594 }
4595 return false;
4596}
4597
Eric Laurente0720872014-03-11 09:30:41 -07004598bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004599 uint32_t inPastMs,
4600 nsecs_t sysTime) const
4601{
4602 if (mRefCount[stream] != 0) {
4603 return true;
4604 }
4605 if (inPastMs == 0) {
4606 return false;
4607 }
4608 if (sysTime == 0) {
4609 sysTime = systemTime();
4610 }
4611 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4612 return true;
4613 }
4614 return false;
4615}
4616
Eric Laurent1c333e22014-05-20 10:48:17 -07004617void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004618 struct audio_port_config *dstConfig,
4619 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004620{
Eric Laurent84c70242014-06-23 08:46:27 -07004621 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4622
Eric Laurent1f2f2232014-06-02 12:01:23 -07004623 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4624 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4625 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004626 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004627 }
4628 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4629
Eric Laurent6a94d692014-05-20 11:18:06 -07004630 dstConfig->id = mId;
4631 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4632 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004633 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4634 dstConfig->ext.mix.handle = mIoHandle;
4635 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004636}
4637
4638void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4639 struct audio_port *port) const
4640{
Eric Laurent84c70242014-06-23 08:46:27 -07004641 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004642 mProfile->toAudioPort(port);
4643 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004644 toAudioPortConfig(&port->active_config);
4645 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004646 port->ext.mix.handle = mIoHandle;
4647 port->ext.mix.latency_class =
4648 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4649}
Eric Laurente552edb2014-03-10 17:42:56 -07004650
Eric Laurente0720872014-03-11 09:30:41 -07004651status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004652{
4653 const size_t SIZE = 256;
4654 char buffer[SIZE];
4655 String8 result;
4656
4657 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4658 result.append(buffer);
4659 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4660 result.append(buffer);
4661 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4662 result.append(buffer);
4663 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4664 result.append(buffer);
4665 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4666 result.append(buffer);
4667 snprintf(buffer, SIZE, " Devices %08x\n", device());
4668 result.append(buffer);
4669 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4670 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004671 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4672 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4673 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004674 result.append(buffer);
4675 }
4676 write(fd, result.string(), result.size());
4677
4678 return NO_ERROR;
4679}
4680
4681// --- AudioInputDescriptor class implementation
4682
Eric Laurent1c333e22014-05-20 10:48:17 -07004683AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004684 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004685 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004686 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004687{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004688 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004689 mAudioPort = profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004690 mSamplingRate = profile->mSamplingRates[0];
4691 mFormat = profile->mFormats[0];
4692 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004693 if (profile->mGains.size() > 0) {
4694 profile->mGains[0]->getDefaultConfig(&mGain);
4695 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004696 } else {
4697 mSamplingRate = 0;
4698 mFormat = AUDIO_FORMAT_DEFAULT;
4699 mChannelMask = 0;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004700 }
Eric Laurente552edb2014-03-10 17:42:56 -07004701}
4702
Eric Laurent1c333e22014-05-20 10:48:17 -07004703void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004704 struct audio_port_config *dstConfig,
4705 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004706{
Eric Laurent84c70242014-06-23 08:46:27 -07004707 ALOG_ASSERT(mProfile != 0,
4708 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004709 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4710 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4711 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004712 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004713 }
4714
4715 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4716
Eric Laurent6a94d692014-05-20 11:18:06 -07004717 dstConfig->id = mId;
4718 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4719 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004720 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4721 dstConfig->ext.mix.handle = mIoHandle;
4722 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004723}
4724
4725void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4726 struct audio_port *port) const
4727{
Eric Laurent84c70242014-06-23 08:46:27 -07004728 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4729
Eric Laurent1c333e22014-05-20 10:48:17 -07004730 mProfile->toAudioPort(port);
4731 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 toAudioPortConfig(&port->active_config);
4733 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004734 port->ext.mix.handle = mIoHandle;
4735 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4736}
4737
Eric Laurente0720872014-03-11 09:30:41 -07004738status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004739{
4740 const size_t SIZE = 256;
4741 char buffer[SIZE];
4742 String8 result;
4743
4744 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4745 result.append(buffer);
4746 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4747 result.append(buffer);
4748 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4749 result.append(buffer);
4750 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4751 result.append(buffer);
4752 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4753 result.append(buffer);
4754 write(fd, result.string(), result.size());
4755
4756 return NO_ERROR;
4757}
4758
4759// --- StreamDescriptor class implementation
4760
Eric Laurente0720872014-03-11 09:30:41 -07004761AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004762 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4763{
4764 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4765}
4766
Eric Laurente0720872014-03-11 09:30:41 -07004767int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004768{
Eric Laurente0720872014-03-11 09:30:41 -07004769 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004770 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4771 if (mIndexCur.indexOfKey(device) < 0) {
4772 device = AUDIO_DEVICE_OUT_DEFAULT;
4773 }
4774 return mIndexCur.valueFor(device);
4775}
4776
Eric Laurente0720872014-03-11 09:30:41 -07004777void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004778{
4779 const size_t SIZE = 256;
4780 char buffer[SIZE];
4781 String8 result;
4782
4783 snprintf(buffer, SIZE, "%s %02d %02d ",
4784 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4785 result.append(buffer);
4786 for (size_t i = 0; i < mIndexCur.size(); i++) {
4787 snprintf(buffer, SIZE, "%04x : %02d, ",
4788 mIndexCur.keyAt(i),
4789 mIndexCur.valueAt(i));
4790 result.append(buffer);
4791 }
4792 result.append("\n");
4793
4794 write(fd, result.string(), result.size());
4795}
4796
4797// --- EffectDescriptor class implementation
4798
Eric Laurente0720872014-03-11 09:30:41 -07004799status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004800{
4801 const size_t SIZE = 256;
4802 char buffer[SIZE];
4803 String8 result;
4804
4805 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4806 result.append(buffer);
4807 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4808 result.append(buffer);
4809 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4810 result.append(buffer);
4811 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4812 result.append(buffer);
4813 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4814 result.append(buffer);
4815 write(fd, result.string(), result.size());
4816
4817 return NO_ERROR;
4818}
4819
Eric Laurent1c333e22014-05-20 10:48:17 -07004820// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004821
Eric Laurente0720872014-03-11 09:30:41 -07004822AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004823 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4824 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004825{
4826}
4827
Eric Laurente0720872014-03-11 09:30:41 -07004828AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004829{
4830 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004831 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004832 }
4833 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004834 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004835 }
4836 free((void *)mName);
4837}
4838
Eric Laurent1afeecb2014-05-14 08:52:28 -07004839status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4840{
4841 cnode *node = root->first_child;
4842
4843 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4844
4845 while (node) {
4846 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4847 profile->loadSamplingRates((char *)node->value);
4848 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4849 profile->loadFormats((char *)node->value);
4850 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4851 profile->loadInChannels((char *)node->value);
4852 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4853 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4854 mDeclaredDevices);
4855 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4856 profile->loadGains(node);
4857 }
4858 node = node->next;
4859 }
4860 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4861 "loadInput() invalid supported devices");
4862 ALOGW_IF(profile->mChannelMasks.size() == 0,
4863 "loadInput() invalid supported channel masks");
4864 ALOGW_IF(profile->mSamplingRates.size() == 0,
4865 "loadInput() invalid supported sampling rates");
4866 ALOGW_IF(profile->mFormats.size() == 0,
4867 "loadInput() invalid supported formats");
4868 if (!profile->mSupportedDevices.isEmpty() &&
4869 (profile->mChannelMasks.size() != 0) &&
4870 (profile->mSamplingRates.size() != 0) &&
4871 (profile->mFormats.size() != 0)) {
4872
4873 ALOGV("loadInput() adding input Supported Devices %04x",
4874 profile->mSupportedDevices.types());
4875
4876 mInputProfiles.add(profile);
4877 return NO_ERROR;
4878 } else {
4879 return BAD_VALUE;
4880 }
4881}
4882
4883status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4884{
4885 cnode *node = root->first_child;
4886
4887 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4888
4889 while (node) {
4890 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4891 profile->loadSamplingRates((char *)node->value);
4892 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4893 profile->loadFormats((char *)node->value);
4894 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4895 profile->loadOutChannels((char *)node->value);
4896 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4897 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4898 mDeclaredDevices);
4899 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4900 profile->mFlags = parseFlagNames((char *)node->value);
4901 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4902 profile->loadGains(node);
4903 }
4904 node = node->next;
4905 }
4906 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4907 "loadOutput() invalid supported devices");
4908 ALOGW_IF(profile->mChannelMasks.size() == 0,
4909 "loadOutput() invalid supported channel masks");
4910 ALOGW_IF(profile->mSamplingRates.size() == 0,
4911 "loadOutput() invalid supported sampling rates");
4912 ALOGW_IF(profile->mFormats.size() == 0,
4913 "loadOutput() invalid supported formats");
4914 if (!profile->mSupportedDevices.isEmpty() &&
4915 (profile->mChannelMasks.size() != 0) &&
4916 (profile->mSamplingRates.size() != 0) &&
4917 (profile->mFormats.size() != 0)) {
4918
4919 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4920 profile->mSupportedDevices.types(), profile->mFlags);
4921
4922 mOutputProfiles.add(profile);
4923 return NO_ERROR;
4924 } else {
4925 return BAD_VALUE;
4926 }
4927}
4928
4929status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4930{
4931 cnode *node = root->first_child;
4932
4933 audio_devices_t type = AUDIO_DEVICE_NONE;
4934 while (node) {
4935 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4936 type = parseDeviceNames((char *)node->value);
4937 break;
4938 }
4939 node = node->next;
4940 }
4941 if (type == AUDIO_DEVICE_NONE ||
4942 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4943 ALOGW("loadDevice() bad type %08x", type);
4944 return BAD_VALUE;
4945 }
4946 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4947 deviceDesc->mModule = this;
4948
4949 node = root->first_child;
4950 while (node) {
4951 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4952 deviceDesc->mAddress = String8((char *)node->value);
4953 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4954 if (audio_is_input_device(type)) {
4955 deviceDesc->loadInChannels((char *)node->value);
4956 } else {
4957 deviceDesc->loadOutChannels((char *)node->value);
4958 }
4959 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4960 deviceDesc->loadGains(node);
4961 }
4962 node = node->next;
4963 }
4964
4965 ALOGV("loadDevice() adding device name %s type %08x address %s",
4966 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4967
4968 mDeclaredDevices.add(deviceDesc);
4969
4970 return NO_ERROR;
4971}
4972
Eric Laurente0720872014-03-11 09:30:41 -07004973void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004974{
4975 const size_t SIZE = 256;
4976 char buffer[SIZE];
4977 String8 result;
4978
4979 snprintf(buffer, SIZE, " - name: %s\n", mName);
4980 result.append(buffer);
4981 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4982 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07004983 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
4984 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07004985 write(fd, result.string(), result.size());
4986 if (mOutputProfiles.size()) {
4987 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4988 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004989 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004990 write(fd, buffer, strlen(buffer));
4991 mOutputProfiles[i]->dump(fd);
4992 }
4993 }
4994 if (mInputProfiles.size()) {
4995 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4996 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004997 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004998 write(fd, buffer, strlen(buffer));
4999 mInputProfiles[i]->dump(fd);
5000 }
5001 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005002 if (mDeclaredDevices.size()) {
5003 write(fd, " - devices:\n", strlen(" - devices:\n"));
5004 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5005 mDeclaredDevices[i]->dump(fd, 4, i);
5006 }
5007 }
Eric Laurente552edb2014-03-10 17:42:56 -07005008}
5009
Eric Laurent1c333e22014-05-20 10:48:17 -07005010// --- AudioPort class implementation
5011
Eric Laurenta121f902014-06-03 13:32:54 -07005012
5013AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5014 audio_port_role_t role, const sp<HwModule>& module) :
5015 mName(name), mType(type), mRole(role), mModule(module)
5016{
5017 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5018 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5019}
5020
Eric Laurent1c333e22014-05-20 10:48:17 -07005021void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5022{
5023 port->role = mRole;
5024 port->type = mType;
5025 unsigned int i;
5026 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5027 port->sample_rates[i] = mSamplingRates[i];
5028 }
5029 port->num_sample_rates = i;
5030 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5031 port->channel_masks[i] = mChannelMasks[i];
5032 }
5033 port->num_channel_masks = i;
5034 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5035 port->formats[i] = mFormats[i];
5036 }
5037 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005038
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005039 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005040
5041 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5042 port->gains[i] = mGains[i]->mGain;
5043 }
5044 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005045}
5046
5047
5048void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5049{
5050 char *str = strtok(name, "|");
5051
5052 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5053 // rates should be read from the output stream after it is opened for the first time
5054 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5055 mSamplingRates.add(0);
5056 return;
5057 }
5058
5059 while (str != NULL) {
5060 uint32_t rate = atoi(str);
5061 if (rate != 0) {
5062 ALOGV("loadSamplingRates() adding rate %d", rate);
5063 mSamplingRates.add(rate);
5064 }
5065 str = strtok(NULL, "|");
5066 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005067}
5068
5069void AudioPolicyManager::AudioPort::loadFormats(char *name)
5070{
5071 char *str = strtok(name, "|");
5072
5073 // by convention, "0' in the first entry in mFormats indicates the supported formats
5074 // should be read from the output stream after it is opened for the first time
5075 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5076 mFormats.add(AUDIO_FORMAT_DEFAULT);
5077 return;
5078 }
5079
5080 while (str != NULL) {
5081 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5082 ARRAY_SIZE(sFormatNameToEnumTable),
5083 str);
5084 if (format != AUDIO_FORMAT_DEFAULT) {
5085 mFormats.add(format);
5086 }
5087 str = strtok(NULL, "|");
5088 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005089}
5090
5091void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5092{
5093 const char *str = strtok(name, "|");
5094
5095 ALOGV("loadInChannels() %s", name);
5096
5097 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5098 mChannelMasks.add(0);
5099 return;
5100 }
5101
5102 while (str != NULL) {
5103 audio_channel_mask_t channelMask =
5104 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5105 ARRAY_SIZE(sInChannelsNameToEnumTable),
5106 str);
5107 if (channelMask != 0) {
5108 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5109 mChannelMasks.add(channelMask);
5110 }
5111 str = strtok(NULL, "|");
5112 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005113}
5114
5115void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5116{
5117 const char *str = strtok(name, "|");
5118
5119 ALOGV("loadOutChannels() %s", name);
5120
5121 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5122 // masks should be read from the output stream after it is opened for the first time
5123 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5124 mChannelMasks.add(0);
5125 return;
5126 }
5127
5128 while (str != NULL) {
5129 audio_channel_mask_t channelMask =
5130 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5131 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5132 str);
5133 if (channelMask != 0) {
5134 mChannelMasks.add(channelMask);
5135 }
5136 str = strtok(NULL, "|");
5137 }
5138 return;
5139}
5140
Eric Laurent1afeecb2014-05-14 08:52:28 -07005141audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5142{
5143 const char *str = strtok(name, "|");
5144
5145 ALOGV("loadGainMode() %s", name);
5146 audio_gain_mode_t mode = 0;
5147 while (str != NULL) {
5148 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5149 ARRAY_SIZE(sGainModeNameToEnumTable),
5150 str);
5151 str = strtok(NULL, "|");
5152 }
5153 return mode;
5154}
5155
Eric Laurenta121f902014-06-03 13:32:54 -07005156void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005157{
5158 cnode *node = root->first_child;
5159
Eric Laurenta121f902014-06-03 13:32:54 -07005160 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005161
5162 while (node) {
5163 if (strcmp(node->name, GAIN_MODE) == 0) {
5164 gain->mGain.mode = loadGainMode((char *)node->value);
5165 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005166 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005167 gain->mGain.channel_mask =
5168 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5169 ARRAY_SIZE(sInChannelsNameToEnumTable),
5170 (char *)node->value);
5171 } else {
5172 gain->mGain.channel_mask =
5173 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5174 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5175 (char *)node->value);
5176 }
5177 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5178 gain->mGain.min_value = atoi((char *)node->value);
5179 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5180 gain->mGain.max_value = atoi((char *)node->value);
5181 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5182 gain->mGain.default_value = atoi((char *)node->value);
5183 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5184 gain->mGain.step_value = atoi((char *)node->value);
5185 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5186 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5187 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5188 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5189 }
5190 node = node->next;
5191 }
5192
5193 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5194 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5195
5196 if (gain->mGain.mode == 0) {
5197 return;
5198 }
5199 mGains.add(gain);
5200}
5201
5202void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5203{
5204 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005205 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005206 while (node) {
5207 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005208 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005209 node = node->next;
5210 }
5211}
5212
Eric Laurenta121f902014-06-03 13:32:54 -07005213status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const
5214{
5215 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5216 if (mSamplingRates[i] == samplingRate) {
5217 return NO_ERROR;
5218 }
5219 }
5220 return BAD_VALUE;
5221}
5222
5223status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const
5224{
5225 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5226 if (mChannelMasks[i] == channelMask) {
5227 return NO_ERROR;
5228 }
5229 }
5230 return BAD_VALUE;
5231}
5232
5233status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5234{
5235 for (size_t i = 0; i < mFormats.size(); i ++) {
5236 if (mFormats[i] == format) {
5237 return NO_ERROR;
5238 }
5239 }
5240 return BAD_VALUE;
5241}
5242
5243status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5244 int index) const
5245{
5246 if (index < 0 || (size_t)index >= mGains.size()) {
5247 return BAD_VALUE;
5248 }
5249 return mGains[index]->checkConfig(gainConfig);
5250}
5251
Eric Laurent1afeecb2014-05-14 08:52:28 -07005252void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5253{
5254 const size_t SIZE = 256;
5255 char buffer[SIZE];
5256 String8 result;
5257
5258 if (mName.size() != 0) {
5259 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5260 result.append(buffer);
5261 }
5262
5263 if (mSamplingRates.size() != 0) {
5264 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5265 result.append(buffer);
5266 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5267 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5268 result.append(buffer);
5269 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5270 }
5271 result.append("\n");
5272 }
5273
5274 if (mChannelMasks.size() != 0) {
5275 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5276 result.append(buffer);
5277 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5278 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5279 result.append(buffer);
5280 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5281 }
5282 result.append("\n");
5283 }
5284
5285 if (mFormats.size() != 0) {
5286 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5287 result.append(buffer);
5288 for (size_t i = 0; i < mFormats.size(); i++) {
5289 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5290 ARRAY_SIZE(sFormatNameToEnumTable),
5291 mFormats[i]));
5292 result.append(buffer);
5293 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5294 }
5295 result.append("\n");
5296 }
5297 write(fd, result.string(), result.size());
5298 if (mGains.size() != 0) {
5299 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5300 write(fd, buffer, strlen(buffer) + 1);
5301 result.append(buffer);
5302 for (size_t i = 0; i < mGains.size(); i++) {
5303 mGains[i]->dump(fd, spaces + 2, i);
5304 }
5305 }
5306}
5307
5308// --- AudioGain class implementation
5309
Eric Laurenta121f902014-06-03 13:32:54 -07005310AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005311{
Eric Laurenta121f902014-06-03 13:32:54 -07005312 mIndex = index;
5313 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005314 memset(&mGain, 0, sizeof(struct audio_gain));
5315}
5316
Eric Laurenta121f902014-06-03 13:32:54 -07005317void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5318{
5319 config->index = mIndex;
5320 config->mode = mGain.mode;
5321 config->channel_mask = mGain.channel_mask;
5322 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5323 config->values[0] = mGain.default_value;
5324 } else {
5325 uint32_t numValues;
5326 if (mUseInChannelMask) {
5327 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5328 } else {
5329 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5330 }
5331 for (size_t i = 0; i < numValues; i++) {
5332 config->values[i] = mGain.default_value;
5333 }
5334 }
5335 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5336 config->ramp_duration_ms = mGain.min_ramp_ms;
5337 }
5338}
5339
5340status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5341{
5342 if ((config->mode & ~mGain.mode) != 0) {
5343 return BAD_VALUE;
5344 }
5345 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5346 if ((config->values[0] < mGain.min_value) ||
5347 (config->values[0] > mGain.max_value)) {
5348 return BAD_VALUE;
5349 }
5350 } else {
5351 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5352 return BAD_VALUE;
5353 }
5354 uint32_t numValues;
5355 if (mUseInChannelMask) {
5356 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5357 } else {
5358 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5359 }
5360 for (size_t i = 0; i < numValues; i++) {
5361 if ((config->values[i] < mGain.min_value) ||
5362 (config->values[i] > mGain.max_value)) {
5363 return BAD_VALUE;
5364 }
5365 }
5366 }
5367 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5368 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5369 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5370 return BAD_VALUE;
5371 }
5372 }
5373 return NO_ERROR;
5374}
5375
Eric Laurent1afeecb2014-05-14 08:52:28 -07005376void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5377{
5378 const size_t SIZE = 256;
5379 char buffer[SIZE];
5380 String8 result;
5381
5382 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5383 result.append(buffer);
5384 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5385 result.append(buffer);
5386 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5387 result.append(buffer);
5388 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5389 result.append(buffer);
5390 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5391 result.append(buffer);
5392 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5393 result.append(buffer);
5394 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5395 result.append(buffer);
5396 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5397 result.append(buffer);
5398 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5399 result.append(buffer);
5400
5401 write(fd, result.string(), result.size());
5402}
5403
Eric Laurent1f2f2232014-06-02 12:01:23 -07005404// --- AudioPortConfig class implementation
5405
5406AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5407{
5408 mSamplingRate = 0;
5409 mChannelMask = AUDIO_CHANNEL_NONE;
5410 mFormat = AUDIO_FORMAT_INVALID;
5411 mGain.index = -1;
5412}
5413
Eric Laurenta121f902014-06-03 13:32:54 -07005414status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5415 const struct audio_port_config *config,
5416 struct audio_port_config *backupConfig)
5417{
5418 struct audio_port_config localBackupConfig;
5419 status_t status = NO_ERROR;
5420
5421 localBackupConfig.config_mask = config->config_mask;
5422 toAudioPortConfig(&localBackupConfig);
5423
5424 if (mAudioPort == 0) {
5425 status = NO_INIT;
5426 goto exit;
5427 }
5428 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5429 status = mAudioPort->checkSamplingRate(config->sample_rate);
5430 if (status != NO_ERROR) {
5431 goto exit;
5432 }
5433 mSamplingRate = config->sample_rate;
5434 }
5435 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5436 status = mAudioPort->checkChannelMask(config->channel_mask);
5437 if (status != NO_ERROR) {
5438 goto exit;
5439 }
5440 mChannelMask = config->channel_mask;
5441 }
5442 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5443 status = mAudioPort->checkFormat(config->format);
5444 if (status != NO_ERROR) {
5445 goto exit;
5446 }
5447 mFormat = config->format;
5448 }
5449 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5450 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5451 if (status != NO_ERROR) {
5452 goto exit;
5453 }
5454 mGain = config->gain;
5455 }
5456
5457exit:
5458 if (status != NO_ERROR) {
5459 applyAudioPortConfig(&localBackupConfig);
5460 }
5461 if (backupConfig != NULL) {
5462 *backupConfig = localBackupConfig;
5463 }
5464 return status;
5465}
5466
Eric Laurent1f2f2232014-06-02 12:01:23 -07005467void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5468 struct audio_port_config *dstConfig,
5469 const struct audio_port_config *srcConfig) const
5470{
5471 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5472 dstConfig->sample_rate = mSamplingRate;
5473 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5474 dstConfig->sample_rate = srcConfig->sample_rate;
5475 }
5476 } else {
5477 dstConfig->sample_rate = 0;
5478 }
5479 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5480 dstConfig->channel_mask = mChannelMask;
5481 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5482 dstConfig->channel_mask = srcConfig->channel_mask;
5483 }
5484 } else {
5485 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5486 }
5487 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5488 dstConfig->format = mFormat;
5489 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5490 dstConfig->format = srcConfig->format;
5491 }
5492 } else {
5493 dstConfig->format = AUDIO_FORMAT_INVALID;
5494 }
5495 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5496 dstConfig->gain = mGain;
5497 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5498 dstConfig->gain = srcConfig->gain;
5499 }
5500 } else {
5501 dstConfig->gain.index = -1;
5502 }
5503 if (dstConfig->gain.index != -1) {
5504 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5505 } else {
5506 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5507 }
5508}
5509
Eric Laurent1c333e22014-05-20 10:48:17 -07005510// --- IOProfile class implementation
5511
Eric Laurent1afeecb2014-05-14 08:52:28 -07005512AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005513 const sp<HwModule>& module)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005514 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005515{
5516}
5517
Eric Laurente0720872014-03-11 09:30:41 -07005518AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005519{
5520}
5521
5522// checks if the IO profile is compatible with specified parameters.
5523// Sampling rate, format and channel mask must be specified in order to
5524// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005525bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005526 uint32_t samplingRate,
5527 audio_format_t format,
5528 audio_channel_mask_t channelMask,
5529 audio_output_flags_t flags) const
5530{
5531 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5532 return false;
5533 }
5534
Eric Laurent3a4311c2014-03-17 12:00:47 -07005535 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005536 return false;
5537 }
5538 if ((mFlags & flags) != flags) {
5539 return false;
5540 }
Eric Laurenta121f902014-06-03 13:32:54 -07005541 if (checkSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005542 return false;
5543 }
Eric Laurenta121f902014-06-03 13:32:54 -07005544 if (checkChannelMask(channelMask) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005545 return false;
5546 }
Eric Laurenta121f902014-06-03 13:32:54 -07005547 if (checkFormat(format) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005548 return false;
5549 }
5550 return true;
5551}
5552
Eric Laurente0720872014-03-11 09:30:41 -07005553void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005554{
5555 const size_t SIZE = 256;
5556 char buffer[SIZE];
5557 String8 result;
5558
Eric Laurent1afeecb2014-05-14 08:52:28 -07005559 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005560
Eric Laurente552edb2014-03-10 17:42:56 -07005561 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5562 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005563 snprintf(buffer, SIZE, " - devices:\n");
5564 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005565 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005566 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5567 mSupportedDevices[i]->dump(fd, 6, i);
5568 }
Eric Laurente552edb2014-03-10 17:42:56 -07005569}
5570
Eric Laurentd4692962014-05-05 18:13:44 -07005571void AudioPolicyManager::IOProfile::log()
5572{
5573 const size_t SIZE = 256;
5574 char buffer[SIZE];
5575 String8 result;
5576
5577 ALOGV(" - sampling rates: ");
5578 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5579 ALOGV(" %d", mSamplingRates[i]);
5580 }
5581
5582 ALOGV(" - channel masks: ");
5583 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5584 ALOGV(" 0x%04x", mChannelMasks[i]);
5585 }
5586
5587 ALOGV(" - formats: ");
5588 for (size_t i = 0; i < mFormats.size(); i++) {
5589 ALOGV(" 0x%08x", mFormats[i]);
5590 }
5591
5592 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5593 ALOGV(" - flags: 0x%04x\n", mFlags);
5594}
5595
5596
Eric Laurent3a4311c2014-03-17 12:00:47 -07005597// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005598
Eric Laurent1f2f2232014-06-02 12:01:23 -07005599
5600AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5601 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5602 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5603 AUDIO_PORT_ROLE_SOURCE,
5604 NULL),
5605 mDeviceType(type), mAddress(""),
5606 mChannelMask(AUDIO_CHANNEL_NONE), mId(0)
5607{
5608 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005609 if (mGains.size() > 0) {
5610 mGains[0]->getDefaultConfig(&mGain);
5611 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005612}
5613
Eric Laurent3a4311c2014-03-17 12:00:47 -07005614bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005615{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005616 // Devices are considered equal if they:
5617 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5618 // - have the same address or one device does not specify the address
5619 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005620 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005621 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005622 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005623 mChannelMask == other->mChannelMask);
5624}
5625
5626void AudioPolicyManager::DeviceVector::refreshTypes()
5627{
Eric Laurent1c333e22014-05-20 10:48:17 -07005628 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005629 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005630 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005631 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005632 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005633}
5634
5635ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5636{
5637 for(size_t i = 0; i < size(); i++) {
5638 if (item->equals(itemAt(i))) {
5639 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005640 }
5641 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005642 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005643}
5644
Eric Laurent3a4311c2014-03-17 12:00:47 -07005645ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005646{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005647 ssize_t ret = indexOf(item);
5648
5649 if (ret < 0) {
5650 ret = SortedVector::add(item);
5651 if (ret >= 0) {
5652 refreshTypes();
5653 }
5654 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005655 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005656 ret = -1;
5657 }
5658 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005659}
5660
Eric Laurent3a4311c2014-03-17 12:00:47 -07005661ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5662{
5663 size_t i;
5664 ssize_t ret = indexOf(item);
5665
5666 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005667 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005668 } else {
5669 ret = SortedVector::removeAt(ret);
5670 if (ret >= 0) {
5671 refreshTypes();
5672 }
5673 }
5674 return ret;
5675}
5676
5677void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5678{
5679 DeviceVector deviceList;
5680
5681 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5682 types &= ~role_bit;
5683
5684 while (types) {
5685 uint32_t i = 31 - __builtin_clz(types);
5686 uint32_t type = 1 << i;
5687 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005688 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005689 }
5690}
5691
Eric Laurent1afeecb2014-05-14 08:52:28 -07005692void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5693 const DeviceVector& declaredDevices)
5694{
5695 char *devName = strtok(name, "|");
5696 while (devName != NULL) {
5697 if (strlen(devName) != 0) {
5698 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5699 ARRAY_SIZE(sDeviceNameToEnumTable),
5700 devName);
5701 if (type != AUDIO_DEVICE_NONE) {
5702 add(new DeviceDescriptor(String8(""), type));
5703 } else {
5704 sp<DeviceDescriptor> deviceDesc =
5705 declaredDevices.getDeviceFromName(String8(devName));
5706 if (deviceDesc != 0) {
5707 add(deviceDesc);
5708 }
5709 }
5710 }
5711 devName = strtok(NULL, "|");
5712 }
5713}
5714
Eric Laurent1c333e22014-05-20 10:48:17 -07005715sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5716 audio_devices_t type, String8 address) const
5717{
5718 sp<DeviceDescriptor> device;
5719 for (size_t i = 0; i < size(); i++) {
5720 if (itemAt(i)->mDeviceType == type) {
5721 device = itemAt(i);
5722 if (itemAt(i)->mAddress = address) {
5723 break;
5724 }
5725 }
5726 }
5727 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5728 type, address.string(), device.get());
5729 return device;
5730}
5731
Eric Laurent6a94d692014-05-20 11:18:06 -07005732sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5733 audio_port_handle_t id) const
5734{
5735 sp<DeviceDescriptor> device;
5736 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005737 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07005738 if (itemAt(i)->mId == id) {
5739 device = itemAt(i);
5740 break;
5741 }
5742 }
5743 return device;
5744}
5745
Eric Laurent1c333e22014-05-20 10:48:17 -07005746AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5747 audio_devices_t type) const
5748{
5749 DeviceVector devices;
5750 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5751 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5752 devices.add(itemAt(i));
5753 type &= ~itemAt(i)->mDeviceType;
5754 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5755 itemAt(i)->mDeviceType, itemAt(i).get());
5756 }
5757 }
5758 return devices;
5759}
5760
Eric Laurent1afeecb2014-05-14 08:52:28 -07005761sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5762 const String8& name) const
5763{
5764 sp<DeviceDescriptor> device;
5765 for (size_t i = 0; i < size(); i++) {
5766 if (itemAt(i)->mName == name) {
5767 device = itemAt(i);
5768 break;
5769 }
5770 }
5771 return device;
5772}
5773
Eric Laurent6a94d692014-05-20 11:18:06 -07005774void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5775 struct audio_port_config *dstConfig,
5776 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005777{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005778 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
5779 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005780 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005781 }
5782
5783 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5784
Eric Laurent6a94d692014-05-20 11:18:06 -07005785 dstConfig->id = mId;
5786 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005787 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005788 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005789 dstConfig->ext.device.type = mDeviceType;
5790 dstConfig->ext.device.hw_module = mModule->mHandle;
5791 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005792}
5793
5794void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5795{
Eric Laurente1715a42014-05-20 11:30:42 -07005796 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07005797 AudioPort::toAudioPort(port);
5798 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005799 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005800 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005801 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005802 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5803}
5804
Eric Laurent1afeecb2014-05-14 08:52:28 -07005805status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005806{
5807 const size_t SIZE = 256;
5808 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005809 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005810
Eric Laurent1afeecb2014-05-14 08:52:28 -07005811 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5812 result.append(buffer);
5813 if (mId != 0) {
5814 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5815 result.append(buffer);
5816 }
5817 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5818 enumToString(sDeviceNameToEnumTable,
5819 ARRAY_SIZE(sDeviceNameToEnumTable),
5820 mDeviceType));
5821 result.append(buffer);
5822 if (mAddress.size() != 0) {
5823 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5824 result.append(buffer);
5825 }
5826 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5827 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5828 result.append(buffer);
5829 }
5830 write(fd, result.string(), result.size());
5831 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005832
5833 return NO_ERROR;
5834}
5835
5836
5837// --- audio_policy.conf file parsing
5838
Eric Laurente0720872014-03-11 09:30:41 -07005839audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005840{
5841 uint32_t flag = 0;
5842
5843 // it is OK to cast name to non const here as we are not going to use it after
5844 // strtok() modifies it
5845 char *flagName = strtok(name, "|");
5846 while (flagName != NULL) {
5847 if (strlen(flagName) != 0) {
5848 flag |= stringToEnum(sFlagNameToEnumTable,
5849 ARRAY_SIZE(sFlagNameToEnumTable),
5850 flagName);
5851 }
5852 flagName = strtok(NULL, "|");
5853 }
5854 //force direct flag if offload flag is set: offloading implies a direct output stream
5855 // and all common behaviors are driven by checking only the direct flag
5856 // this should normally be set appropriately in the policy configuration file
5857 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5858 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5859 }
5860
5861 return (audio_output_flags_t)flag;
5862}
5863
Eric Laurente0720872014-03-11 09:30:41 -07005864audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005865{
5866 uint32_t device = 0;
5867
5868 char *devName = strtok(name, "|");
5869 while (devName != NULL) {
5870 if (strlen(devName) != 0) {
5871 device |= stringToEnum(sDeviceNameToEnumTable,
5872 ARRAY_SIZE(sDeviceNameToEnumTable),
5873 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005874 }
Eric Laurente552edb2014-03-10 17:42:56 -07005875 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005876 }
Eric Laurente552edb2014-03-10 17:42:56 -07005877 return device;
5878}
5879
Eric Laurente0720872014-03-11 09:30:41 -07005880void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005881{
Eric Laurente552edb2014-03-10 17:42:56 -07005882 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005883 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005884 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07005885
Eric Laurent1afeecb2014-05-14 08:52:28 -07005886 node = config_find(root, DEVICES_TAG);
5887 if (node != NULL) {
5888 node = node->first_child;
5889 while (node) {
5890 ALOGV("loadHwModule() loading device %s", node->name);
5891 status_t tmpStatus = module->loadDevice(node);
5892 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5893 status = tmpStatus;
5894 }
5895 node = node->next;
5896 }
5897 }
5898 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005899 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005900 node = node->first_child;
5901 while (node) {
5902 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005903 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005904 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5905 status = tmpStatus;
5906 }
5907 node = node->next;
5908 }
5909 }
5910 node = config_find(root, INPUTS_TAG);
5911 if (node != NULL) {
5912 node = node->first_child;
5913 while (node) {
5914 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005915 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005916 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5917 status = tmpStatus;
5918 }
5919 node = node->next;
5920 }
5921 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005922 loadGlobalConfig(root, module);
5923
Eric Laurente552edb2014-03-10 17:42:56 -07005924 if (status == NO_ERROR) {
5925 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07005926 }
5927}
5928
Eric Laurente0720872014-03-11 09:30:41 -07005929void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005930{
5931 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5932 if (node == NULL) {
5933 return;
5934 }
5935
5936 node = node->first_child;
5937 while (node) {
5938 ALOGV("loadHwModules() loading module %s", node->name);
5939 loadHwModule(node);
5940 node = node->next;
5941 }
5942}
5943
Eric Laurent1f2f2232014-06-02 12:01:23 -07005944void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07005945{
5946 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07005947
Eric Laurente552edb2014-03-10 17:42:56 -07005948 if (node == NULL) {
5949 return;
5950 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005951 DeviceVector declaredDevices;
5952 if (module != NULL) {
5953 declaredDevices = module->mDeclaredDevices;
5954 }
5955
Eric Laurente552edb2014-03-10 17:42:56 -07005956 node = node->first_child;
5957 while (node) {
5958 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005959 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5960 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005961 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5962 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005963 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005964 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005965 ARRAY_SIZE(sDeviceNameToEnumTable),
5966 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005967 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005968 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005969 } else {
5970 ALOGW("loadGlobalConfig() default device not specified");
5971 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005972 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005973 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005974 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5975 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005976 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005977 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5978 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5979 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07005980 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
5981 uint32_t major, minor;
5982 sscanf((char *)node->value, "%u.%u", &major, &minor);
5983 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
5984 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
5985 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07005986 }
5987 node = node->next;
5988 }
5989}
5990
Eric Laurente0720872014-03-11 09:30:41 -07005991status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005992{
5993 cnode *root;
5994 char *data;
5995
5996 data = (char *)load_file(path, NULL);
5997 if (data == NULL) {
5998 return -ENODEV;
5999 }
6000 root = config_node("", "");
6001 config_load(root, data);
6002
Eric Laurente552edb2014-03-10 17:42:56 -07006003 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006004 // legacy audio_policy.conf files have one global_configuration section
6005 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006006 config_free(root);
6007 free(root);
6008 free(data);
6009
6010 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6011
6012 return NO_ERROR;
6013}
6014
Eric Laurente0720872014-03-11 09:30:41 -07006015void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006016{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006017 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006018 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006019 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6020 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006021 mAvailableOutputDevices.add(mDefaultOutputDevice);
6022 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006023
6024 module = new HwModule("primary");
6025
Eric Laurent1afeecb2014-05-14 08:52:28 -07006026 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006027 profile->mSamplingRates.add(44100);
6028 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6029 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006030 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006031 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6032 module->mOutputProfiles.add(profile);
6033
Eric Laurent1afeecb2014-05-14 08:52:28 -07006034 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006035 profile->mSamplingRates.add(8000);
6036 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6037 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006038 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006039 module->mInputProfiles.add(profile);
6040
6041 mHwModules.add(module);
6042}
6043
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006044audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6045{
6046 // flags to stream type mapping
6047 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6048 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6049 }
6050 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6051 return AUDIO_STREAM_BLUETOOTH_SCO;
6052 }
6053
6054 // usage to stream type mapping
6055 switch (attr->usage) {
6056 case AUDIO_USAGE_MEDIA:
6057 case AUDIO_USAGE_GAME:
6058 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6059 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6060 return AUDIO_STREAM_MUSIC;
6061 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6062 return AUDIO_STREAM_SYSTEM;
6063 case AUDIO_USAGE_VOICE_COMMUNICATION:
6064 return AUDIO_STREAM_VOICE_CALL;
6065
6066 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6067 return AUDIO_STREAM_DTMF;
6068
6069 case AUDIO_USAGE_ALARM:
6070 return AUDIO_STREAM_ALARM;
6071 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6072 return AUDIO_STREAM_RING;
6073
6074 case AUDIO_USAGE_NOTIFICATION:
6075 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6076 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6077 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6078 case AUDIO_USAGE_NOTIFICATION_EVENT:
6079 return AUDIO_STREAM_NOTIFICATION;
6080
6081 case AUDIO_USAGE_UNKNOWN:
6082 default:
6083 return AUDIO_STREAM_MUSIC;
6084 }
6085}
Eric Laurente552edb2014-03-10 17:42:56 -07006086}; // namespace android