blob: aa976b56a78c0fdf0bc0c55c7c13f32a2da1e03f [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
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070085 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070090 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
92 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070096 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700104 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700105 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700109 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700111};
112
113const StringToEnum sFlagNameToEnumTable[] = {
114 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
120};
121
122const StringToEnum sFormatNameToEnumTable[] = {
123 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
124 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
128 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
129 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
130 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530131 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700141 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700142 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
143 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
144 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
145 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
146 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700147};
148
149const StringToEnum sOutChannelsNameToEnumTable[] = {
150 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
151 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
154 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
155};
156
157const StringToEnum sInChannelsNameToEnumTable[] = {
158 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
159 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
161};
162
Eric Laurent1afeecb2014-05-14 08:52:28 -0700163const StringToEnum sGainModeNameToEnumTable[] = {
164 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
165 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
166 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
167};
168
Eric Laurent3a4311c2014-03-17 12:00:47 -0700169
170uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
171 size_t size,
172 const char *name)
173{
174 for (size_t i = 0; i < size; i++) {
175 if (strcmp(table[i].name, name) == 0) {
176 ALOGV("stringToEnum() found %s", table[i].name);
177 return table[i].value;
178 }
179 }
180 return 0;
181}
182
183const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
184 size_t size,
185 uint32_t value)
186{
187 for (size_t i = 0; i < size; i++) {
188 if (table[i].value == value) {
189 return table[i].name;
190 }
191 }
192 return "";
193}
194
195bool AudioPolicyManager::stringToBool(const char *value)
196{
197 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
198}
199
200
201// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700202// AudioPolicyInterface implementation
203// ----------------------------------------------------------------------------
204
205
Eric Laurente0720872014-03-11 09:30:41 -0700206status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700207 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700208 const char *device_address)
209{
Eric Laurent22226012014-08-01 17:00:54 -0700210 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700211
Eric Laurent22226012014-08-01 17:00:54 -0700212 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
213 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700214
215 // connect/disconnect only 1 device at a time
216 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
217
Eric Laurente552edb2014-03-10 17:42:56 -0700218 // handle output devices
219 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700220 SortedVector <audio_io_handle_t> outputs;
221
Eric Laurent1afeecb2014-05-14 08:52:28 -0700222 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
223 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700224 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
225
Eric Laurente552edb2014-03-10 17:42:56 -0700226 // save a copy of the opened output descriptors before any output is opened or closed
227 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
228 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700229 switch (state)
230 {
231 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700234 ALOGW("setDeviceConnectionState() device already connected: %x", device);
235 return INVALID_OPERATION;
236 }
237 ALOGV("setDeviceConnectionState() connecting device %x", device);
238
Eric Laurente552edb2014-03-10 17:42:56 -0700239 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700240 index = mAvailableOutputDevices.add(devDesc);
241 if (index >= 0) {
242 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700243 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700244 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
245 "could not find HW module for device %08x", device);
246 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700247 } else {
248 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700249 }
250
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700251 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
252 mAvailableOutputDevices.remove(devDesc);
253 return INVALID_OPERATION;
254 }
255 // outputs should never be empty here
256 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
257 "checkOutputsForDevice() returned no outputs but status OK");
258 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
259 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700260 break;
261 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700262 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700263 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700264 ALOGW("setDeviceConnectionState() device not connected: %x", device);
265 return INVALID_OPERATION;
266 }
267
268 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
269 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700270 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700271
Eric Laurent3a4311c2014-03-17 12:00:47 -0700272 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700273 } break;
274
275 default:
276 ALOGE("setDeviceConnectionState() invalid state: %x", state);
277 return BAD_VALUE;
278 }
279
Eric Laurent3a4311c2014-03-17 12:00:47 -0700280 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
281 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700282 checkA2dpSuspend();
283 checkOutputForAllStrategies();
284 // outputs must be closed after checkOutputForAllStrategies() is executed
285 if (!outputs.isEmpty()) {
286 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700287 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700288 // close unused outputs after device disconnection or direct outputs that have been
289 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700290 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700291 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
292 (desc->mDirectOpenCount == 0))) {
293 closeOutput(outputs[i]);
294 }
295 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700296 // check again after closing A2DP output to reset mA2dpSuspended if needed
297 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700298 }
299
300 updateDevicesAndOutputs();
301 for (size_t i = 0; i < mOutputs.size(); i++) {
302 // do not force device change on duplicated output because if device is 0, it will
303 // also force a device 0 for the two outputs it is duplicated to which may override
304 // a valid device selection on those outputs.
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700305 bool force = !mOutputs.valueAt(i)->isDuplicated()
306 && (!deviceDistinguishesOnAddress(device)
307 // always force when disconnecting (a non-duplicated device)
308 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurente552edb2014-03-10 17:42:56 -0700309 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700310 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700311 force, 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700312 }
313
Eric Laurent72aa32f2014-05-30 18:51:48 -0700314 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700315 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700316 } // end if is output device
317
Eric Laurente552edb2014-03-10 17:42:56 -0700318 // handle input devices
319 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700320 SortedVector <audio_io_handle_t> inputs;
321
Eric Laurent1afeecb2014-05-14 08:52:28 -0700322 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
323 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700324 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700325 switch (state)
326 {
327 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700328 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700329 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700330 ALOGW("setDeviceConnectionState() device already connected: %d", device);
331 return INVALID_OPERATION;
332 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700333 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700334 if (module == NULL) {
335 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
336 device);
337 return INVALID_OPERATION;
338 }
Eric Laurentd4692962014-05-05 18:13:44 -0700339 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
340 return INVALID_OPERATION;
341 }
342
Eric Laurent3a4311c2014-03-17 12:00:47 -0700343 index = mAvailableInputDevices.add(devDesc);
344 if (index >= 0) {
345 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700346 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700347 } else {
348 return NO_MEMORY;
349 }
Eric Laurentd4692962014-05-05 18:13:44 -0700350 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700351
352 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700353 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700355 ALOGW("setDeviceConnectionState() device not connected: %d", device);
356 return INVALID_OPERATION;
357 }
Eric Laurentd4692962014-05-05 18:13:44 -0700358 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700360 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700361
362 default:
363 ALOGE("setDeviceConnectionState() invalid state: %x", state);
364 return BAD_VALUE;
365 }
366
Eric Laurentd4692962014-05-05 18:13:44 -0700367 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700368
Eric Laurentb52c1522014-05-20 11:27:36 -0700369 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700370 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700371 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700372
373 ALOGW("setDeviceConnectionState() invalid device: %x", device);
374 return BAD_VALUE;
375}
376
Eric Laurente0720872014-03-11 09:30:41 -0700377audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700378 const char *device_address)
379{
Eric Laurent3b73df72014-03-11 09:06:29 -0700380 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700381 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700382 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 ssize_t index;
384 DeviceVector *deviceVector;
385
Eric Laurente552edb2014-03-10 17:42:56 -0700386 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700388 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700389 deviceVector = &mAvailableInputDevices;
390 } else {
391 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
392 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700393 }
394
Eric Laurent3a4311c2014-03-17 12:00:47 -0700395 index = deviceVector->indexOf(devDesc);
396 if (index >= 0) {
397 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
398 } else {
399 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
400 }
Eric Laurente552edb2014-03-10 17:42:56 -0700401}
402
Eric Laurente0720872014-03-11 09:30:41 -0700403void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700404{
405 ALOGV("setPhoneState() state %d", state);
406 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700407 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700408 ALOGW("setPhoneState() invalid state %d", state);
409 return;
410 }
411
412 if (state == mPhoneState ) {
413 ALOGW("setPhoneState() setting same state %d", state);
414 return;
415 }
416
417 // if leaving call state, handle special case of active streams
418 // pertaining to sonification strategy see handleIncallSonification()
419 if (isInCall()) {
420 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700421 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
422 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700423 }
424 }
425
426 // store previous phone state for management of sonification strategy below
427 int oldState = mPhoneState;
428 mPhoneState = state;
429 bool force = false;
430
431 // are we entering or starting a call
432 if (!isStateInCall(oldState) && isStateInCall(state)) {
433 ALOGV(" Entering call in setPhoneState()");
434 // force routing command to audio hardware when starting a call
435 // even if no device change is needed
436 force = true;
437 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
438 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
439 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
440 }
441 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
442 ALOGV(" Exiting call in setPhoneState()");
443 // force routing command to audio hardware when exiting a call
444 // even if no device change is needed
445 force = true;
446 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
447 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
448 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
449 }
450 } else if (isStateInCall(state) && (state != oldState)) {
451 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
452 // force routing command to audio hardware when switching between telephony and VoIP
453 // even if no device change is needed
454 force = true;
455 }
456
457 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700458 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700459 checkA2dpSuspend();
460 checkOutputForAllStrategies();
461 updateDevicesAndOutputs();
462
Eric Laurent1f2f2232014-06-02 12:01:23 -0700463 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700464
465 // force routing command to audio hardware when ending call
466 // even if no device change is needed
467 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
468 newDevice = hwOutputDesc->device();
469 }
470
471 int delayMs = 0;
472 if (isStateInCall(state)) {
473 nsecs_t sysTime = systemTime();
474 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700475 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700476 // mute media and sonification strategies and delay device switch by the largest
477 // latency of any output where either strategy is active.
478 // This avoid sending the ring tone or music tail into the earpiece or headset.
479 if ((desc->isStrategyActive(STRATEGY_MEDIA,
480 SONIFICATION_HEADSET_MUSIC_DELAY,
481 sysTime) ||
482 desc->isStrategyActive(STRATEGY_SONIFICATION,
483 SONIFICATION_HEADSET_MUSIC_DELAY,
484 sysTime)) &&
485 (delayMs < (int)desc->mLatency*2)) {
486 delayMs = desc->mLatency*2;
487 }
488 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
489 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
490 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
491 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
492 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
493 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
494 }
495 }
496
497 // change routing is necessary
498 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
499
500 // if entering in call state, handle special case of active streams
501 // pertaining to sonification strategy see handleIncallSonification()
502 if (isStateInCall(state)) {
503 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700504 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
505 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700506 }
507 }
508
509 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700510 if (state == AUDIO_MODE_RINGTONE &&
511 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700512 mLimitRingtoneVolume = true;
513 } else {
514 mLimitRingtoneVolume = false;
515 }
516}
517
Eric Laurente0720872014-03-11 09:30:41 -0700518void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700519 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700520{
521 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
522
523 bool forceVolumeReeval = false;
524 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700525 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
526 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
527 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700528 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
529 return;
530 }
531 forceVolumeReeval = true;
532 mForceUse[usage] = config;
533 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700534 case AUDIO_POLICY_FORCE_FOR_MEDIA:
535 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
536 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
537 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
538 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900539 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
541 return;
542 }
543 mForceUse[usage] = config;
544 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700545 case AUDIO_POLICY_FORCE_FOR_RECORD:
546 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
547 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700548 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
549 return;
550 }
551 mForceUse[usage] = config;
552 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700553 case AUDIO_POLICY_FORCE_FOR_DOCK:
554 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
555 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
556 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
557 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
558 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700559 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
560 }
561 forceVolumeReeval = true;
562 mForceUse[usage] = config;
563 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700564 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
565 if (config != AUDIO_POLICY_FORCE_NONE &&
566 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700567 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
568 }
569 forceVolumeReeval = true;
570 mForceUse[usage] = config;
571 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900572 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
573 if (config != AUDIO_POLICY_FORCE_NONE &&
574 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
575 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
576 }
577 mForceUse[usage] = config;
578 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700579 default:
580 ALOGW("setForceUse() invalid usage %d", usage);
581 break;
582 }
583
584 // check for device and output changes triggered by new force usage
585 checkA2dpSuspend();
586 checkOutputForAllStrategies();
587 updateDevicesAndOutputs();
588 for (size_t i = 0; i < mOutputs.size(); i++) {
589 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700590 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700591 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
592 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
593 applyStreamVolumes(output, newDevice, 0, true);
594 }
595 }
596
597 audio_io_handle_t activeInput = getActiveInput();
598 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700599 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700600 }
601
602}
603
Eric Laurente0720872014-03-11 09:30:41 -0700604audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700605{
606 return mForceUse[usage];
607}
608
Eric Laurente0720872014-03-11 09:30:41 -0700609void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700610{
611 ALOGV("setSystemProperty() property %s, value %s", property, value);
612}
613
614// Find a direct output profile compatible with the parameters passed, even if the input flags do
615// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700616sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700617 audio_devices_t device,
618 uint32_t samplingRate,
619 audio_format_t format,
620 audio_channel_mask_t channelMask,
621 audio_output_flags_t flags)
622{
623 for (size_t i = 0; i < mHwModules.size(); i++) {
624 if (mHwModules[i]->mHandle == 0) {
625 continue;
626 }
627 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700628 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700629 bool found = profile->isCompatibleProfile(device, samplingRate,
630 NULL /*updatedSamplingRate*/, format, channelMask,
631 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
632 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700633 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
634 return profile;
635 }
Eric Laurente552edb2014-03-10 17:42:56 -0700636 }
637 }
638 return 0;
639}
640
Eric Laurente0720872014-03-11 09:30:41 -0700641audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700642 uint32_t samplingRate,
643 audio_format_t format,
644 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700645 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700646 const audio_offload_info_t *offloadInfo)
647{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700648
Eric Laurent3b73df72014-03-11 09:06:29 -0700649 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700650 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
651 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
652 device, stream, samplingRate, format, channelMask, flags);
653
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700654 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
655 offloadInfo);
656}
657
658audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
659 uint32_t samplingRate,
660 audio_format_t format,
661 audio_channel_mask_t channelMask,
662 audio_output_flags_t flags,
663 const audio_offload_info_t *offloadInfo)
664{
665 if (attr == NULL) {
666 ALOGE("getOutputForAttr() called with NULL audio attributes");
667 return 0;
668 }
669 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
670 attr->usage, attr->content_type, attr->tags);
671
672 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
673 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
674 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
675 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
676 device, samplingRate, format, channelMask, flags);
677
678 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
679 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
680 offloadInfo);
681}
682
683audio_io_handle_t AudioPolicyManager::getOutputForDevice(
684 audio_devices_t device,
685 audio_stream_type_t stream,
686 uint32_t samplingRate,
687 audio_format_t format,
688 audio_channel_mask_t channelMask,
689 audio_output_flags_t flags,
690 const audio_offload_info_t *offloadInfo)
691{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700692 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700693 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700694 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700695
Eric Laurente552edb2014-03-10 17:42:56 -0700696#ifdef AUDIO_POLICY_TEST
697 if (mCurOutput != 0) {
698 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
699 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
700
701 if (mTestOutputs[mCurOutput] == 0) {
702 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700703 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700704 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700705 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700706 outputDesc->mFlags =
707 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700708 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700709 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
710 config.sample_rate = mTestSamplingRate;
711 config.channel_mask = mTestChannels;
712 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700713 if (offloadInfo != NULL) {
714 config.offload_info = *offloadInfo;
715 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700716 status = mpClientInterface->openOutput(0,
717 &mTestOutputs[mCurOutput],
718 &config,
719 &outputDesc->mDevice,
720 String8(""),
721 &outputDesc->mLatency,
722 outputDesc->mFlags);
723 if (status == NO_ERROR) {
724 outputDesc->mSamplingRate = config.sample_rate;
725 outputDesc->mFormat = config.format;
726 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700727 AudioParameter outputCmd = AudioParameter();
728 outputCmd.addInt(String8("set_id"),mCurOutput);
729 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
730 addOutput(mTestOutputs[mCurOutput], outputDesc);
731 }
732 }
733 return mTestOutputs[mCurOutput];
734 }
735#endif //AUDIO_POLICY_TEST
736
737 // open a direct output if required by specified parameters
738 //force direct flag if offload flag is set: offloading implies a direct output stream
739 // and all common behaviors are driven by checking only the direct flag
740 // this should normally be set appropriately in the policy configuration file
741 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700742 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700743 }
744
745 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
746 // creating an offloaded track and tearing it down immediately after start when audioflinger
747 // detects there is an active non offloadable effect.
748 // FIXME: We should check the audio session here but we do not have it in this context.
749 // This may prevent offloading in rare situations where effects are left active by apps
750 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700751 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700752 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
753 !isNonOffloadableEffectEnabled()) {
754 profile = getProfileForDirectOutput(device,
755 samplingRate,
756 format,
757 channelMask,
758 (audio_output_flags_t)flags);
759 }
760
Eric Laurent1c333e22014-05-20 10:48:17 -0700761 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700762 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700763
764 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700765 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700766 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
767 outputDesc = desc;
768 // reuse direct output if currently open and configured with same parameters
769 if ((samplingRate == outputDesc->mSamplingRate) &&
770 (format == outputDesc->mFormat) &&
771 (channelMask == outputDesc->mChannelMask)) {
772 outputDesc->mDirectOpenCount++;
773 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
774 return mOutputs.keyAt(i);
775 }
776 }
777 }
778 // close direct output if currently open and configured with different parameters
779 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700780 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700781 }
782 outputDesc = new AudioOutputDescriptor(profile);
783 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700784 outputDesc->mLatency = 0;
785 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700786 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
787 config.sample_rate = samplingRate;
788 config.channel_mask = channelMask;
789 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700790 if (offloadInfo != NULL) {
791 config.offload_info = *offloadInfo;
792 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700793 status = mpClientInterface->openOutput(profile->mModule->mHandle,
794 &output,
795 &config,
796 &outputDesc->mDevice,
797 String8(""),
798 &outputDesc->mLatency,
799 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700800
801 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700802 if (status != NO_ERROR ||
803 (samplingRate != 0 && samplingRate != config.sample_rate) ||
804 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
805 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700806 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
807 "format %d %d, channelMask %04x %04x", output, samplingRate,
808 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
809 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700810 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700811 mpClientInterface->closeOutput(output);
812 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700813 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700814 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700815 outputDesc->mSamplingRate = config.sample_rate;
816 outputDesc->mChannelMask = config.channel_mask;
817 outputDesc->mFormat = config.format;
818 outputDesc->mRefCount[stream] = 0;
819 outputDesc->mStopTime[stream] = 0;
820 outputDesc->mDirectOpenCount = 1;
821
Eric Laurente552edb2014-03-10 17:42:56 -0700822 audio_io_handle_t srcOutput = getOutputForEffect();
823 addOutput(output, outputDesc);
824 audio_io_handle_t dstOutput = getOutputForEffect();
825 if (dstOutput == output) {
826 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
827 }
828 mPreviousOutputs = mOutputs;
829 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700830 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700831 return output;
832 }
833
834 // ignoring channel mask due to downmix capability in mixer
835
836 // open a non direct output
837
838 // for non direct outputs, only PCM is supported
839 if (audio_is_linear_pcm(format)) {
840 // get which output is suitable for the specified stream. The actual
841 // routing change will happen when startOutput() will be called
842 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
843
844 output = selectOutput(outputs, flags);
845 }
846 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
847 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
848
849 ALOGV("getOutput() returns output %d", output);
850
851 return output;
852}
853
Eric Laurente0720872014-03-11 09:30:41 -0700854audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700855 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700856{
857 // select one output among several that provide a path to a particular device or set of
858 // devices (the list was previously build by getOutputsForDevice()).
859 // The priority is as follows:
860 // 1: the output with the highest number of requested policy flags
861 // 2: the primary output
862 // 3: the first output in the list
863
864 if (outputs.size() == 0) {
865 return 0;
866 }
867 if (outputs.size() == 1) {
868 return outputs[0];
869 }
870
871 int maxCommonFlags = 0;
872 audio_io_handle_t outputFlags = 0;
873 audio_io_handle_t outputPrimary = 0;
874
875 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700876 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700877 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700878 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700879 if (commonFlags > maxCommonFlags) {
880 outputFlags = outputs[i];
881 maxCommonFlags = commonFlags;
882 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
883 }
884 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
885 outputPrimary = outputs[i];
886 }
887 }
888 }
889
890 if (outputFlags != 0) {
891 return outputFlags;
892 }
893 if (outputPrimary != 0) {
894 return outputPrimary;
895 }
896
897 return outputs[0];
898}
899
Eric Laurente0720872014-03-11 09:30:41 -0700900status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700901 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700902 int session)
903{
904 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
905 ssize_t index = mOutputs.indexOfKey(output);
906 if (index < 0) {
907 ALOGW("startOutput() unknown output %d", output);
908 return BAD_VALUE;
909 }
910
Eric Laurent1f2f2232014-06-02 12:01:23 -0700911 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700912
913 // increment usage count for this stream on the requested output:
914 // NOTE that the usage count is the same for duplicated output and hardware output which is
915 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
916 outputDesc->changeRefCount(stream, 1);
917
918 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700919 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700920 routing_strategy strategy = getStrategy(stream);
921 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
922 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
923 uint32_t waitMs = 0;
924 bool force = false;
925 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700926 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700927 if (desc != outputDesc) {
928 // force a device change if any other output is managed by the same hw
929 // module and has a current device selection that differs from selected device.
930 // In this case, the audio HAL must receive the new device selection so that it can
931 // change the device currently selected by the other active output.
932 if (outputDesc->sharesHwModuleWith(desc) &&
933 desc->device() != newDevice) {
934 force = true;
935 }
936 // wait for audio on other active outputs to be presented when starting
937 // a notification so that audio focus effect can propagate.
938 uint32_t latency = desc->latency();
939 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
940 waitMs = latency;
941 }
942 }
943 }
944 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
945
946 // handle special case for sonification while in call
947 if (isInCall()) {
948 handleIncallSonification(stream, true, false);
949 }
950
951 // apply volume rules for current stream and device if necessary
952 checkAndSetVolume(stream,
953 mStreams[stream].getVolumeIndex(newDevice),
954 output,
955 newDevice);
956
957 // update the outputs if starting an output with a stream that can affect notification
958 // routing
959 handleNotificationRoutingForStream(stream);
960 if (waitMs > muteWaitMs) {
961 usleep((waitMs - muteWaitMs) * 2 * 1000);
962 }
963 }
964 return NO_ERROR;
965}
966
967
Eric Laurente0720872014-03-11 09:30:41 -0700968status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700969 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700970 int session)
971{
972 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
973 ssize_t index = mOutputs.indexOfKey(output);
974 if (index < 0) {
975 ALOGW("stopOutput() unknown output %d", output);
976 return BAD_VALUE;
977 }
978
Eric Laurent1f2f2232014-06-02 12:01:23 -0700979 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700980
981 // handle special case for sonification while in call
982 if (isInCall()) {
983 handleIncallSonification(stream, false, false);
984 }
985
986 if (outputDesc->mRefCount[stream] > 0) {
987 // decrement usage count of this stream on the output
988 outputDesc->changeRefCount(stream, -1);
989 // store time at which the stream was stopped - see isStreamActive()
990 if (outputDesc->mRefCount[stream] == 0) {
991 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700992 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700993 // delay the device switch by twice the latency because stopOutput() is executed when
994 // the track stop() command is received and at that time the audio track buffer can
995 // still contain data that needs to be drained. The latency only covers the audio HAL
996 // and kernel buffers. Also the latency does not always include additional delay in the
997 // audio path (audio DSP, CODEC ...)
998 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
999
1000 // force restoring the device selection on other active outputs if it differs from the
1001 // one being selected for this output
1002 for (size_t i = 0; i < mOutputs.size(); i++) {
1003 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001004 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001005 if (curOutput != output &&
1006 desc->isActive() &&
1007 outputDesc->sharesHwModuleWith(desc) &&
1008 (newDevice != desc->device())) {
1009 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001010 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001011 true,
1012 outputDesc->mLatency*2);
1013 }
1014 }
1015 // update the outputs if stopping one with a stream that can affect notification routing
1016 handleNotificationRoutingForStream(stream);
1017 }
1018 return NO_ERROR;
1019 } else {
1020 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1021 return INVALID_OPERATION;
1022 }
1023}
1024
Eric Laurente0720872014-03-11 09:30:41 -07001025void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001026{
1027 ALOGV("releaseOutput() %d", output);
1028 ssize_t index = mOutputs.indexOfKey(output);
1029 if (index < 0) {
1030 ALOGW("releaseOutput() releasing unknown output %d", output);
1031 return;
1032 }
1033
1034#ifdef AUDIO_POLICY_TEST
1035 int testIndex = testOutputIndex(output);
1036 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001037 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001038 if (outputDesc->isActive()) {
1039 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001040 mOutputs.removeItem(output);
1041 mTestOutputs[testIndex] = 0;
1042 }
1043 return;
1044 }
1045#endif //AUDIO_POLICY_TEST
1046
Eric Laurent1f2f2232014-06-02 12:01:23 -07001047 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001048 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001049 if (desc->mDirectOpenCount <= 0) {
1050 ALOGW("releaseOutput() invalid open count %d for output %d",
1051 desc->mDirectOpenCount, output);
1052 return;
1053 }
1054 if (--desc->mDirectOpenCount == 0) {
1055 closeOutput(output);
1056 // If effects where present on the output, audioflinger moved them to the primary
1057 // output by default: move them back to the appropriate output.
1058 audio_io_handle_t dstOutput = getOutputForEffect();
1059 if (dstOutput != mPrimaryOutput) {
1060 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1061 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001062 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001063 }
1064 }
1065}
1066
1067
Eric Laurente0720872014-03-11 09:30:41 -07001068audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001069 uint32_t samplingRate,
1070 audio_format_t format,
1071 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001072 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001073 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001074{
Eric Laurent4dc68062014-07-28 17:26:49 -07001075 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001076 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001077 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001078
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001079 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001080
1081 if (device == AUDIO_DEVICE_NONE) {
1082 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001083 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001084 }
1085
1086 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001087 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001088 case AUDIO_SOURCE_VOICE_UPLINK:
1089 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1090 break;
1091 case AUDIO_SOURCE_VOICE_DOWNLINK:
1092 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1093 break;
1094 case AUDIO_SOURCE_VOICE_CALL:
1095 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1096 break;
1097 default:
1098 break;
1099 }
1100
Eric Laurent1c333e22014-05-20 10:48:17 -07001101 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001102 samplingRate,
1103 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001104 channelMask,
1105 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001106 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001107 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1108 "channelMask 0x%X, flags %#x",
1109 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001110 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001111 }
1112
1113 if (profile->mModule->mHandle == 0) {
1114 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001115 return AUDIO_IO_HANDLE_NONE;
1116 }
1117
1118 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1119 config.sample_rate = samplingRate;
1120 config.channel_mask = channelMask;
1121 config.format = format;
1122 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001123
1124 bool isSoundTrigger = false;
1125 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1126 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1127 if (index >= 0) {
1128 input = mSoundTriggerSessions.valueFor(session);
1129 isSoundTrigger = true;
1130 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1131 }
1132 }
1133
Eric Laurentcf2c0212014-07-25 16:20:43 -07001134 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1135 &input,
1136 &config,
1137 &device,
1138 String8(""),
1139 inputSource,
1140 flags);
1141
1142 // only accept input with the exact requested set of parameters
1143 if (status != NO_ERROR ||
1144 (samplingRate != config.sample_rate) ||
1145 (format != config.format) ||
1146 (channelMask != config.channel_mask)) {
1147 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1148 samplingRate, format, channelMask);
1149 if (input != AUDIO_IO_HANDLE_NONE) {
1150 mpClientInterface->closeInput(input);
1151 }
1152 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001153 }
1154
Eric Laurent1f2f2232014-06-02 12:01:23 -07001155 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001156 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001157 inputDesc->mRefCount = 0;
1158 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001159 inputDesc->mSamplingRate = samplingRate;
1160 inputDesc->mFormat = format;
1161 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001162 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001163 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001164 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001165
Eric Laurentd4692962014-05-05 18:13:44 -07001166 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001167 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001168 return input;
1169}
1170
Eric Laurent4dc68062014-07-28 17:26:49 -07001171status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1172 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001173{
1174 ALOGV("startInput() input %d", input);
1175 ssize_t index = mInputs.indexOfKey(input);
1176 if (index < 0) {
1177 ALOGW("startInput() unknown input %d", input);
1178 return BAD_VALUE;
1179 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001180 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001181
Eric Laurent4dc68062014-07-28 17:26:49 -07001182 index = inputDesc->mSessions.indexOf(session);
1183 if (index < 0) {
1184 ALOGW("startInput() unknown session %d on input %d", session, input);
1185 return BAD_VALUE;
1186 }
1187
Glenn Kasten74a8e252014-07-24 14:09:55 -07001188 // virtual input devices are compatible with other input devices
1189 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1190
1191 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001192 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001193 if (activeInput != 0 && activeInput != input) {
1194
1195 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1196 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001197 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001198 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001199 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001200 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1201 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001202 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001203 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001204 return INVALID_OPERATION;
1205 }
1206 }
1207 }
1208
Glenn Kasten74a8e252014-07-24 14:09:55 -07001209 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001210 if (activeInputsCount() == 0) {
1211 SoundTrigger::setCaptureState(true);
1212 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001213 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001214
Glenn Kasten74a8e252014-07-24 14:09:55 -07001215 // Automatically enable the remote submix output when input is started.
1216 // For remote submix (a virtual device), we open only one input per capture request.
1217 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1218 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1219 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1220 }
Eric Laurente552edb2014-03-10 17:42:56 -07001221 }
1222
Eric Laurente552edb2014-03-10 17:42:56 -07001223 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1224
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001225 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001226 return NO_ERROR;
1227}
1228
Eric Laurent4dc68062014-07-28 17:26:49 -07001229status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1230 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001231{
1232 ALOGV("stopInput() input %d", input);
1233 ssize_t index = mInputs.indexOfKey(input);
1234 if (index < 0) {
1235 ALOGW("stopInput() unknown input %d", input);
1236 return BAD_VALUE;
1237 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001238 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001239
Eric Laurent4dc68062014-07-28 17:26:49 -07001240 index = inputDesc->mSessions.indexOf(session);
1241 if (index < 0) {
1242 ALOGW("stopInput() unknown session %d on input %d", session, input);
1243 return BAD_VALUE;
1244 }
1245
Eric Laurente552edb2014-03-10 17:42:56 -07001246 if (inputDesc->mRefCount == 0) {
1247 ALOGW("stopInput() input %d already stopped", input);
1248 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001249 }
1250
1251 inputDesc->mRefCount--;
1252 if (inputDesc->mRefCount == 0) {
1253
Eric Laurente552edb2014-03-10 17:42:56 -07001254 // automatically disable the remote submix output when input is stopped
1255 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1256 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001257 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001258 }
1259
Eric Laurent1c333e22014-05-20 10:48:17 -07001260 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001261
1262 if (activeInputsCount() == 0) {
1263 SoundTrigger::setCaptureState(false);
1264 }
Eric Laurente552edb2014-03-10 17:42:56 -07001265 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001266 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001267}
1268
Eric Laurent4dc68062014-07-28 17:26:49 -07001269void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1270 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001271{
1272 ALOGV("releaseInput() %d", input);
1273 ssize_t index = mInputs.indexOfKey(input);
1274 if (index < 0) {
1275 ALOGW("releaseInput() releasing unknown input %d", input);
1276 return;
1277 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001278 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1279 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001280
1281 index = inputDesc->mSessions.indexOf(session);
1282 if (index < 0) {
1283 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1284 return;
1285 }
1286 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001287 if (inputDesc->mOpenRefCount == 0) {
1288 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1289 return;
1290 }
1291 inputDesc->mOpenRefCount--;
1292 if (inputDesc->mOpenRefCount > 0) {
1293 ALOGV("releaseInput() exit > 0");
1294 return;
1295 }
1296
Eric Laurente552edb2014-03-10 17:42:56 -07001297 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001298 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001299 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001300 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001301 ALOGV("releaseInput() exit");
1302}
1303
Eric Laurentd4692962014-05-05 18:13:44 -07001304void AudioPolicyManager::closeAllInputs() {
1305 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1306 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1307 }
1308 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001309 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001310}
1311
Eric Laurente0720872014-03-11 09:30:41 -07001312void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001313 int indexMin,
1314 int indexMax)
1315{
1316 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1317 if (indexMin < 0 || indexMin >= indexMax) {
1318 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1319 return;
1320 }
1321 mStreams[stream].mIndexMin = indexMin;
1322 mStreams[stream].mIndexMax = indexMax;
1323}
1324
Eric Laurente0720872014-03-11 09:30:41 -07001325status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001326 int index,
1327 audio_devices_t device)
1328{
1329
1330 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1331 return BAD_VALUE;
1332 }
1333 if (!audio_is_output_device(device)) {
1334 return BAD_VALUE;
1335 }
1336
1337 // Force max volume if stream cannot be muted
1338 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1339
1340 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1341 stream, device, index);
1342
1343 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1344 // clear all device specific values
1345 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1346 mStreams[stream].mIndexCur.clear();
1347 }
1348 mStreams[stream].mIndexCur.add(device, index);
1349
1350 // compute and apply stream volume on all outputs according to connected device
1351 status_t status = NO_ERROR;
1352 for (size_t i = 0; i < mOutputs.size(); i++) {
1353 audio_devices_t curDevice =
1354 getDeviceForVolume(mOutputs.valueAt(i)->device());
1355 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1356 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1357 if (volStatus != NO_ERROR) {
1358 status = volStatus;
1359 }
1360 }
1361 }
1362 return status;
1363}
1364
Eric Laurente0720872014-03-11 09:30:41 -07001365status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001366 int *index,
1367 audio_devices_t device)
1368{
1369 if (index == NULL) {
1370 return BAD_VALUE;
1371 }
1372 if (!audio_is_output_device(device)) {
1373 return BAD_VALUE;
1374 }
1375 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1376 // the strategy the stream belongs to.
1377 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1378 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1379 }
1380 device = getDeviceForVolume(device);
1381
1382 *index = mStreams[stream].getVolumeIndex(device);
1383 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1384 return NO_ERROR;
1385}
1386
Eric Laurente0720872014-03-11 09:30:41 -07001387audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001388 const SortedVector<audio_io_handle_t>& outputs)
1389{
1390 // select one output among several suitable for global effects.
1391 // The priority is as follows:
1392 // 1: An offloaded output. If the effect ends up not being offloadable,
1393 // AudioFlinger will invalidate the track and the offloaded output
1394 // will be closed causing the effect to be moved to a PCM output.
1395 // 2: A deep buffer output
1396 // 3: the first output in the list
1397
1398 if (outputs.size() == 0) {
1399 return 0;
1400 }
1401
1402 audio_io_handle_t outputOffloaded = 0;
1403 audio_io_handle_t outputDeepBuffer = 0;
1404
1405 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001406 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001407 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001408 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1409 outputOffloaded = outputs[i];
1410 }
1411 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1412 outputDeepBuffer = outputs[i];
1413 }
1414 }
1415
1416 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1417 outputOffloaded, outputDeepBuffer);
1418 if (outputOffloaded != 0) {
1419 return outputOffloaded;
1420 }
1421 if (outputDeepBuffer != 0) {
1422 return outputDeepBuffer;
1423 }
1424
1425 return outputs[0];
1426}
1427
Eric Laurente0720872014-03-11 09:30:41 -07001428audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001429{
1430 // apply simple rule where global effects are attached to the same output as MUSIC streams
1431
Eric Laurent3b73df72014-03-11 09:06:29 -07001432 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001433 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1434 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1435
1436 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1437 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1438 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1439
1440 return output;
1441}
1442
Eric Laurente0720872014-03-11 09:30:41 -07001443status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001444 audio_io_handle_t io,
1445 uint32_t strategy,
1446 int session,
1447 int id)
1448{
1449 ssize_t index = mOutputs.indexOfKey(io);
1450 if (index < 0) {
1451 index = mInputs.indexOfKey(io);
1452 if (index < 0) {
1453 ALOGW("registerEffect() unknown io %d", io);
1454 return INVALID_OPERATION;
1455 }
1456 }
1457
1458 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1459 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1460 desc->name, desc->memoryUsage);
1461 return INVALID_OPERATION;
1462 }
1463 mTotalEffectsMemory += desc->memoryUsage;
1464 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1465 desc->name, io, strategy, session, id);
1466 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1467
Eric Laurent1f2f2232014-06-02 12:01:23 -07001468 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1469 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1470 effectDesc->mIo = io;
1471 effectDesc->mStrategy = (routing_strategy)strategy;
1472 effectDesc->mSession = session;
1473 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001474
Eric Laurent1f2f2232014-06-02 12:01:23 -07001475 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001476
1477 return NO_ERROR;
1478}
1479
Eric Laurente0720872014-03-11 09:30:41 -07001480status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001481{
1482 ssize_t index = mEffects.indexOfKey(id);
1483 if (index < 0) {
1484 ALOGW("unregisterEffect() unknown effect ID %d", id);
1485 return INVALID_OPERATION;
1486 }
1487
Eric Laurent1f2f2232014-06-02 12:01:23 -07001488 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001489
Eric Laurent1f2f2232014-06-02 12:01:23 -07001490 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001491
Eric Laurent1f2f2232014-06-02 12:01:23 -07001492 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001493 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001494 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1495 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001496 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001497 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001498 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001499 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001500
1501 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001502
1503 return NO_ERROR;
1504}
1505
Eric Laurente0720872014-03-11 09:30:41 -07001506status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001507{
1508 ssize_t index = mEffects.indexOfKey(id);
1509 if (index < 0) {
1510 ALOGW("unregisterEffect() unknown effect ID %d", id);
1511 return INVALID_OPERATION;
1512 }
1513
1514 return setEffectEnabled(mEffects.valueAt(index), enabled);
1515}
1516
Eric Laurent1f2f2232014-06-02 12:01:23 -07001517status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001518{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001519 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001520 ALOGV("setEffectEnabled(%s) effect already %s",
1521 enabled?"true":"false", enabled?"enabled":"disabled");
1522 return INVALID_OPERATION;
1523 }
1524
1525 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001526 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001527 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001528 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001529 return INVALID_OPERATION;
1530 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001531 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001532 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1533 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001534 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001535 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001536 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1537 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001538 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001539 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001540 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1541 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001542 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001543 return NO_ERROR;
1544}
1545
Eric Laurente0720872014-03-11 09:30:41 -07001546bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001547{
1548 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001549 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1550 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1551 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001552 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001553 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001554 return true;
1555 }
1556 }
1557 return false;
1558}
1559
Eric Laurente0720872014-03-11 09:30:41 -07001560bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001561{
1562 nsecs_t sysTime = systemTime();
1563 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001564 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001565 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001566 return true;
1567 }
1568 }
1569 return false;
1570}
1571
Eric Laurente0720872014-03-11 09:30:41 -07001572bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001573 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001574{
1575 nsecs_t sysTime = systemTime();
1576 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001577 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001578 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001579 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001580 return true;
1581 }
1582 }
1583 return false;
1584}
1585
Eric Laurente0720872014-03-11 09:30:41 -07001586bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001587{
1588 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001589 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001590 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001591 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001592 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1593 && (inputDescriptor->mRefCount > 0)) {
1594 return true;
1595 }
1596 }
1597 return false;
1598}
1599
1600
Eric Laurente0720872014-03-11 09:30:41 -07001601status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001602{
1603 const size_t SIZE = 256;
1604 char buffer[SIZE];
1605 String8 result;
1606
1607 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1608 result.append(buffer);
1609
1610 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1611 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001612 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1613 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001614 snprintf(buffer, SIZE, " Force use for communications %d\n",
1615 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001616 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001617 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001618 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001619 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001620 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001621 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001622 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001623 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001624 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001625 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1626 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1627 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001628
Eric Laurent3a4311c2014-03-17 12:00:47 -07001629 snprintf(buffer, SIZE, " Available output devices:\n");
1630 result.append(buffer);
1631 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001632 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001633 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001634 }
1635 snprintf(buffer, SIZE, "\n Available input devices:\n");
1636 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001637 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001638 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001639 }
Eric Laurente552edb2014-03-10 17:42:56 -07001640
1641 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1642 write(fd, buffer, strlen(buffer));
1643 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001644 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001645 write(fd, buffer, strlen(buffer));
1646 mHwModules[i]->dump(fd);
1647 }
1648
1649 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1650 write(fd, buffer, strlen(buffer));
1651 for (size_t i = 0; i < mOutputs.size(); i++) {
1652 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1653 write(fd, buffer, strlen(buffer));
1654 mOutputs.valueAt(i)->dump(fd);
1655 }
1656
1657 snprintf(buffer, SIZE, "\nInputs dump:\n");
1658 write(fd, buffer, strlen(buffer));
1659 for (size_t i = 0; i < mInputs.size(); i++) {
1660 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1661 write(fd, buffer, strlen(buffer));
1662 mInputs.valueAt(i)->dump(fd);
1663 }
1664
1665 snprintf(buffer, SIZE, "\nStreams dump:\n");
1666 write(fd, buffer, strlen(buffer));
1667 snprintf(buffer, SIZE,
1668 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1669 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001670 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001671 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001672 write(fd, buffer, strlen(buffer));
1673 mStreams[i].dump(fd);
1674 }
1675
1676 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1677 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1678 write(fd, buffer, strlen(buffer));
1679
1680 snprintf(buffer, SIZE, "Registered effects:\n");
1681 write(fd, buffer, strlen(buffer));
1682 for (size_t i = 0; i < mEffects.size(); i++) {
1683 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1684 write(fd, buffer, strlen(buffer));
1685 mEffects.valueAt(i)->dump(fd);
1686 }
1687
1688
1689 return NO_ERROR;
1690}
1691
1692// This function checks for the parameters which can be offloaded.
1693// This can be enhanced depending on the capability of the DSP and policy
1694// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001695bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001696{
1697 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001698 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001699 offloadInfo.sample_rate, offloadInfo.channel_mask,
1700 offloadInfo.format,
1701 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1702 offloadInfo.has_video);
1703
1704 // Check if offload has been disabled
1705 char propValue[PROPERTY_VALUE_MAX];
1706 if (property_get("audio.offload.disable", propValue, "0")) {
1707 if (atoi(propValue) != 0) {
1708 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1709 return false;
1710 }
1711 }
1712
1713 // Check if stream type is music, then only allow offload as of now.
1714 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1715 {
1716 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1717 return false;
1718 }
1719
1720 //TODO: enable audio offloading with video when ready
1721 if (offloadInfo.has_video)
1722 {
1723 ALOGV("isOffloadSupported: has_video == true, returning false");
1724 return false;
1725 }
1726
1727 //If duration is less than minimum value defined in property, return false
1728 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1729 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1730 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1731 return false;
1732 }
1733 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1734 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1735 return false;
1736 }
1737
1738 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1739 // creating an offloaded track and tearing it down immediately after start when audioflinger
1740 // detects there is an active non offloadable effect.
1741 // FIXME: We should check the audio session here but we do not have it in this context.
1742 // This may prevent offloading in rare situations where effects are left active by apps
1743 // in the background.
1744 if (isNonOffloadableEffectEnabled()) {
1745 return false;
1746 }
1747
1748 // See if there is a profile to support this.
1749 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001750 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001751 offloadInfo.sample_rate,
1752 offloadInfo.format,
1753 offloadInfo.channel_mask,
1754 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001755 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1756 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001757}
1758
Eric Laurent6a94d692014-05-20 11:18:06 -07001759status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1760 audio_port_type_t type,
1761 unsigned int *num_ports,
1762 struct audio_port *ports,
1763 unsigned int *generation)
1764{
1765 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1766 generation == NULL) {
1767 return BAD_VALUE;
1768 }
1769 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1770 if (ports == NULL) {
1771 *num_ports = 0;
1772 }
1773
1774 size_t portsWritten = 0;
1775 size_t portsMax = *num_ports;
1776 *num_ports = 0;
1777 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1778 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1779 for (size_t i = 0;
1780 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1781 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1782 }
1783 *num_ports += mAvailableOutputDevices.size();
1784 }
1785 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1786 for (size_t i = 0;
1787 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1788 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1789 }
1790 *num_ports += mAvailableInputDevices.size();
1791 }
1792 }
1793 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1794 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1795 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1796 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1797 }
1798 *num_ports += mInputs.size();
1799 }
1800 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001801 size_t numOutputs = 0;
1802 for (size_t i = 0; i < mOutputs.size(); i++) {
1803 if (!mOutputs[i]->isDuplicated()) {
1804 numOutputs++;
1805 if (portsWritten < portsMax) {
1806 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1807 }
1808 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001809 }
Eric Laurent84c70242014-06-23 08:46:27 -07001810 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001811 }
1812 }
1813 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001814 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001815 return NO_ERROR;
1816}
1817
1818status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1819{
1820 return NO_ERROR;
1821}
1822
Eric Laurent1f2f2232014-06-02 12:01:23 -07001823sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001824 audio_port_handle_t id) const
1825{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001826 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001827 for (size_t i = 0; i < mOutputs.size(); i++) {
1828 outputDesc = mOutputs.valueAt(i);
1829 if (outputDesc->mId == id) {
1830 break;
1831 }
1832 }
1833 return outputDesc;
1834}
1835
Eric Laurent1f2f2232014-06-02 12:01:23 -07001836sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001837 audio_port_handle_t id) const
1838{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001839 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001840 for (size_t i = 0; i < mInputs.size(); i++) {
1841 inputDesc = mInputs.valueAt(i);
1842 if (inputDesc->mId == id) {
1843 break;
1844 }
1845 }
1846 return inputDesc;
1847}
1848
Eric Laurent1f2f2232014-06-02 12:01:23 -07001849sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1850 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001851{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001852 sp <HwModule> module;
1853
Eric Laurent6a94d692014-05-20 11:18:06 -07001854 for (size_t i = 0; i < mHwModules.size(); i++) {
1855 if (mHwModules[i]->mHandle == 0) {
1856 continue;
1857 }
1858 if (audio_is_output_device(device)) {
1859 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1860 {
1861 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1862 return mHwModules[i];
1863 }
1864 }
1865 } else {
1866 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1867 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1868 device & ~AUDIO_DEVICE_BIT_IN) {
1869 return mHwModules[i];
1870 }
1871 }
1872 }
1873 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001874 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001875}
1876
Eric Laurent1f2f2232014-06-02 12:01:23 -07001877sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001878{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001879 sp <HwModule> module;
1880
Eric Laurent1afeecb2014-05-14 08:52:28 -07001881 for (size_t i = 0; i < mHwModules.size(); i++)
1882 {
1883 if (strcmp(mHwModules[i]->mName, name) == 0) {
1884 return mHwModules[i];
1885 }
1886 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001887 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001888}
1889
1890
Eric Laurent6a94d692014-05-20 11:18:06 -07001891status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1892 audio_patch_handle_t *handle,
1893 uid_t uid)
1894{
1895 ALOGV("createAudioPatch()");
1896
1897 if (handle == NULL || patch == NULL) {
1898 return BAD_VALUE;
1899 }
1900 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1901
1902 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1903 return INVALID_OPERATION;
1904 }
1905 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1906 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1907 return INVALID_OPERATION;
1908 }
1909
1910 sp<AudioPatch> patchDesc;
1911 ssize_t index = mAudioPatches.indexOfKey(*handle);
1912
1913 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1914 patch->sinks[0].type);
1915 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1916 patch->sources[0].role,
1917 patch->sources[0].type);
1918
1919 if (index >= 0) {
1920 patchDesc = mAudioPatches.valueAt(index);
1921 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1922 mUidCached, patchDesc->mUid, uid);
1923 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1924 return INVALID_OPERATION;
1925 }
1926 } else {
1927 *handle = 0;
1928 }
1929
1930 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1931 // TODO add support for mix to mix connection
1932 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1933 ALOGV("createAudioPatch() source mix sink not device");
1934 return BAD_VALUE;
1935 }
1936 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001937 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001938 if (outputDesc == NULL) {
1939 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1940 return BAD_VALUE;
1941 }
Eric Laurent84c70242014-06-23 08:46:27 -07001942 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1943 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001944 if (patchDesc != 0) {
1945 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1946 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1947 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1948 return BAD_VALUE;
1949 }
1950 }
1951 sp<DeviceDescriptor> devDesc =
1952 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1953 if (devDesc == 0) {
1954 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1955 return BAD_VALUE;
1956 }
1957
Eric Laurent84c70242014-06-23 08:46:27 -07001958 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001959 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07001960 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07001961 patch->sources[0].format,
1962 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001963 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001964 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001965 return INVALID_OPERATION;
1966 }
1967 // TODO: reconfigure output format and channels here
1968 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001969 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001970 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001971 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001972 true,
1973 0,
1974 handle);
1975 index = mAudioPatches.indexOfKey(*handle);
1976 if (index >= 0) {
1977 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1978 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1979 }
1980 patchDesc = mAudioPatches.valueAt(index);
1981 patchDesc->mUid = uid;
1982 ALOGV("createAudioPatch() success");
1983 } else {
1984 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1985 return INVALID_OPERATION;
1986 }
1987 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1988 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1989 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001990 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001991 if (inputDesc == NULL) {
1992 return BAD_VALUE;
1993 }
1994 if (patchDesc != 0) {
1995 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1996 return BAD_VALUE;
1997 }
1998 }
1999 sp<DeviceDescriptor> devDesc =
2000 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2001 if (devDesc == 0) {
2002 return BAD_VALUE;
2003 }
2004
Eric Laurent84c70242014-06-23 08:46:27 -07002005 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002006 patch->sinks[0].sample_rate,
2007 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002008 patch->sinks[0].format,
2009 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002010 // FIXME for the parameter type,
2011 // and the NONE
2012 (audio_output_flags_t)
2013 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002014 return INVALID_OPERATION;
2015 }
2016 // TODO: reconfigure output format and channels here
2017 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002018 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002019 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07002020 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07002021 true,
2022 handle);
2023 index = mAudioPatches.indexOfKey(*handle);
2024 if (index >= 0) {
2025 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2026 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2027 }
2028 patchDesc = mAudioPatches.valueAt(index);
2029 patchDesc->mUid = uid;
2030 ALOGV("createAudioPatch() success");
2031 } else {
2032 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2033 return INVALID_OPERATION;
2034 }
2035 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2036 // device to device connection
2037 if (patchDesc != 0) {
2038 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2039 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2040 return BAD_VALUE;
2041 }
2042 }
2043
2044 sp<DeviceDescriptor> srcDeviceDesc =
2045 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2046 sp<DeviceDescriptor> sinkDeviceDesc =
2047 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2048 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2049 return BAD_VALUE;
2050 }
2051 //update source and sink with our own data as the data passed in the patch may
2052 // be incomplete.
2053 struct audio_patch newPatch = *patch;
2054 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2055 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2056
Eric Laurent6a94d692014-05-20 11:18:06 -07002057 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002058 SortedVector<audio_io_handle_t> outputs =
2059 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2060 // if the sink device is reachable via an opened output stream, request to go via
2061 // this output stream by adding a second source to the patch description
2062 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2063 if (output != AUDIO_IO_HANDLE_NONE) {
2064 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2065 if (outputDesc->isDuplicated()) {
2066 return INVALID_OPERATION;
2067 }
2068 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2069 newPatch.num_sources = 2;
2070 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002071 }
2072 // TODO: check from routing capabilities in config file and other conflicting patches
2073
2074 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2075 if (index >= 0) {
2076 afPatchHandle = patchDesc->mAfPatchHandle;
2077 }
2078
2079 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2080 &afPatchHandle,
2081 0);
2082 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2083 status, afPatchHandle);
2084 if (status == NO_ERROR) {
2085 if (index < 0) {
2086 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2087 &newPatch, uid);
2088 addAudioPatch(patchDesc->mHandle, patchDesc);
2089 } else {
2090 patchDesc->mPatch = newPatch;
2091 }
2092 patchDesc->mAfPatchHandle = afPatchHandle;
2093 *handle = patchDesc->mHandle;
2094 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002095 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002096 } else {
2097 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2098 status);
2099 return INVALID_OPERATION;
2100 }
2101 } else {
2102 return BAD_VALUE;
2103 }
2104 } else {
2105 return BAD_VALUE;
2106 }
2107 return NO_ERROR;
2108}
2109
2110status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2111 uid_t uid)
2112{
2113 ALOGV("releaseAudioPatch() patch %d", handle);
2114
2115 ssize_t index = mAudioPatches.indexOfKey(handle);
2116
2117 if (index < 0) {
2118 return BAD_VALUE;
2119 }
2120 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2121 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2122 mUidCached, patchDesc->mUid, uid);
2123 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2124 return INVALID_OPERATION;
2125 }
2126
2127 struct audio_patch *patch = &patchDesc->mPatch;
2128 patchDesc->mUid = mUidCached;
2129 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002130 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002131 if (outputDesc == NULL) {
2132 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2133 return BAD_VALUE;
2134 }
2135
2136 setOutputDevice(outputDesc->mIoHandle,
2137 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2138 true,
2139 0,
2140 NULL);
2141 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2142 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002143 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002144 if (inputDesc == NULL) {
2145 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2146 return BAD_VALUE;
2147 }
2148 setInputDevice(inputDesc->mIoHandle,
2149 getNewInputDevice(inputDesc->mIoHandle),
2150 true,
2151 NULL);
2152 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2153 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2154 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2155 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2156 status, patchDesc->mAfPatchHandle);
2157 removeAudioPatch(patchDesc->mHandle);
2158 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002159 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002160 } else {
2161 return BAD_VALUE;
2162 }
2163 } else {
2164 return BAD_VALUE;
2165 }
2166 return NO_ERROR;
2167}
2168
2169status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2170 struct audio_patch *patches,
2171 unsigned int *generation)
2172{
2173 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2174 generation == NULL) {
2175 return BAD_VALUE;
2176 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002177 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002178 *num_patches, patches, mAudioPatches.size());
2179 if (patches == NULL) {
2180 *num_patches = 0;
2181 }
2182
2183 size_t patchesWritten = 0;
2184 size_t patchesMax = *num_patches;
2185 for (size_t i = 0;
2186 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2187 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2188 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002189 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002190 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2191 }
2192 *num_patches = mAudioPatches.size();
2193
2194 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002195 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002196 return NO_ERROR;
2197}
2198
Eric Laurente1715a42014-05-20 11:30:42 -07002199status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002200{
Eric Laurente1715a42014-05-20 11:30:42 -07002201 ALOGV("setAudioPortConfig()");
2202
2203 if (config == NULL) {
2204 return BAD_VALUE;
2205 }
2206 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2207 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002208 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2209 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002210 }
2211
Eric Laurenta121f902014-06-03 13:32:54 -07002212 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002213 if (config->type == AUDIO_PORT_TYPE_MIX) {
2214 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002215 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002216 if (outputDesc == NULL) {
2217 return BAD_VALUE;
2218 }
Eric Laurent84c70242014-06-23 08:46:27 -07002219 ALOG_ASSERT(!outputDesc->isDuplicated(),
2220 "setAudioPortConfig() called on duplicated output %d",
2221 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002222 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002223 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002224 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002225 if (inputDesc == NULL) {
2226 return BAD_VALUE;
2227 }
Eric Laurenta121f902014-06-03 13:32:54 -07002228 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002229 } else {
2230 return BAD_VALUE;
2231 }
2232 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2233 sp<DeviceDescriptor> deviceDesc;
2234 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2235 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2236 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2237 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2238 } else {
2239 return BAD_VALUE;
2240 }
2241 if (deviceDesc == NULL) {
2242 return BAD_VALUE;
2243 }
Eric Laurenta121f902014-06-03 13:32:54 -07002244 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002245 } else {
2246 return BAD_VALUE;
2247 }
2248
Eric Laurenta121f902014-06-03 13:32:54 -07002249 struct audio_port_config backupConfig;
2250 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2251 if (status == NO_ERROR) {
2252 struct audio_port_config newConfig;
2253 audioPortConfig->toAudioPortConfig(&newConfig, config);
2254 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002255 }
Eric Laurenta121f902014-06-03 13:32:54 -07002256 if (status != NO_ERROR) {
2257 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002258 }
Eric Laurente1715a42014-05-20 11:30:42 -07002259
2260 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002261}
2262
2263void AudioPolicyManager::clearAudioPatches(uid_t uid)
2264{
2265 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2266 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2267 if (patchDesc->mUid == uid) {
2268 // releaseAudioPatch() removes the patch from mAudioPatches
2269 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2270 i--;
2271 }
2272 }
2273 }
2274}
2275
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002276status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2277 audio_io_handle_t *ioHandle,
2278 audio_devices_t *device)
2279{
2280 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2281 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2282 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2283
2284 mSoundTriggerSessions.add(*session, *ioHandle);
2285
2286 return NO_ERROR;
2287}
2288
2289status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2290{
2291 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2292 if (index < 0) {
2293 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2294 return BAD_VALUE;
2295 }
2296
2297 mSoundTriggerSessions.removeItem(session);
2298 return NO_ERROR;
2299}
2300
Eric Laurent6a94d692014-05-20 11:18:06 -07002301status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2302 const sp<AudioPatch>& patch)
2303{
2304 ssize_t index = mAudioPatches.indexOfKey(handle);
2305
2306 if (index >= 0) {
2307 ALOGW("addAudioPatch() patch %d already in", handle);
2308 return ALREADY_EXISTS;
2309 }
2310 mAudioPatches.add(handle, patch);
2311 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2312 "sink handle %d",
2313 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2314 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2315 return NO_ERROR;
2316}
2317
2318status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2319{
2320 ssize_t index = mAudioPatches.indexOfKey(handle);
2321
2322 if (index < 0) {
2323 ALOGW("removeAudioPatch() patch %d not in", handle);
2324 return ALREADY_EXISTS;
2325 }
2326 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2327 mAudioPatches.valueAt(index)->mAfPatchHandle);
2328 mAudioPatches.removeItemsAt(index);
2329 return NO_ERROR;
2330}
2331
Eric Laurente552edb2014-03-10 17:42:56 -07002332// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002333// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002334// ----------------------------------------------------------------------------
2335
Eric Laurent3a4311c2014-03-17 12:00:47 -07002336uint32_t AudioPolicyManager::nextUniqueId()
2337{
2338 return android_atomic_inc(&mNextUniqueId);
2339}
2340
Eric Laurent6a94d692014-05-20 11:18:06 -07002341uint32_t AudioPolicyManager::nextAudioPortGeneration()
2342{
2343 return android_atomic_inc(&mAudioPortGeneration);
2344}
2345
Eric Laurente0720872014-03-11 09:30:41 -07002346AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002347 :
2348#ifdef AUDIO_POLICY_TEST
2349 Thread(false),
2350#endif //AUDIO_POLICY_TEST
2351 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002352 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002353 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2354 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002355 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002356 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2357 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002358{
Eric Laurent6a94d692014-05-20 11:18:06 -07002359 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002360 mpClientInterface = clientInterface;
2361
Eric Laurent3b73df72014-03-11 09:06:29 -07002362 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2363 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002364 }
2365
Eric Laurent1afeecb2014-05-14 08:52:28 -07002366 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002367 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2368 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2369 ALOGE("could not load audio policy configuration file, setting defaults");
2370 defaultAudioPolicyConfig();
2371 }
2372 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002373 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002374
2375 // must be done after reading the policy
2376 initializeVolumeCurves();
2377
2378 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002379 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2380 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002381 for (size_t i = 0; i < mHwModules.size(); i++) {
2382 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2383 if (mHwModules[i]->mHandle == 0) {
2384 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2385 continue;
2386 }
2387 // open all output streams needed to access attached devices
2388 // except for direct output streams that are only opened when they are actually
2389 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002390 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002391 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2392 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002393 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002394
Eric Laurent3a4311c2014-03-17 12:00:47 -07002395 if (outProfile->mSupportedDevices.isEmpty()) {
2396 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2397 continue;
2398 }
2399
Eric Laurent83b88082014-06-20 18:31:16 -07002400 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2401 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2402 profileType = mDefaultOutputDevice->mDeviceType;
2403 } else {
2404 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2405 }
2406 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002407 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002408 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002409
Eric Laurent83b88082014-06-20 18:31:16 -07002410 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002411 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2412 config.sample_rate = outputDesc->mSamplingRate;
2413 config.channel_mask = outputDesc->mChannelMask;
2414 config.format = outputDesc->mFormat;
2415 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2416 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2417 &output,
2418 &config,
2419 &outputDesc->mDevice,
2420 String8(""),
2421 &outputDesc->mLatency,
2422 outputDesc->mFlags);
2423
2424 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002425 ALOGW("Cannot open output stream for device %08x on hw module %s",
2426 outputDesc->mDevice,
2427 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002428 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002429 outputDesc->mSamplingRate = config.sample_rate;
2430 outputDesc->mChannelMask = config.channel_mask;
2431 outputDesc->mFormat = config.format;
2432
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002433 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002434 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002435 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002436 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002437 // give a valid ID to an attached device once confirmed it is reachable
2438 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2439 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002440 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002441 }
2442 }
Eric Laurente552edb2014-03-10 17:42:56 -07002443 if (mPrimaryOutput == 0 &&
2444 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2445 mPrimaryOutput = output;
2446 }
2447 addOutput(output, outputDesc);
2448 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002449 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002450 true);
2451 }
2452 }
2453 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002454 // open input streams needed to access attached devices to validate
2455 // mAvailableInputDevices list
2456 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2457 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002458 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002459
Eric Laurent3a4311c2014-03-17 12:00:47 -07002460 if (inProfile->mSupportedDevices.isEmpty()) {
2461 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2462 continue;
2463 }
2464
Eric Laurent83b88082014-06-20 18:31:16 -07002465 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2466 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002467 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002468
2469 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002470 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002471
Eric Laurentcf2c0212014-07-25 16:20:43 -07002472 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2473 config.sample_rate = inputDesc->mSamplingRate;
2474 config.channel_mask = inputDesc->mChannelMask;
2475 config.format = inputDesc->mFormat;
2476 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2477 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2478 &input,
2479 &config,
2480 &inputDesc->mDevice,
2481 String8(""),
2482 AUDIO_SOURCE_MIC,
2483 AUDIO_INPUT_FLAG_NONE);
2484
2485 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002486 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002487 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002488 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002489 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002490 // give a valid ID to an attached device once confirmed it is reachable
2491 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2492 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002493 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002494 }
2495 }
2496 mpClientInterface->closeInput(input);
2497 } else {
2498 ALOGW("Cannot open input stream for device %08x on hw module %s",
2499 inputDesc->mDevice,
2500 mHwModules[i]->mName);
2501 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002502 }
2503 }
2504 }
2505 // make sure all attached devices have been allocated a unique ID
2506 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2507 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002508 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002509 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2510 continue;
2511 }
2512 i++;
2513 }
2514 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2515 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002516 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002517 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2518 continue;
2519 }
2520 i++;
2521 }
2522 // make sure default device is reachable
2523 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002524 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002525 }
Eric Laurente552edb2014-03-10 17:42:56 -07002526
2527 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2528
2529 updateDevicesAndOutputs();
2530
2531#ifdef AUDIO_POLICY_TEST
2532 if (mPrimaryOutput != 0) {
2533 AudioParameter outputCmd = AudioParameter();
2534 outputCmd.addInt(String8("set_id"), 0);
2535 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2536
2537 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2538 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002539 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2540 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002541 mTestLatencyMs = 0;
2542 mCurOutput = 0;
2543 mDirectOutput = false;
2544 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2545 mTestOutputs[i] = 0;
2546 }
2547
2548 const size_t SIZE = 256;
2549 char buffer[SIZE];
2550 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2551 run(buffer, ANDROID_PRIORITY_AUDIO);
2552 }
2553#endif //AUDIO_POLICY_TEST
2554}
2555
Eric Laurente0720872014-03-11 09:30:41 -07002556AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002557{
2558#ifdef AUDIO_POLICY_TEST
2559 exit();
2560#endif //AUDIO_POLICY_TEST
2561 for (size_t i = 0; i < mOutputs.size(); i++) {
2562 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002563 }
2564 for (size_t i = 0; i < mInputs.size(); i++) {
2565 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002566 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002567 mAvailableOutputDevices.clear();
2568 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002569 mOutputs.clear();
2570 mInputs.clear();
2571 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002572}
2573
Eric Laurente0720872014-03-11 09:30:41 -07002574status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002575{
2576 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2577}
2578
2579#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002580bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002581{
2582 ALOGV("entering threadLoop()");
2583 while (!exitPending())
2584 {
2585 String8 command;
2586 int valueInt;
2587 String8 value;
2588
2589 Mutex::Autolock _l(mLock);
2590 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2591
2592 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2593 AudioParameter param = AudioParameter(command);
2594
2595 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2596 valueInt != 0) {
2597 ALOGV("Test command %s received", command.string());
2598 String8 target;
2599 if (param.get(String8("target"), target) != NO_ERROR) {
2600 target = "Manager";
2601 }
2602 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2603 param.remove(String8("test_cmd_policy_output"));
2604 mCurOutput = valueInt;
2605 }
2606 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2607 param.remove(String8("test_cmd_policy_direct"));
2608 if (value == "false") {
2609 mDirectOutput = false;
2610 } else if (value == "true") {
2611 mDirectOutput = true;
2612 }
2613 }
2614 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2615 param.remove(String8("test_cmd_policy_input"));
2616 mTestInput = valueInt;
2617 }
2618
2619 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2620 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002621 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002622 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002623 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002624 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002625 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002626 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002627 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002628 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002629 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002630 if (target == "Manager") {
2631 mTestFormat = format;
2632 } else if (mTestOutputs[mCurOutput] != 0) {
2633 AudioParameter outputParam = AudioParameter();
2634 outputParam.addInt(String8("format"), format);
2635 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2636 }
2637 }
2638 }
2639 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2640 param.remove(String8("test_cmd_policy_channels"));
2641 int channels = 0;
2642
2643 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002644 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002645 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002646 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002647 }
2648 if (channels != 0) {
2649 if (target == "Manager") {
2650 mTestChannels = channels;
2651 } else if (mTestOutputs[mCurOutput] != 0) {
2652 AudioParameter outputParam = AudioParameter();
2653 outputParam.addInt(String8("channels"), channels);
2654 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2655 }
2656 }
2657 }
2658 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2659 param.remove(String8("test_cmd_policy_sampleRate"));
2660 if (valueInt >= 0 && valueInt <= 96000) {
2661 int samplingRate = valueInt;
2662 if (target == "Manager") {
2663 mTestSamplingRate = samplingRate;
2664 } else if (mTestOutputs[mCurOutput] != 0) {
2665 AudioParameter outputParam = AudioParameter();
2666 outputParam.addInt(String8("sampling_rate"), samplingRate);
2667 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2668 }
2669 }
2670 }
2671
2672 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2673 param.remove(String8("test_cmd_policy_reopen"));
2674
Eric Laurent1f2f2232014-06-02 12:01:23 -07002675 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002676 mpClientInterface->closeOutput(mPrimaryOutput);
2677
2678 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2679
Eric Laurente552edb2014-03-10 17:42:56 -07002680 mOutputs.removeItem(mPrimaryOutput);
2681
Eric Laurent1f2f2232014-06-02 12:01:23 -07002682 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002683 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002684 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2685 config.sample_rate = outputDesc->mSamplingRate;
2686 config.channel_mask = outputDesc->mChannelMask;
2687 config.format = outputDesc->mFormat;
2688 status_t status = mpClientInterface->openOutput(moduleHandle,
2689 &mPrimaryOutput,
2690 &config,
2691 &outputDesc->mDevice,
2692 String8(""),
2693 &outputDesc->mLatency,
2694 outputDesc->mFlags);
2695 if (status != NO_ERROR) {
2696 ALOGE("Failed to reopen hardware output stream, "
2697 "samplingRate: %d, format %d, channels %d",
2698 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002699 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002700 outputDesc->mSamplingRate = config.sample_rate;
2701 outputDesc->mChannelMask = config.channel_mask;
2702 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002703 AudioParameter outputCmd = AudioParameter();
2704 outputCmd.addInt(String8("set_id"), 0);
2705 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2706 addOutput(mPrimaryOutput, outputDesc);
2707 }
2708 }
2709
2710
2711 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2712 }
2713 }
2714 return false;
2715}
2716
Eric Laurente0720872014-03-11 09:30:41 -07002717void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002718{
2719 {
2720 AutoMutex _l(mLock);
2721 requestExit();
2722 mWaitWorkCV.signal();
2723 }
2724 requestExitAndWait();
2725}
2726
Eric Laurente0720872014-03-11 09:30:41 -07002727int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002728{
2729 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2730 if (output == mTestOutputs[i]) return i;
2731 }
2732 return 0;
2733}
2734#endif //AUDIO_POLICY_TEST
2735
2736// ---
2737
Eric Laurent1f2f2232014-06-02 12:01:23 -07002738void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002739{
Eric Laurent1c333e22014-05-20 10:48:17 -07002740 outputDesc->mIoHandle = output;
2741 outputDesc->mId = nextUniqueId();
2742 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002743 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002744}
2745
Eric Laurent1f2f2232014-06-02 12:01:23 -07002746void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002747{
Eric Laurent1c333e22014-05-20 10:48:17 -07002748 inputDesc->mIoHandle = input;
2749 inputDesc->mId = nextUniqueId();
2750 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002751 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002752}
Eric Laurente552edb2014-03-10 17:42:56 -07002753
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002754void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2755 const String8 address /*in*/,
2756 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2757 // look for a match on the given address on the addresses of the outputs:
2758 // find the address by finding the patch that maps to this output
2759 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2760 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2761 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2762 if (patchIdx >= 0) {
2763 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2764 const int numSinks = patchDesc->mPatch.num_sinks;
2765 for (ssize_t j=0; j < numSinks; j++) {
2766 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2767 const char* patchAddr =
2768 patchDesc->mPatch.sinks[j].ext.device.address;
2769 if (strncmp(patchAddr,
2770 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2771 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2772 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2773 outputs.add(desc->mIoHandle);
2774 break;
2775 }
2776 }
2777 }
2778 }
2779}
2780
Eric Laurente0720872014-03-11 09:30:41 -07002781status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002782 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002783 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002784 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002785{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002786 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002787
Eric Laurent3b73df72014-03-11 09:06:29 -07002788 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002789 // first list already open outputs that can be routed to this device
2790 for (size_t i = 0; i < mOutputs.size(); i++) {
2791 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002792 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002793 if (!deviceDistinguishesOnAddress(device)) {
2794 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2795 outputs.add(mOutputs.keyAt(i));
2796 } else {
2797 ALOGV(" checking address match due to device 0x%x", device);
2798 findIoHandlesByAddress(desc, address, outputs);
2799 }
Eric Laurente552edb2014-03-10 17:42:56 -07002800 }
2801 }
2802 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002803 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002804 for (size_t i = 0; i < mHwModules.size(); i++)
2805 {
2806 if (mHwModules[i]->mHandle == 0) {
2807 continue;
2808 }
2809 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2810 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002811 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002812 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002813 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2814 }
2815 }
2816 }
2817
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002818 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2819
Eric Laurente552edb2014-03-10 17:42:56 -07002820 if (profiles.isEmpty() && outputs.isEmpty()) {
2821 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2822 return BAD_VALUE;
2823 }
2824
2825 // open outputs for matching profiles if needed. Direct outputs are also opened to
2826 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2827 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002828 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002829
2830 // nothing to do if one output is already opened for this profile
2831 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002832 for (j = 0; j < outputs.size(); j++) {
2833 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002834 if (!desc->isDuplicated() && desc->mProfile == profile) {
2835 break;
2836 }
2837 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002838 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002839 continue;
2840 }
2841
Eric Laurent83b88082014-06-20 18:31:16 -07002842 ALOGV("opening output for device %08x with params %s profile %p",
2843 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002844 desc = new AudioOutputDescriptor(profile);
2845 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002846 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2847 config.sample_rate = desc->mSamplingRate;
2848 config.channel_mask = desc->mChannelMask;
2849 config.format = desc->mFormat;
2850 config.offload_info.sample_rate = desc->mSamplingRate;
2851 config.offload_info.channel_mask = desc->mChannelMask;
2852 config.offload_info.format = desc->mFormat;
2853 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2854 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
2855 &output,
2856 &config,
2857 &desc->mDevice,
2858 address,
2859 &desc->mLatency,
2860 desc->mFlags);
2861 if (status == NO_ERROR) {
2862 desc->mSamplingRate = config.sample_rate;
2863 desc->mChannelMask = config.channel_mask;
2864 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002865
Eric Laurentd4692962014-05-05 18:13:44 -07002866 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002867 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002868 char *param = audio_device_address_to_parameter(device, address);
2869 mpClientInterface->setParameters(output, String8(param));
2870 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07002871 }
2872
Eric Laurentd4692962014-05-05 18:13:44 -07002873 // Here is where we step through and resolve any "dynamic" fields
2874 String8 reply;
2875 char *value;
2876 if (profile->mSamplingRates[0] == 0) {
2877 reply = mpClientInterface->getParameters(output,
2878 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002879 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002880 reply.string());
2881 value = strpbrk((char *)reply.string(), "=");
2882 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002883 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002884 }
Eric Laurentd4692962014-05-05 18:13:44 -07002885 }
2886 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2887 reply = mpClientInterface->getParameters(output,
2888 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002889 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002890 reply.string());
2891 value = strpbrk((char *)reply.string(), "=");
2892 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002893 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002894 }
Eric Laurentd4692962014-05-05 18:13:44 -07002895 }
2896 if (profile->mChannelMasks[0] == 0) {
2897 reply = mpClientInterface->getParameters(output,
2898 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002899 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002900 reply.string());
2901 value = strpbrk((char *)reply.string(), "=");
2902 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002903 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002904 }
Eric Laurentd4692962014-05-05 18:13:44 -07002905 }
2906 if (((profile->mSamplingRates[0] == 0) &&
2907 (profile->mSamplingRates.size() < 2)) ||
2908 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2909 (profile->mFormats.size() < 2)) ||
2910 ((profile->mChannelMasks[0] == 0) &&
2911 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002912 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002913 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002914 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07002915 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2916 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002917 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002918 config.sample_rate = profile->pickSamplingRate();
2919 config.channel_mask = profile->pickChannelMask();
2920 config.format = profile->pickFormat();
2921 config.offload_info.sample_rate = config.sample_rate;
2922 config.offload_info.channel_mask = config.channel_mask;
2923 config.offload_info.format = config.format;
2924 status = mpClientInterface->openOutput(profile->mModule->mHandle,
2925 &output,
2926 &config,
2927 &desc->mDevice,
2928 address,
2929 &desc->mLatency,
2930 desc->mFlags);
2931 if (status == NO_ERROR) {
2932 desc->mSamplingRate = config.sample_rate;
2933 desc->mChannelMask = config.channel_mask;
2934 desc->mFormat = config.format;
2935 } else {
2936 output = AUDIO_IO_HANDLE_NONE;
2937 }
Eric Laurentd4692962014-05-05 18:13:44 -07002938 }
2939
Eric Laurentcf2c0212014-07-25 16:20:43 -07002940 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002941 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002942 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002943 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002944
Eric Laurentd4692962014-05-05 18:13:44 -07002945 // set initial stream volume for device
2946 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002947
Eric Laurentd4692962014-05-05 18:13:44 -07002948 //TODO: configure audio effect output stage here
2949
2950 // open a duplicating output thread for the new output and the primary output
2951 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2952 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002953 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07002954 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07002955 sp<AudioOutputDescriptor> dupOutputDesc =
2956 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002957 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2958 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2959 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2960 dupOutputDesc->mFormat = desc->mFormat;
2961 dupOutputDesc->mChannelMask = desc->mChannelMask;
2962 dupOutputDesc->mLatency = desc->mLatency;
2963 addOutput(duplicatedOutput, dupOutputDesc);
2964 applyStreamVolumes(duplicatedOutput, device, 0, true);
2965 } else {
2966 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2967 mPrimaryOutput, output);
2968 mpClientInterface->closeOutput(output);
2969 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002970 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002971 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07002972 }
Eric Laurente552edb2014-03-10 17:42:56 -07002973 }
2974 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002975 } else {
2976 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002977 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002978 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002979 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002980 profiles.removeAt(profile_index);
2981 profile_index--;
2982 } else {
2983 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002984 if (deviceDistinguishesOnAddress(device)) {
2985 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2986 device, address.string());
2987 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2988 NULL/*patch handle*/, address.string());
2989 }
Eric Laurente552edb2014-03-10 17:42:56 -07002990 ALOGV("checkOutputsForDevice(): adding output %d", output);
2991 }
2992 }
2993
2994 if (profiles.isEmpty()) {
2995 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2996 return BAD_VALUE;
2997 }
Eric Laurentd4692962014-05-05 18:13:44 -07002998 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002999 // check if one opened output is not needed any more after disconnecting one device
3000 for (size_t i = 0; i < mOutputs.size(); i++) {
3001 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003002 if (!desc->isDuplicated()) {
3003 if (!(desc->mProfile->mSupportedDevices.types()
3004 & mAvailableOutputDevices.types())) {
3005 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3006 mOutputs.keyAt(i));
3007 outputs.add(mOutputs.keyAt(i));
3008 } else if (deviceDistinguishesOnAddress(device) &&
3009 // exact match on device
3010 (desc->mProfile->mSupportedDevices.types() == device)) {
3011 findIoHandlesByAddress(desc, address, outputs);
3012 }
Eric Laurente552edb2014-03-10 17:42:56 -07003013 }
3014 }
Eric Laurentd4692962014-05-05 18:13:44 -07003015 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003016 for (size_t i = 0; i < mHwModules.size(); i++)
3017 {
3018 if (mHwModules[i]->mHandle == 0) {
3019 continue;
3020 }
3021 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3022 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003023 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003024 if (profile->mSupportedDevices.types() & device) {
3025 ALOGV("checkOutputsForDevice(): "
3026 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003027 if (profile->mSamplingRates[0] == 0) {
3028 profile->mSamplingRates.clear();
3029 profile->mSamplingRates.add(0);
3030 }
3031 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3032 profile->mFormats.clear();
3033 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3034 }
3035 if (profile->mChannelMasks[0] == 0) {
3036 profile->mChannelMasks.clear();
3037 profile->mChannelMasks.add(0);
3038 }
3039 }
3040 }
3041 }
3042 }
3043 return NO_ERROR;
3044}
3045
Eric Laurentd4692962014-05-05 18:13:44 -07003046status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3047 audio_policy_dev_state_t state,
3048 SortedVector<audio_io_handle_t>& inputs,
3049 const String8 address)
3050{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003051 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003052 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3053 // first list already open inputs that can be routed to this device
3054 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3055 desc = mInputs.valueAt(input_index);
3056 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3057 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3058 inputs.add(mInputs.keyAt(input_index));
3059 }
3060 }
3061
3062 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003063 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003064 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3065 {
3066 if (mHwModules[module_idx]->mHandle == 0) {
3067 continue;
3068 }
3069 for (size_t profile_index = 0;
3070 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3071 profile_index++)
3072 {
3073 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3074 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003075 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003076 profile_index, module_idx);
3077 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3078 }
3079 }
3080 }
3081
3082 if (profiles.isEmpty() && inputs.isEmpty()) {
3083 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3084 return BAD_VALUE;
3085 }
3086
3087 // open inputs for matching profiles if needed. Direct inputs are also opened to
3088 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3089 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3090
Eric Laurent1c333e22014-05-20 10:48:17 -07003091 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003092 // nothing to do if one input is already opened for this profile
3093 size_t input_index;
3094 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3095 desc = mInputs.valueAt(input_index);
3096 if (desc->mProfile == profile) {
3097 break;
3098 }
3099 }
3100 if (input_index != mInputs.size()) {
3101 continue;
3102 }
3103
3104 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3105 desc = new AudioInputDescriptor(profile);
3106 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003107 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3108 config.sample_rate = desc->mSamplingRate;
3109 config.channel_mask = desc->mChannelMask;
3110 config.format = desc->mFormat;
3111 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3112 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3113 &input,
3114 &config,
3115 &desc->mDevice,
3116 address,
3117 AUDIO_SOURCE_MIC,
3118 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003119
Eric Laurentcf2c0212014-07-25 16:20:43 -07003120 if (status == NO_ERROR) {
3121 desc->mSamplingRate = config.sample_rate;
3122 desc->mChannelMask = config.channel_mask;
3123 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003124
Eric Laurentd4692962014-05-05 18:13:44 -07003125 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003126 char *param = audio_device_address_to_parameter(device, address);
3127 mpClientInterface->setParameters(input, String8(param));
3128 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003129 }
3130
3131 // Here is where we step through and resolve any "dynamic" fields
3132 String8 reply;
3133 char *value;
3134 if (profile->mSamplingRates[0] == 0) {
3135 reply = mpClientInterface->getParameters(input,
3136 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3137 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3138 reply.string());
3139 value = strpbrk((char *)reply.string(), "=");
3140 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003141 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003142 }
3143 }
3144 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3145 reply = mpClientInterface->getParameters(input,
3146 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3147 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3148 value = strpbrk((char *)reply.string(), "=");
3149 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003150 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003151 }
3152 }
3153 if (profile->mChannelMasks[0] == 0) {
3154 reply = mpClientInterface->getParameters(input,
3155 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3156 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3157 reply.string());
3158 value = strpbrk((char *)reply.string(), "=");
3159 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003160 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003161 }
3162 }
3163 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3164 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3165 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3166 ALOGW("checkInputsForDevice() direct input missing param");
3167 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003168 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003169 }
3170
3171 if (input != 0) {
3172 addInput(input, desc);
3173 }
3174 } // endif input != 0
3175
Eric Laurentcf2c0212014-07-25 16:20:43 -07003176 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003177 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003178 profiles.removeAt(profile_index);
3179 profile_index--;
3180 } else {
3181 inputs.add(input);
3182 ALOGV("checkInputsForDevice(): adding input %d", input);
3183 }
3184 } // end scan profiles
3185
3186 if (profiles.isEmpty()) {
3187 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3188 return BAD_VALUE;
3189 }
3190 } else {
3191 // Disconnect
3192 // check if one opened input is not needed any more after disconnecting one device
3193 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3194 desc = mInputs.valueAt(input_index);
3195 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3196 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3197 mInputs.keyAt(input_index));
3198 inputs.add(mInputs.keyAt(input_index));
3199 }
3200 }
3201 // Clear any profiles associated with the disconnected device.
3202 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3203 if (mHwModules[module_index]->mHandle == 0) {
3204 continue;
3205 }
3206 for (size_t profile_index = 0;
3207 profile_index < mHwModules[module_index]->mInputProfiles.size();
3208 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003209 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003210 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003211 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003212 profile_index, module_index);
3213 if (profile->mSamplingRates[0] == 0) {
3214 profile->mSamplingRates.clear();
3215 profile->mSamplingRates.add(0);
3216 }
3217 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3218 profile->mFormats.clear();
3219 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3220 }
3221 if (profile->mChannelMasks[0] == 0) {
3222 profile->mChannelMasks.clear();
3223 profile->mChannelMasks.add(0);
3224 }
3225 }
3226 }
3227 }
3228 } // end disconnect
3229
3230 return NO_ERROR;
3231}
3232
3233
Eric Laurente0720872014-03-11 09:30:41 -07003234void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003235{
3236 ALOGV("closeOutput(%d)", output);
3237
Eric Laurent1f2f2232014-06-02 12:01:23 -07003238 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003239 if (outputDesc == NULL) {
3240 ALOGW("closeOutput() unknown output %d", output);
3241 return;
3242 }
3243
3244 // look for duplicated outputs connected to the output being removed.
3245 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003246 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003247 if (dupOutputDesc->isDuplicated() &&
3248 (dupOutputDesc->mOutput1 == outputDesc ||
3249 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003250 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003251 if (dupOutputDesc->mOutput1 == outputDesc) {
3252 outputDesc2 = dupOutputDesc->mOutput2;
3253 } else {
3254 outputDesc2 = dupOutputDesc->mOutput1;
3255 }
3256 // As all active tracks on duplicated output will be deleted,
3257 // and as they were also referenced on the other output, the reference
3258 // count for their stream type must be adjusted accordingly on
3259 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003260 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003261 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003262 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003263 }
3264 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3265 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3266
3267 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003268 mOutputs.removeItem(duplicatedOutput);
3269 }
3270 }
3271
3272 AudioParameter param;
3273 param.add(String8("closing"), String8("true"));
3274 mpClientInterface->setParameters(output, param.toString());
3275
3276 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003277 mOutputs.removeItem(output);
3278 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003279 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003280}
3281
Eric Laurente0720872014-03-11 09:30:41 -07003282SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003283 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003284{
3285 SortedVector<audio_io_handle_t> outputs;
3286
3287 ALOGVV("getOutputsForDevice() device %04x", device);
3288 for (size_t i = 0; i < openOutputs.size(); i++) {
3289 ALOGVV("output %d isDuplicated=%d device=%04x",
3290 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3291 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3292 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3293 outputs.add(openOutputs.keyAt(i));
3294 }
3295 }
3296 return outputs;
3297}
3298
Eric Laurente0720872014-03-11 09:30:41 -07003299bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003300 SortedVector<audio_io_handle_t>& outputs2)
3301{
3302 if (outputs1.size() != outputs2.size()) {
3303 return false;
3304 }
3305 for (size_t i = 0; i < outputs1.size(); i++) {
3306 if (outputs1[i] != outputs2[i]) {
3307 return false;
3308 }
3309 }
3310 return true;
3311}
3312
Eric Laurente0720872014-03-11 09:30:41 -07003313void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003314{
3315 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3316 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3317 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3318 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3319
3320 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3321 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3322 strategy, srcOutputs[0], dstOutputs[0]);
3323 // mute strategy while moving tracks from one output to another
3324 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003325 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003326 if (desc->isStrategyActive(strategy)) {
3327 setStrategyMute(strategy, true, srcOutputs[i]);
3328 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3329 }
3330 }
3331
3332 // Move effects associated to this strategy from previous output to new output
3333 if (strategy == STRATEGY_MEDIA) {
3334 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3335 SortedVector<audio_io_handle_t> moved;
3336 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003337 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3338 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3339 effectDesc->mIo != fxOutput) {
3340 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003341 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3342 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003343 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003344 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003345 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003346 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003347 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003348 }
3349 }
3350 }
3351 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003352 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3353 if (getStrategy((audio_stream_type_t)i) == strategy) {
3354 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003355 }
3356 }
3357 }
3358}
3359
Eric Laurente0720872014-03-11 09:30:41 -07003360void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003361{
3362 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3363 checkOutputForStrategy(STRATEGY_PHONE);
3364 checkOutputForStrategy(STRATEGY_SONIFICATION);
3365 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3366 checkOutputForStrategy(STRATEGY_MEDIA);
3367 checkOutputForStrategy(STRATEGY_DTMF);
3368}
3369
Eric Laurente0720872014-03-11 09:30:41 -07003370audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003371{
Eric Laurente552edb2014-03-10 17:42:56 -07003372 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003373 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003374 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3375 return mOutputs.keyAt(i);
3376 }
3377 }
3378
3379 return 0;
3380}
3381
Eric Laurente0720872014-03-11 09:30:41 -07003382void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003383{
Eric Laurente552edb2014-03-10 17:42:56 -07003384 audio_io_handle_t a2dpOutput = getA2dpOutput();
3385 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003386 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003387 return;
3388 }
3389
Eric Laurent3a4311c2014-03-17 12:00:47 -07003390 bool isScoConnected =
3391 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003392 // suspend A2DP output if:
3393 // (NOT already suspended) &&
3394 // ((SCO device is connected &&
3395 // (forced usage for communication || for record is SCO))) ||
3396 // (phone state is ringing || in call)
3397 //
3398 // restore A2DP output if:
3399 // (Already suspended) &&
3400 // ((SCO device is NOT connected ||
3401 // (forced usage NOT for communication && NOT for record is SCO))) &&
3402 // (phone state is NOT ringing && NOT in call)
3403 //
3404 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003405 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003406 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3407 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3408 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3409 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003410
3411 mpClientInterface->restoreOutput(a2dpOutput);
3412 mA2dpSuspended = false;
3413 }
3414 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003415 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003416 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3417 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3418 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3419 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003420
3421 mpClientInterface->suspendOutput(a2dpOutput);
3422 mA2dpSuspended = true;
3423 }
3424 }
3425}
3426
Eric Laurent1c333e22014-05-20 10:48:17 -07003427audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003428{
3429 audio_devices_t device = AUDIO_DEVICE_NONE;
3430
Eric Laurent1f2f2232014-06-02 12:01:23 -07003431 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003432
3433 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3434 if (index >= 0) {
3435 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3436 if (patchDesc->mUid != mUidCached) {
3437 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3438 outputDesc->device(), outputDesc->mPatchHandle);
3439 return outputDesc->device();
3440 }
3441 }
3442
Eric Laurente552edb2014-03-10 17:42:56 -07003443 // check the following by order of priority to request a routing change if necessary:
3444 // 1: the strategy enforced audible is active on the output:
3445 // use device for strategy enforced audible
3446 // 2: we are in call or the strategy phone is active on the output:
3447 // use device for strategy phone
3448 // 3: the strategy sonification is active on the output:
3449 // use device for strategy sonification
3450 // 4: the strategy "respectful" sonification is active on the output:
3451 // use device for strategy "respectful" sonification
3452 // 5: the strategy media is active on the output:
3453 // use device for strategy media
3454 // 6: the strategy DTMF is active on the output:
3455 // use device for strategy DTMF
3456 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3457 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3458 } else if (isInCall() ||
3459 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3460 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3461 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3462 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3463 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3464 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3465 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3466 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3467 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3468 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3469 }
3470
Eric Laurent1c333e22014-05-20 10:48:17 -07003471 ALOGV("getNewOutputDevice() selected device %x", device);
3472 return device;
3473}
3474
3475audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3476{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003477 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003478
3479 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3480 if (index >= 0) {
3481 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3482 if (patchDesc->mUid != mUidCached) {
3483 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3484 inputDesc->mDevice, inputDesc->mPatchHandle);
3485 return inputDesc->mDevice;
3486 }
3487 }
3488
Eric Laurent1c333e22014-05-20 10:48:17 -07003489 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3490
3491 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003492 return device;
3493}
3494
Eric Laurente0720872014-03-11 09:30:41 -07003495uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003496 return (uint32_t)getStrategy(stream);
3497}
3498
Eric Laurente0720872014-03-11 09:30:41 -07003499audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003500 // By checking the range of stream before calling getStrategy, we avoid
3501 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3502 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003503 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003504 return AUDIO_DEVICE_NONE;
3505 }
3506 audio_devices_t devices;
3507 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3508 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3509 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3510 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003511 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003512 if (outputDesc->isStrategyActive(strategy)) {
3513 devices = outputDesc->device();
3514 break;
3515 }
Eric Laurente552edb2014-03-10 17:42:56 -07003516 }
3517 return devices;
3518}
3519
Eric Laurente0720872014-03-11 09:30:41 -07003520AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003521 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003522 // stream to strategy mapping
3523 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003524 case AUDIO_STREAM_VOICE_CALL:
3525 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003526 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003527 case AUDIO_STREAM_RING:
3528 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003529 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003530 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003531 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003532 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003533 return STRATEGY_DTMF;
3534 default:
3535 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003536 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003537 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3538 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003539 case AUDIO_STREAM_TTS:
3540 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003541 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003542 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003543 return STRATEGY_ENFORCED_AUDIBLE;
3544 }
3545}
3546
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003547uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3548 // flags to strategy mapping
3549 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3550 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3551 }
3552
3553 // usage to strategy mapping
3554 switch (attr->usage) {
3555 case AUDIO_USAGE_MEDIA:
3556 case AUDIO_USAGE_GAME:
3557 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3558 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3559 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3560 return (uint32_t) STRATEGY_MEDIA;
3561
3562 case AUDIO_USAGE_VOICE_COMMUNICATION:
3563 return (uint32_t) STRATEGY_PHONE;
3564
3565 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3566 return (uint32_t) STRATEGY_DTMF;
3567
3568 case AUDIO_USAGE_ALARM:
3569 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3570 return (uint32_t) STRATEGY_SONIFICATION;
3571
3572 case AUDIO_USAGE_NOTIFICATION:
3573 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3574 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3575 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3576 case AUDIO_USAGE_NOTIFICATION_EVENT:
3577 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3578
3579 case AUDIO_USAGE_UNKNOWN:
3580 default:
3581 return (uint32_t) STRATEGY_MEDIA;
3582 }
3583}
3584
Eric Laurente0720872014-03-11 09:30:41 -07003585void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003586 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003587 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003588 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3589 updateDevicesAndOutputs();
3590 break;
3591 default:
3592 break;
3593 }
3594}
3595
Eric Laurente0720872014-03-11 09:30:41 -07003596audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003597 bool fromCache)
3598{
3599 uint32_t device = AUDIO_DEVICE_NONE;
3600
3601 if (fromCache) {
3602 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3603 strategy, mDeviceForStrategy[strategy]);
3604 return mDeviceForStrategy[strategy];
3605 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003606 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003607 switch (strategy) {
3608
3609 case STRATEGY_SONIFICATION_RESPECTFUL:
3610 if (isInCall()) {
3611 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003612 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003613 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3614 // while media is playing on a remote device, use the the sonification behavior.
3615 // Note that we test this usecase before testing if media is playing because
3616 // the isStreamActive() method only informs about the activity of a stream, not
3617 // if it's for local playback. Note also that we use the same delay between both tests
3618 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003619 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003620 // while media is playing (or has recently played), use the same device
3621 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3622 } else {
3623 // when media is not playing anymore, fall back on the sonification behavior
3624 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3625 }
3626
3627 break;
3628
3629 case STRATEGY_DTMF:
3630 if (!isInCall()) {
3631 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3632 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3633 break;
3634 }
3635 // when in call, DTMF and PHONE strategies follow the same rules
3636 // FALL THROUGH
3637
3638 case STRATEGY_PHONE:
3639 // for phone strategy, we first consider the forced use and then the available devices by order
3640 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003641 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3642 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003643 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003644 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003645 if (device) break;
3646 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003647 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003648 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 if (device) break;
3651 // if SCO device is requested but no SCO device is available, fall back to default case
3652 // FALL THROUGH
3653
3654 default: // FORCE_NONE
3655 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003656 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003657 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003658 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003659 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003660 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003661 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003662 if (device) break;
3663 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003664 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003665 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003666 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003667 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003668 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003669 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003670 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003671 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003672 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003673 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003674 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003675 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003676 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003677 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003678 if (device) break;
3679 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003680 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003681 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003682 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003683 if (device == AUDIO_DEVICE_NONE) {
3684 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3685 }
3686 break;
3687
Eric Laurent3b73df72014-03-11 09:06:29 -07003688 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003689 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3690 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003691 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003692 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003693 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003694 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003695 if (device) break;
3696 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003697 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003698 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003699 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003700 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003701 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003702 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003703 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003704 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003705 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003706 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003707 if (device) break;
3708 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003709 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3710 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003711 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003712 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003713 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003714 if (device == AUDIO_DEVICE_NONE) {
3715 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3716 }
3717 break;
3718 }
3719 break;
3720
3721 case STRATEGY_SONIFICATION:
3722
3723 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3724 // handleIncallSonification().
3725 if (isInCall()) {
3726 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3727 break;
3728 }
3729 // FALL THROUGH
3730
3731 case STRATEGY_ENFORCED_AUDIBLE:
3732 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3733 // except:
3734 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3735 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3736
3737 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003738 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003739 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003740 if (device == AUDIO_DEVICE_NONE) {
3741 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3742 }
3743 }
3744 // The second device used for sonification is the same as the device used by media strategy
3745 // FALL THROUGH
3746
3747 case STRATEGY_MEDIA: {
3748 uint32_t device2 = AUDIO_DEVICE_NONE;
3749 if (strategy != STRATEGY_SONIFICATION) {
3750 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003751 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003752 }
3753 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003754 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003755 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003756 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003757 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003758 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003759 }
3760 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003761 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003762 }
3763 }
3764 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003765 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003766 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003767 if ((device2 == AUDIO_DEVICE_NONE)) {
3768 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3769 }
Eric Laurente552edb2014-03-10 17:42:56 -07003770 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003771 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003772 }
3773 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003774 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003775 }
3776 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003777 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003778 }
3779 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003780 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003781 }
3782 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3783 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003784 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003785 }
3786 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003787 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003788 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003789 }
3790 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003791 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003792 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003793 int device3 = AUDIO_DEVICE_NONE;
3794 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003795 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003796 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3797 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003798 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003799 }
Eric Laurente552edb2014-03-10 17:42:56 -07003800
Jungshik Jang839e4f32014-06-26 17:23:40 +09003801 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003802 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3803 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3804 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003805
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003806 // If hdmi system audio mode is on, remove speaker out of output list.
3807 if ((strategy == STRATEGY_MEDIA) &&
3808 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3809 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3810 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3811 }
3812
Eric Laurente552edb2014-03-10 17:42:56 -07003813 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003814 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003815 if (device == AUDIO_DEVICE_NONE) {
3816 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3817 }
3818 } break;
3819
3820 default:
3821 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3822 break;
3823 }
3824
3825 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3826 return device;
3827}
3828
Eric Laurente0720872014-03-11 09:30:41 -07003829void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003830{
3831 for (int i = 0; i < NUM_STRATEGIES; i++) {
3832 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3833 }
3834 mPreviousOutputs = mOutputs;
3835}
3836
Eric Laurent1f2f2232014-06-02 12:01:23 -07003837uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003838 audio_devices_t prevDevice,
3839 uint32_t delayMs)
3840{
3841 // mute/unmute strategies using an incompatible device combination
3842 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3843 // if unmuting, unmute only after the specified delay
3844 if (outputDesc->isDuplicated()) {
3845 return 0;
3846 }
3847
3848 uint32_t muteWaitMs = 0;
3849 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003850 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003851
3852 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3853 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3854 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3855 bool doMute = false;
3856
3857 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3858 doMute = true;
3859 outputDesc->mStrategyMutedByDevice[i] = true;
3860 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3861 doMute = true;
3862 outputDesc->mStrategyMutedByDevice[i] = false;
3863 }
Eric Laurent99401132014-05-07 19:48:15 -07003864 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003865 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003866 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003867 // skip output if it does not share any device with current output
3868 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3869 == AUDIO_DEVICE_NONE) {
3870 continue;
3871 }
3872 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3873 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3874 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3875 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3876 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003877 if (mute) {
3878 // FIXME: should not need to double latency if volume could be applied
3879 // immediately by the audioflinger mixer. We must account for the delay
3880 // between now and the next time the audioflinger thread for this output
3881 // will process a buffer (which corresponds to one buffer size,
3882 // usually 1/2 or 1/4 of the latency).
3883 if (muteWaitMs < desc->latency() * 2) {
3884 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003885 }
3886 }
3887 }
3888 }
3889 }
3890 }
3891
Eric Laurent99401132014-05-07 19:48:15 -07003892 // temporary mute output if device selection changes to avoid volume bursts due to
3893 // different per device volumes
3894 if (outputDesc->isActive() && (device != prevDevice)) {
3895 if (muteWaitMs < outputDesc->latency() * 2) {
3896 muteWaitMs = outputDesc->latency() * 2;
3897 }
3898 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3899 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003900 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003901 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003902 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003903 muteWaitMs *2, device);
3904 }
3905 }
3906 }
3907
Eric Laurente552edb2014-03-10 17:42:56 -07003908 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3909 if (muteWaitMs > delayMs) {
3910 muteWaitMs -= delayMs;
3911 usleep(muteWaitMs * 1000);
3912 return muteWaitMs;
3913 }
3914 return 0;
3915}
3916
Eric Laurente0720872014-03-11 09:30:41 -07003917uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003918 audio_devices_t device,
3919 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003920 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003921 audio_patch_handle_t *patchHandle,
3922 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003923{
3924 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003925 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003926 AudioParameter param;
3927 uint32_t muteWaitMs;
3928
3929 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003930 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3931 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003932 return muteWaitMs;
3933 }
3934 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3935 // output profile
3936 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003938 return 0;
3939 }
3940
3941 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003942 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003943
3944 audio_devices_t prevDevice = outputDesc->mDevice;
3945
3946 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3947
3948 if (device != AUDIO_DEVICE_NONE) {
3949 outputDesc->mDevice = device;
3950 }
3951 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3952
3953 // Do not change the routing if:
3954 // - the requested device is AUDIO_DEVICE_NONE
3955 // - the requested device is the same as current device and force is not specified.
3956 // Doing this check here allows the caller to call setOutputDevice() without conditions
3957 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3958 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3959 return muteWaitMs;
3960 }
3961
3962 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003963
Eric Laurente552edb2014-03-10 17:42:56 -07003964 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003965 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003966 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003967 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003968 DeviceVector deviceList = (address == NULL) ?
3969 mAvailableOutputDevices.getDevicesFromType(device)
3970 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003971 if (!deviceList.isEmpty()) {
3972 struct audio_patch patch;
3973 outputDesc->toAudioPortConfig(&patch.sources[0]);
3974 patch.num_sources = 1;
3975 patch.num_sinks = 0;
3976 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3977 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003978 patch.num_sinks++;
3979 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 ssize_t index;
3981 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3982 index = mAudioPatches.indexOfKey(*patchHandle);
3983 } else {
3984 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3985 }
3986 sp< AudioPatch> patchDesc;
3987 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3988 if (index >= 0) {
3989 patchDesc = mAudioPatches.valueAt(index);
3990 afPatchHandle = patchDesc->mAfPatchHandle;
3991 }
3992
Eric Laurent1c333e22014-05-20 10:48:17 -07003993 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003994 &afPatchHandle,
3995 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003996 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3997 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003998 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003999 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004000 if (index < 0) {
4001 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4002 &patch, mUidCached);
4003 addAudioPatch(patchDesc->mHandle, patchDesc);
4004 } else {
4005 patchDesc->mPatch = patch;
4006 }
4007 patchDesc->mAfPatchHandle = afPatchHandle;
4008 patchDesc->mUid = mUidCached;
4009 if (patchHandle) {
4010 *patchHandle = patchDesc->mHandle;
4011 }
4012 outputDesc->mPatchHandle = patchDesc->mHandle;
4013 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004014 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004015 }
4016 }
4017 }
Eric Laurente552edb2014-03-10 17:42:56 -07004018
4019 // update stream volumes according to new device
4020 applyStreamVolumes(output, device, delayMs);
4021
4022 return muteWaitMs;
4023}
4024
Eric Laurent1c333e22014-05-20 10:48:17 -07004025status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004026 int delayMs,
4027 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004028{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004029 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004030 ssize_t index;
4031 if (patchHandle) {
4032 index = mAudioPatches.indexOfKey(*patchHandle);
4033 } else {
4034 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4035 }
4036 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004037 return INVALID_OPERATION;
4038 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004039 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4040 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004041 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4042 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004043 removeAudioPatch(patchDesc->mHandle);
4044 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004045 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004046 return status;
4047}
4048
4049status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4050 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004051 bool force,
4052 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004053{
4054 status_t status = NO_ERROR;
4055
Eric Laurent1f2f2232014-06-02 12:01:23 -07004056 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004057 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4058 inputDesc->mDevice = device;
4059
4060 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4061 if (!deviceList.isEmpty()) {
4062 struct audio_patch patch;
4063 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004064 // AUDIO_SOURCE_HOTWORD is for internal use only:
4065 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004066 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4067 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004068 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4069 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004070 patch.num_sinks = 1;
4071 //only one input device for now
4072 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004073 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004074 ssize_t index;
4075 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4076 index = mAudioPatches.indexOfKey(*patchHandle);
4077 } else {
4078 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4079 }
4080 sp< AudioPatch> patchDesc;
4081 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4082 if (index >= 0) {
4083 patchDesc = mAudioPatches.valueAt(index);
4084 afPatchHandle = patchDesc->mAfPatchHandle;
4085 }
4086
Eric Laurent1c333e22014-05-20 10:48:17 -07004087 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004088 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004089 0);
4090 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004091 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004092 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004093 if (index < 0) {
4094 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4095 &patch, mUidCached);
4096 addAudioPatch(patchDesc->mHandle, patchDesc);
4097 } else {
4098 patchDesc->mPatch = patch;
4099 }
4100 patchDesc->mAfPatchHandle = afPatchHandle;
4101 patchDesc->mUid = mUidCached;
4102 if (patchHandle) {
4103 *patchHandle = patchDesc->mHandle;
4104 }
4105 inputDesc->mPatchHandle = patchDesc->mHandle;
4106 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004107 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004108 }
4109 }
4110 }
4111 return status;
4112}
4113
Eric Laurent6a94d692014-05-20 11:18:06 -07004114status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4115 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004116{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004117 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004118 ssize_t index;
4119 if (patchHandle) {
4120 index = mAudioPatches.indexOfKey(*patchHandle);
4121 } else {
4122 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4123 }
4124 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004125 return INVALID_OPERATION;
4126 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004127 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4128 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004129 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4130 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004131 removeAudioPatch(patchDesc->mHandle);
4132 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004133 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004134 return status;
4135}
4136
4137sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004138 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004139 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004140 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004141 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004142{
4143 // Choose an input profile based on the requested capture parameters: select the first available
4144 // profile supporting all requested parameters.
4145
4146 for (size_t i = 0; i < mHwModules.size(); i++)
4147 {
4148 if (mHwModules[i]->mHandle == 0) {
4149 continue;
4150 }
4151 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4152 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004153 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004154 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004155 if (profile->isCompatibleProfile(device, samplingRate,
4156 &samplingRate /*updatedSamplingRate*/,
4157 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004158 return profile;
4159 }
4160 }
4161 }
4162 return NULL;
4163}
4164
Eric Laurente0720872014-03-11 09:30:41 -07004165audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004166{
4167 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004168 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4169 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004170 switch (inputSource) {
4171 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004173 device = AUDIO_DEVICE_IN_VOICE_CALL;
4174 break;
4175 }
4176 // FALL THROUGH
4177
4178 case AUDIO_SOURCE_DEFAULT:
4179 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004180 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4181 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4182 break;
4183 }
4184 // FALL THROUGH
4185
Eric Laurente552edb2014-03-10 17:42:56 -07004186 case AUDIO_SOURCE_VOICE_RECOGNITION:
4187 case AUDIO_SOURCE_HOTWORD:
4188 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004189 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004190 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004191 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004192 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004193 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004194 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4195 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004196 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004197 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4198 }
4199 break;
4200 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004201 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004202 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004203 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004204 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4205 }
4206 break;
4207 case AUDIO_SOURCE_VOICE_DOWNLINK:
4208 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004209 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004210 device = AUDIO_DEVICE_IN_VOICE_CALL;
4211 }
4212 break;
4213 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004214 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004215 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4216 }
4217 break;
4218 default:
4219 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4220 break;
4221 }
4222 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4223 return device;
4224}
4225
Eric Laurente0720872014-03-11 09:30:41 -07004226bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004227{
4228 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4229 device &= ~AUDIO_DEVICE_BIT_IN;
4230 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4231 return true;
4232 }
4233 return false;
4234}
4235
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004236bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4237 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4238}
4239
Eric Laurente0720872014-03-11 09:30:41 -07004240audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004241{
4242 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004243 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004244 if ((input_descriptor->mRefCount > 0)
4245 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4246 return mInputs.keyAt(i);
4247 }
4248 }
4249 return 0;
4250}
4251
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004252uint32_t AudioPolicyManager::activeInputsCount() const
4253{
4254 uint32_t count = 0;
4255 for (size_t i = 0; i < mInputs.size(); i++) {
4256 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4257 if (desc->mRefCount > 0) {
4258 return count++;
4259 }
4260 }
4261 return count;
4262}
4263
Eric Laurente552edb2014-03-10 17:42:56 -07004264
Eric Laurente0720872014-03-11 09:30:41 -07004265audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004266{
4267 if (device == AUDIO_DEVICE_NONE) {
4268 // this happens when forcing a route update and no track is active on an output.
4269 // In this case the returned category is not important.
4270 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004271 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004272 // Multiple device selection is either:
4273 // - speaker + one other device: give priority to speaker in this case.
4274 // - one A2DP device + another device: happens with duplicated output. In this case
4275 // retain the device on the A2DP output as the other must not correspond to an active
4276 // selection if not the speaker.
4277 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4278 device = AUDIO_DEVICE_OUT_SPEAKER;
4279 } else {
4280 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4281 }
4282 }
4283
Eric Laurent3b73df72014-03-11 09:06:29 -07004284 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004285 "getDeviceForVolume() invalid device combination: %08x",
4286 device);
4287
4288 return device;
4289}
4290
Eric Laurente0720872014-03-11 09:30:41 -07004291AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004292{
4293 switch(getDeviceForVolume(device)) {
4294 case AUDIO_DEVICE_OUT_EARPIECE:
4295 return DEVICE_CATEGORY_EARPIECE;
4296 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4297 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4298 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4299 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4300 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4301 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4302 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004303 case AUDIO_DEVICE_OUT_LINE:
4304 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4305 /*USB? Remote submix?*/
4306 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004307 case AUDIO_DEVICE_OUT_SPEAKER:
4308 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4309 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004310 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4311 case AUDIO_DEVICE_OUT_USB_DEVICE:
4312 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4313 default:
4314 return DEVICE_CATEGORY_SPEAKER;
4315 }
4316}
4317
Eric Laurente0720872014-03-11 09:30:41 -07004318float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004319 int indexInUi)
4320{
4321 device_category deviceCategory = getDeviceCategory(device);
4322 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4323
4324 // the volume index in the UI is relative to the min and max volume indices for this stream type
4325 int nbSteps = 1 + curve[VOLMAX].mIndex -
4326 curve[VOLMIN].mIndex;
4327 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4328 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4329
4330 // find what part of the curve this index volume belongs to, or if it's out of bounds
4331 int segment = 0;
4332 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4333 return 0.0f;
4334 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4335 segment = 0;
4336 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4337 segment = 1;
4338 } else if (volIdx <= curve[VOLMAX].mIndex) {
4339 segment = 2;
4340 } else { // out of bounds
4341 return 1.0f;
4342 }
4343
4344 // linear interpolation in the attenuation table in dB
4345 float decibels = curve[segment].mDBAttenuation +
4346 ((float)(volIdx - curve[segment].mIndex)) *
4347 ( (curve[segment+1].mDBAttenuation -
4348 curve[segment].mDBAttenuation) /
4349 ((float)(curve[segment+1].mIndex -
4350 curve[segment].mIndex)) );
4351
4352 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4353
4354 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4355 curve[segment].mIndex, volIdx,
4356 curve[segment+1].mIndex,
4357 curve[segment].mDBAttenuation,
4358 decibels,
4359 curve[segment+1].mDBAttenuation,
4360 amplification);
4361
4362 return amplification;
4363}
4364
Eric Laurente0720872014-03-11 09:30:41 -07004365const AudioPolicyManager::VolumeCurvePoint
4366 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004367 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4368};
4369
Eric Laurente0720872014-03-11 09:30:41 -07004370const AudioPolicyManager::VolumeCurvePoint
4371 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004372 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4373};
4374
Eric Laurente0720872014-03-11 09:30:41 -07004375const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004376 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4377 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4378};
4379
4380const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004381 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004382 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4383};
4384
Eric Laurente0720872014-03-11 09:30:41 -07004385const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004386 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004387 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004388};
4389
4390const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004391 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004392 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4393};
4394
Eric Laurente0720872014-03-11 09:30:41 -07004395const AudioPolicyManager::VolumeCurvePoint
4396 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004397 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4398};
4399
4400// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4401// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4402// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4403// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4404
Eric Laurente0720872014-03-11 09:30:41 -07004405const AudioPolicyManager::VolumeCurvePoint
4406 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004407 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4408};
4409
Eric Laurente0720872014-03-11 09:30:41 -07004410const AudioPolicyManager::VolumeCurvePoint
4411 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004412 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4413};
4414
Eric Laurente0720872014-03-11 09:30:41 -07004415const AudioPolicyManager::VolumeCurvePoint
4416 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004417 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4418};
4419
Eric Laurente0720872014-03-11 09:30:41 -07004420const AudioPolicyManager::VolumeCurvePoint
4421 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004422 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4423};
4424
Eric Laurente0720872014-03-11 09:30:41 -07004425const AudioPolicyManager::VolumeCurvePoint
4426 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004427 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4428};
4429
Eric Laurente0720872014-03-11 09:30:41 -07004430const AudioPolicyManager::VolumeCurvePoint
4431 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4432 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004433 { // AUDIO_STREAM_VOICE_CALL
4434 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4435 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004436 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4437 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004438 },
4439 { // AUDIO_STREAM_SYSTEM
4440 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4441 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004442 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4443 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004444 },
4445 { // AUDIO_STREAM_RING
4446 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4447 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004448 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4449 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004450 },
4451 { // AUDIO_STREAM_MUSIC
4452 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4453 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004454 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4455 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004456 },
4457 { // AUDIO_STREAM_ALARM
4458 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4459 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004460 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4461 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004462 },
4463 { // AUDIO_STREAM_NOTIFICATION
4464 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4465 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004466 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4467 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004468 },
4469 { // AUDIO_STREAM_BLUETOOTH_SCO
4470 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4471 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004472 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4473 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004474 },
4475 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4476 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4477 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004478 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4479 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004480 },
4481 { // AUDIO_STREAM_DTMF
4482 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4483 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004484 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4485 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004486 },
4487 { // AUDIO_STREAM_TTS
4488 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4489 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004490 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4491 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004492 },
4493};
4494
Eric Laurente0720872014-03-11 09:30:41 -07004495void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004496{
4497 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4498 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4499 mStreams[i].mVolumeCurve[j] =
4500 sVolumeProfiles[i][j];
4501 }
4502 }
4503
4504 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4505 if (mSpeakerDrcEnabled) {
4506 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4507 sDefaultSystemVolumeCurveDrc;
4508 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4509 sSpeakerSonificationVolumeCurveDrc;
4510 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4511 sSpeakerSonificationVolumeCurveDrc;
4512 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4513 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004514 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4515 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004516 }
4517}
4518
Eric Laurente0720872014-03-11 09:30:41 -07004519float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004520 int index,
4521 audio_io_handle_t output,
4522 audio_devices_t device)
4523{
4524 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004525 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004526 StreamDescriptor &streamDesc = mStreams[stream];
4527
4528 if (device == AUDIO_DEVICE_NONE) {
4529 device = outputDesc->device();
4530 }
4531
Eric Laurente552edb2014-03-10 17:42:56 -07004532 volume = volIndexToAmpl(device, streamDesc, index);
4533
4534 // if a headset is connected, apply the following rules to ring tones and notifications
4535 // to avoid sound level bursts in user's ears:
4536 // - always attenuate ring tones and notifications volume by 6dB
4537 // - if music is playing, always limit the volume to current music volume,
4538 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004539 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004540 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4541 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4542 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4543 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4544 ((stream_strategy == STRATEGY_SONIFICATION)
4545 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004546 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004547 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004548 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004549 streamDesc.mCanBeMuted) {
4550 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4551 // when the phone is ringing we must consider that music could have been paused just before
4552 // by the music application and behave as if music was active if the last music track was
4553 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004554 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004555 mLimitRingtoneVolume) {
4556 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004557 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4558 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004559 output,
4560 musicDevice);
4561 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4562 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4563 if (volume > minVol) {
4564 volume = minVol;
4565 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4566 }
4567 }
4568 }
4569
4570 return volume;
4571}
4572
Eric Laurente0720872014-03-11 09:30:41 -07004573status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004574 int index,
4575 audio_io_handle_t output,
4576 audio_devices_t device,
4577 int delayMs,
4578 bool force)
4579{
4580
4581 // do not change actual stream volume if the stream is muted
4582 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4583 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4584 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4585 return NO_ERROR;
4586 }
4587
4588 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004589 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4590 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4591 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4592 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004593 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004594 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004595 return INVALID_OPERATION;
4596 }
4597
4598 float volume = computeVolume(stream, index, output, device);
4599 // We actually change the volume if:
4600 // - the float value returned by computeVolume() changed
4601 // - the force flag is set
4602 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4603 force) {
4604 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4605 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4606 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4607 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004608 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4609 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004610 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004611 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004612 }
4613
Eric Laurent3b73df72014-03-11 09:06:29 -07004614 if (stream == AUDIO_STREAM_VOICE_CALL ||
4615 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004616 float voiceVolume;
4617 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004618 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004619 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4620 } else {
4621 voiceVolume = 1.0;
4622 }
4623
4624 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4625 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4626 mLastVoiceVolume = voiceVolume;
4627 }
4628 }
4629
4630 return NO_ERROR;
4631}
4632
Eric Laurente0720872014-03-11 09:30:41 -07004633void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004634 audio_devices_t device,
4635 int delayMs,
4636 bool force)
4637{
4638 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4639
Eric Laurent3b73df72014-03-11 09:06:29 -07004640 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4641 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004642 mStreams[stream].getVolumeIndex(device),
4643 output,
4644 device,
4645 delayMs,
4646 force);
4647 }
4648}
4649
Eric Laurente0720872014-03-11 09:30:41 -07004650void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004651 bool on,
4652 audio_io_handle_t output,
4653 int delayMs,
4654 audio_devices_t device)
4655{
4656 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004657 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4658 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4659 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004660 }
4661 }
4662}
4663
Eric Laurente0720872014-03-11 09:30:41 -07004664void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004665 bool on,
4666 audio_io_handle_t output,
4667 int delayMs,
4668 audio_devices_t device)
4669{
4670 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004671 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004672 if (device == AUDIO_DEVICE_NONE) {
4673 device = outputDesc->device();
4674 }
4675
4676 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4677 stream, on, output, outputDesc->mMuteCount[stream], device);
4678
4679 if (on) {
4680 if (outputDesc->mMuteCount[stream] == 0) {
4681 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004682 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4683 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004684 checkAndSetVolume(stream, 0, output, device, delayMs);
4685 }
4686 }
4687 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4688 outputDesc->mMuteCount[stream]++;
4689 } else {
4690 if (outputDesc->mMuteCount[stream] == 0) {
4691 ALOGV("setStreamMute() unmuting non muted stream!");
4692 return;
4693 }
4694 if (--outputDesc->mMuteCount[stream] == 0) {
4695 checkAndSetVolume(stream,
4696 streamDesc.getVolumeIndex(device),
4697 output,
4698 device,
4699 delayMs);
4700 }
4701 }
4702}
4703
Eric Laurente0720872014-03-11 09:30:41 -07004704void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004705 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004706{
4707 // if the stream pertains to sonification strategy and we are in call we must
4708 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4709 // in the device used for phone strategy and play the tone if the selected device does not
4710 // interfere with the device used for phone strategy
4711 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4712 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004713 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004714 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4715 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004716 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004717 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4718 stream, starting, outputDesc->mDevice, stateChange);
4719 if (outputDesc->mRefCount[stream]) {
4720 int muteCount = 1;
4721 if (stateChange) {
4722 muteCount = outputDesc->mRefCount[stream];
4723 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004724 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004725 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4726 for (int i = 0; i < muteCount; i++) {
4727 setStreamMute(stream, starting, mPrimaryOutput);
4728 }
4729 } else {
4730 ALOGV("handleIncallSonification() high visibility");
4731 if (outputDesc->device() &
4732 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4733 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4734 for (int i = 0; i < muteCount; i++) {
4735 setStreamMute(stream, starting, mPrimaryOutput);
4736 }
4737 }
4738 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004739 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4740 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004741 } else {
4742 mpClientInterface->stopTone();
4743 }
4744 }
4745 }
4746 }
4747}
4748
Eric Laurente0720872014-03-11 09:30:41 -07004749bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004750{
4751 return isStateInCall(mPhoneState);
4752}
4753
Eric Laurente0720872014-03-11 09:30:41 -07004754bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004755 return ((state == AUDIO_MODE_IN_CALL) ||
4756 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004757}
4758
Eric Laurente0720872014-03-11 09:30:41 -07004759uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004760{
4761 return MAX_EFFECTS_CPU_LOAD;
4762}
4763
Eric Laurente0720872014-03-11 09:30:41 -07004764uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004765{
4766 return MAX_EFFECTS_MEMORY;
4767}
4768
Eric Laurent6a94d692014-05-20 11:18:06 -07004769
Eric Laurente552edb2014-03-10 17:42:56 -07004770// --- AudioOutputDescriptor class implementation
4771
Eric Laurente0720872014-03-11 09:30:41 -07004772AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004773 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004774 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004775 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004776 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4777{
4778 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004779 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004780 mRefCount[i] = 0;
4781 mCurVolume[i] = -1.0;
4782 mMuteCount[i] = 0;
4783 mStopTime[i] = 0;
4784 }
4785 for (int i = 0; i < NUM_STRATEGIES; i++) {
4786 mStrategyMutedByDevice[i] = false;
4787 }
4788 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004789 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004790 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004791 mSamplingRate = profile->pickSamplingRate();
4792 mFormat = profile->pickFormat();
4793 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004794 if (profile->mGains.size() > 0) {
4795 profile->mGains[0]->getDefaultConfig(&mGain);
4796 }
Eric Laurente552edb2014-03-10 17:42:56 -07004797 }
4798}
4799
Eric Laurente0720872014-03-11 09:30:41 -07004800audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004801{
4802 if (isDuplicated()) {
4803 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4804 } else {
4805 return mDevice;
4806 }
4807}
4808
Eric Laurente0720872014-03-11 09:30:41 -07004809uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004810{
4811 if (isDuplicated()) {
4812 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4813 } else {
4814 return mLatency;
4815 }
4816}
4817
Eric Laurente0720872014-03-11 09:30:41 -07004818bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004819 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004820{
4821 if (isDuplicated()) {
4822 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4823 } else if (outputDesc->isDuplicated()){
4824 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4825 } else {
4826 return (mProfile->mModule == outputDesc->mProfile->mModule);
4827 }
4828}
4829
Eric Laurente0720872014-03-11 09:30:41 -07004830void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004831 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004832{
4833 // forward usage count change to attached outputs
4834 if (isDuplicated()) {
4835 mOutput1->changeRefCount(stream, delta);
4836 mOutput2->changeRefCount(stream, delta);
4837 }
4838 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004839 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4840 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004841 mRefCount[stream] = 0;
4842 return;
4843 }
4844 mRefCount[stream] += delta;
4845 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4846}
4847
Eric Laurente0720872014-03-11 09:30:41 -07004848audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004849{
4850 if (isDuplicated()) {
4851 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4852 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004853 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004854 }
4855}
4856
Eric Laurente0720872014-03-11 09:30:41 -07004857bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004858{
4859 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4860}
4861
Eric Laurente0720872014-03-11 09:30:41 -07004862bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004863 uint32_t inPastMs,
4864 nsecs_t sysTime) const
4865{
4866 if ((sysTime == 0) && (inPastMs != 0)) {
4867 sysTime = systemTime();
4868 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004869 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4870 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004871 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004872 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004873 return true;
4874 }
4875 }
4876 return false;
4877}
4878
Eric Laurente0720872014-03-11 09:30:41 -07004879bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004880 uint32_t inPastMs,
4881 nsecs_t sysTime) const
4882{
4883 if (mRefCount[stream] != 0) {
4884 return true;
4885 }
4886 if (inPastMs == 0) {
4887 return false;
4888 }
4889 if (sysTime == 0) {
4890 sysTime = systemTime();
4891 }
4892 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4893 return true;
4894 }
4895 return false;
4896}
4897
Eric Laurent1c333e22014-05-20 10:48:17 -07004898void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 struct audio_port_config *dstConfig,
4900 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004901{
Eric Laurent84c70242014-06-23 08:46:27 -07004902 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4903
Eric Laurent1f2f2232014-06-02 12:01:23 -07004904 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4905 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4906 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004907 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004908 }
4909 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4910
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 dstConfig->id = mId;
4912 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4913 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4915 dstConfig->ext.mix.handle = mIoHandle;
4916 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004917}
4918
4919void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4920 struct audio_port *port) const
4921{
Eric Laurent84c70242014-06-23 08:46:27 -07004922 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004923 mProfile->toAudioPort(port);
4924 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 toAudioPortConfig(&port->active_config);
4926 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004927 port->ext.mix.handle = mIoHandle;
4928 port->ext.mix.latency_class =
4929 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4930}
Eric Laurente552edb2014-03-10 17:42:56 -07004931
Eric Laurente0720872014-03-11 09:30:41 -07004932status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004933{
4934 const size_t SIZE = 256;
4935 char buffer[SIZE];
4936 String8 result;
4937
4938 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4939 result.append(buffer);
4940 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4941 result.append(buffer);
4942 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4943 result.append(buffer);
4944 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4945 result.append(buffer);
4946 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4947 result.append(buffer);
4948 snprintf(buffer, SIZE, " Devices %08x\n", device());
4949 result.append(buffer);
4950 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4951 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004952 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4953 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4954 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004955 result.append(buffer);
4956 }
4957 write(fd, result.string(), result.size());
4958
4959 return NO_ERROR;
4960}
4961
4962// --- AudioInputDescriptor class implementation
4963
Eric Laurent1c333e22014-05-20 10:48:17 -07004964AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004965 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004966 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004967 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004968{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004969 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004970 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004971 mSamplingRate = profile->pickSamplingRate();
4972 mFormat = profile->pickFormat();
4973 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004974 if (profile->mGains.size() > 0) {
4975 profile->mGains[0]->getDefaultConfig(&mGain);
4976 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004977 }
Eric Laurente552edb2014-03-10 17:42:56 -07004978}
4979
Eric Laurent1c333e22014-05-20 10:48:17 -07004980void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004981 struct audio_port_config *dstConfig,
4982 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004983{
Eric Laurent84c70242014-06-23 08:46:27 -07004984 ALOG_ASSERT(mProfile != 0,
4985 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004986 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4987 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4988 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004989 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004990 }
4991
4992 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4993
Eric Laurent6a94d692014-05-20 11:18:06 -07004994 dstConfig->id = mId;
4995 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4996 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004997 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4998 dstConfig->ext.mix.handle = mIoHandle;
4999 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005000}
5001
5002void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5003 struct audio_port *port) const
5004{
Eric Laurent84c70242014-06-23 08:46:27 -07005005 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5006
Eric Laurent1c333e22014-05-20 10:48:17 -07005007 mProfile->toAudioPort(port);
5008 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 toAudioPortConfig(&port->active_config);
5010 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005011 port->ext.mix.handle = mIoHandle;
5012 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5013}
5014
Eric Laurente0720872014-03-11 09:30:41 -07005015status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005016{
5017 const size_t SIZE = 256;
5018 char buffer[SIZE];
5019 String8 result;
5020
5021 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5022 result.append(buffer);
5023 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5024 result.append(buffer);
5025 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5026 result.append(buffer);
5027 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5028 result.append(buffer);
5029 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5030 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005031 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5032 result.append(buffer);
5033
Eric Laurente552edb2014-03-10 17:42:56 -07005034 write(fd, result.string(), result.size());
5035
5036 return NO_ERROR;
5037}
5038
5039// --- StreamDescriptor class implementation
5040
Eric Laurente0720872014-03-11 09:30:41 -07005041AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005042 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5043{
5044 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5045}
5046
Eric Laurente0720872014-03-11 09:30:41 -07005047int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005048{
Eric Laurente0720872014-03-11 09:30:41 -07005049 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005050 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5051 if (mIndexCur.indexOfKey(device) < 0) {
5052 device = AUDIO_DEVICE_OUT_DEFAULT;
5053 }
5054 return mIndexCur.valueFor(device);
5055}
5056
Eric Laurente0720872014-03-11 09:30:41 -07005057void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005058{
5059 const size_t SIZE = 256;
5060 char buffer[SIZE];
5061 String8 result;
5062
5063 snprintf(buffer, SIZE, "%s %02d %02d ",
5064 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5065 result.append(buffer);
5066 for (size_t i = 0; i < mIndexCur.size(); i++) {
5067 snprintf(buffer, SIZE, "%04x : %02d, ",
5068 mIndexCur.keyAt(i),
5069 mIndexCur.valueAt(i));
5070 result.append(buffer);
5071 }
5072 result.append("\n");
5073
5074 write(fd, result.string(), result.size());
5075}
5076
5077// --- EffectDescriptor class implementation
5078
Eric Laurente0720872014-03-11 09:30:41 -07005079status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005080{
5081 const size_t SIZE = 256;
5082 char buffer[SIZE];
5083 String8 result;
5084
5085 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5086 result.append(buffer);
5087 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5088 result.append(buffer);
5089 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5090 result.append(buffer);
5091 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5092 result.append(buffer);
5093 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5094 result.append(buffer);
5095 write(fd, result.string(), result.size());
5096
5097 return NO_ERROR;
5098}
5099
Eric Laurent1c333e22014-05-20 10:48:17 -07005100// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005101
Eric Laurente0720872014-03-11 09:30:41 -07005102AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005103 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5104 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005105{
5106}
5107
Eric Laurente0720872014-03-11 09:30:41 -07005108AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005109{
5110 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005111 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005112 }
5113 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005114 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005115 }
5116 free((void *)mName);
5117}
5118
Eric Laurent1afeecb2014-05-14 08:52:28 -07005119status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5120{
5121 cnode *node = root->first_child;
5122
5123 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5124
5125 while (node) {
5126 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5127 profile->loadSamplingRates((char *)node->value);
5128 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5129 profile->loadFormats((char *)node->value);
5130 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5131 profile->loadInChannels((char *)node->value);
5132 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5133 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5134 mDeclaredDevices);
5135 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5136 profile->loadGains(node);
5137 }
5138 node = node->next;
5139 }
5140 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5141 "loadInput() invalid supported devices");
5142 ALOGW_IF(profile->mChannelMasks.size() == 0,
5143 "loadInput() invalid supported channel masks");
5144 ALOGW_IF(profile->mSamplingRates.size() == 0,
5145 "loadInput() invalid supported sampling rates");
5146 ALOGW_IF(profile->mFormats.size() == 0,
5147 "loadInput() invalid supported formats");
5148 if (!profile->mSupportedDevices.isEmpty() &&
5149 (profile->mChannelMasks.size() != 0) &&
5150 (profile->mSamplingRates.size() != 0) &&
5151 (profile->mFormats.size() != 0)) {
5152
5153 ALOGV("loadInput() adding input Supported Devices %04x",
5154 profile->mSupportedDevices.types());
5155
5156 mInputProfiles.add(profile);
5157 return NO_ERROR;
5158 } else {
5159 return BAD_VALUE;
5160 }
5161}
5162
5163status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5164{
5165 cnode *node = root->first_child;
5166
5167 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5168
5169 while (node) {
5170 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5171 profile->loadSamplingRates((char *)node->value);
5172 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5173 profile->loadFormats((char *)node->value);
5174 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5175 profile->loadOutChannels((char *)node->value);
5176 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5177 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5178 mDeclaredDevices);
5179 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5180 profile->mFlags = parseFlagNames((char *)node->value);
5181 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5182 profile->loadGains(node);
5183 }
5184 node = node->next;
5185 }
5186 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5187 "loadOutput() invalid supported devices");
5188 ALOGW_IF(profile->mChannelMasks.size() == 0,
5189 "loadOutput() invalid supported channel masks");
5190 ALOGW_IF(profile->mSamplingRates.size() == 0,
5191 "loadOutput() invalid supported sampling rates");
5192 ALOGW_IF(profile->mFormats.size() == 0,
5193 "loadOutput() invalid supported formats");
5194 if (!profile->mSupportedDevices.isEmpty() &&
5195 (profile->mChannelMasks.size() != 0) &&
5196 (profile->mSamplingRates.size() != 0) &&
5197 (profile->mFormats.size() != 0)) {
5198
5199 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5200 profile->mSupportedDevices.types(), profile->mFlags);
5201
5202 mOutputProfiles.add(profile);
5203 return NO_ERROR;
5204 } else {
5205 return BAD_VALUE;
5206 }
5207}
5208
5209status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5210{
5211 cnode *node = root->first_child;
5212
5213 audio_devices_t type = AUDIO_DEVICE_NONE;
5214 while (node) {
5215 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5216 type = parseDeviceNames((char *)node->value);
5217 break;
5218 }
5219 node = node->next;
5220 }
5221 if (type == AUDIO_DEVICE_NONE ||
5222 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5223 ALOGW("loadDevice() bad type %08x", type);
5224 return BAD_VALUE;
5225 }
5226 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5227 deviceDesc->mModule = this;
5228
5229 node = root->first_child;
5230 while (node) {
5231 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5232 deviceDesc->mAddress = String8((char *)node->value);
5233 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5234 if (audio_is_input_device(type)) {
5235 deviceDesc->loadInChannels((char *)node->value);
5236 } else {
5237 deviceDesc->loadOutChannels((char *)node->value);
5238 }
5239 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5240 deviceDesc->loadGains(node);
5241 }
5242 node = node->next;
5243 }
5244
5245 ALOGV("loadDevice() adding device name %s type %08x address %s",
5246 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5247
5248 mDeclaredDevices.add(deviceDesc);
5249
5250 return NO_ERROR;
5251}
5252
Eric Laurente0720872014-03-11 09:30:41 -07005253void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005254{
5255 const size_t SIZE = 256;
5256 char buffer[SIZE];
5257 String8 result;
5258
5259 snprintf(buffer, SIZE, " - name: %s\n", mName);
5260 result.append(buffer);
5261 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5262 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005263 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5264 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005265 write(fd, result.string(), result.size());
5266 if (mOutputProfiles.size()) {
5267 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5268 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005269 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005270 write(fd, buffer, strlen(buffer));
5271 mOutputProfiles[i]->dump(fd);
5272 }
5273 }
5274 if (mInputProfiles.size()) {
5275 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5276 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005277 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005278 write(fd, buffer, strlen(buffer));
5279 mInputProfiles[i]->dump(fd);
5280 }
5281 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005282 if (mDeclaredDevices.size()) {
5283 write(fd, " - devices:\n", strlen(" - devices:\n"));
5284 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5285 mDeclaredDevices[i]->dump(fd, 4, i);
5286 }
5287 }
Eric Laurente552edb2014-03-10 17:42:56 -07005288}
5289
Eric Laurent1c333e22014-05-20 10:48:17 -07005290// --- AudioPort class implementation
5291
Eric Laurenta121f902014-06-03 13:32:54 -07005292
5293AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5294 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005295 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005296{
5297 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5298 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5299}
5300
Eric Laurent1c333e22014-05-20 10:48:17 -07005301void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5302{
5303 port->role = mRole;
5304 port->type = mType;
5305 unsigned int i;
5306 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5307 port->sample_rates[i] = mSamplingRates[i];
5308 }
5309 port->num_sample_rates = i;
5310 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5311 port->channel_masks[i] = mChannelMasks[i];
5312 }
5313 port->num_channel_masks = i;
5314 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5315 port->formats[i] = mFormats[i];
5316 }
5317 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005318
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005319 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005320
5321 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5322 port->gains[i] = mGains[i]->mGain;
5323 }
5324 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005325}
5326
5327
5328void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5329{
5330 char *str = strtok(name, "|");
5331
5332 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5333 // rates should be read from the output stream after it is opened for the first time
5334 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5335 mSamplingRates.add(0);
5336 return;
5337 }
5338
5339 while (str != NULL) {
5340 uint32_t rate = atoi(str);
5341 if (rate != 0) {
5342 ALOGV("loadSamplingRates() adding rate %d", rate);
5343 mSamplingRates.add(rate);
5344 }
5345 str = strtok(NULL, "|");
5346 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005347}
5348
5349void AudioPolicyManager::AudioPort::loadFormats(char *name)
5350{
5351 char *str = strtok(name, "|");
5352
5353 // by convention, "0' in the first entry in mFormats indicates the supported formats
5354 // should be read from the output stream after it is opened for the first time
5355 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5356 mFormats.add(AUDIO_FORMAT_DEFAULT);
5357 return;
5358 }
5359
5360 while (str != NULL) {
5361 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5362 ARRAY_SIZE(sFormatNameToEnumTable),
5363 str);
5364 if (format != AUDIO_FORMAT_DEFAULT) {
5365 mFormats.add(format);
5366 }
5367 str = strtok(NULL, "|");
5368 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005369}
5370
5371void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5372{
5373 const char *str = strtok(name, "|");
5374
5375 ALOGV("loadInChannels() %s", name);
5376
5377 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5378 mChannelMasks.add(0);
5379 return;
5380 }
5381
5382 while (str != NULL) {
5383 audio_channel_mask_t channelMask =
5384 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5385 ARRAY_SIZE(sInChannelsNameToEnumTable),
5386 str);
5387 if (channelMask != 0) {
5388 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5389 mChannelMasks.add(channelMask);
5390 }
5391 str = strtok(NULL, "|");
5392 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005393}
5394
5395void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5396{
5397 const char *str = strtok(name, "|");
5398
5399 ALOGV("loadOutChannels() %s", name);
5400
5401 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5402 // masks should be read from the output stream after it is opened for the first time
5403 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5404 mChannelMasks.add(0);
5405 return;
5406 }
5407
5408 while (str != NULL) {
5409 audio_channel_mask_t channelMask =
5410 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5411 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5412 str);
5413 if (channelMask != 0) {
5414 mChannelMasks.add(channelMask);
5415 }
5416 str = strtok(NULL, "|");
5417 }
5418 return;
5419}
5420
Eric Laurent1afeecb2014-05-14 08:52:28 -07005421audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5422{
5423 const char *str = strtok(name, "|");
5424
5425 ALOGV("loadGainMode() %s", name);
5426 audio_gain_mode_t mode = 0;
5427 while (str != NULL) {
5428 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5429 ARRAY_SIZE(sGainModeNameToEnumTable),
5430 str);
5431 str = strtok(NULL, "|");
5432 }
5433 return mode;
5434}
5435
Eric Laurenta121f902014-06-03 13:32:54 -07005436void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005437{
5438 cnode *node = root->first_child;
5439
Eric Laurenta121f902014-06-03 13:32:54 -07005440 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005441
5442 while (node) {
5443 if (strcmp(node->name, GAIN_MODE) == 0) {
5444 gain->mGain.mode = loadGainMode((char *)node->value);
5445 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005446 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005447 gain->mGain.channel_mask =
5448 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5449 ARRAY_SIZE(sInChannelsNameToEnumTable),
5450 (char *)node->value);
5451 } else {
5452 gain->mGain.channel_mask =
5453 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5454 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5455 (char *)node->value);
5456 }
5457 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5458 gain->mGain.min_value = atoi((char *)node->value);
5459 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5460 gain->mGain.max_value = atoi((char *)node->value);
5461 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5462 gain->mGain.default_value = atoi((char *)node->value);
5463 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5464 gain->mGain.step_value = atoi((char *)node->value);
5465 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5466 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5467 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5468 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5469 }
5470 node = node->next;
5471 }
5472
5473 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5474 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5475
5476 if (gain->mGain.mode == 0) {
5477 return;
5478 }
5479 mGains.add(gain);
5480}
5481
5482void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5483{
5484 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005485 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005486 while (node) {
5487 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005488 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005489 node = node->next;
5490 }
5491}
5492
Glenn Kastencbd48022014-07-24 13:46:44 -07005493status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005494{
5495 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5496 if (mSamplingRates[i] == samplingRate) {
5497 return NO_ERROR;
5498 }
5499 }
5500 return BAD_VALUE;
5501}
5502
Glenn Kastencbd48022014-07-24 13:46:44 -07005503status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5504 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005505{
Glenn Kastencbd48022014-07-24 13:46:44 -07005506 // Search for the closest supported sampling rate that is above (preferred)
5507 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5508 // The sampling rates do not need to be sorted in ascending order.
5509 ssize_t maxBelow = -1;
5510 ssize_t minAbove = -1;
5511 uint32_t candidate;
5512 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5513 candidate = mSamplingRates[i];
5514 if (candidate == samplingRate) {
5515 if (updatedSamplingRate != NULL) {
5516 *updatedSamplingRate = candidate;
5517 }
5518 return NO_ERROR;
5519 }
5520 // candidate < desired
5521 if (candidate < samplingRate) {
5522 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5523 maxBelow = i;
5524 }
5525 // candidate > desired
5526 } else {
5527 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5528 minAbove = i;
5529 }
5530 }
5531 }
5532 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5533 // TODO Move these assumptions out.
5534 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5535 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5536 // due to approximation by an int32_t of the
5537 // phase increments
5538 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5539 if (minAbove >= 0) {
5540 candidate = mSamplingRates[minAbove];
5541 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5542 if (updatedSamplingRate != NULL) {
5543 *updatedSamplingRate = candidate;
5544 }
5545 return NO_ERROR;
5546 }
5547 }
5548 // But if we have to up-sample from a lower sampling rate, that's OK.
5549 if (maxBelow >= 0) {
5550 candidate = mSamplingRates[maxBelow];
5551 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5552 if (updatedSamplingRate != NULL) {
5553 *updatedSamplingRate = candidate;
5554 }
5555 return NO_ERROR;
5556 }
5557 }
5558 // leave updatedSamplingRate unmodified
5559 return BAD_VALUE;
5560}
5561
5562status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5563{
5564 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005565 if (mChannelMasks[i] == channelMask) {
5566 return NO_ERROR;
5567 }
5568 }
5569 return BAD_VALUE;
5570}
5571
Glenn Kastencbd48022014-07-24 13:46:44 -07005572status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5573 const
5574{
5575 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5576 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5577 // FIXME Does not handle multi-channel automatic conversions yet
5578 audio_channel_mask_t supported = mChannelMasks[i];
5579 if (supported == channelMask) {
5580 return NO_ERROR;
5581 }
5582 if (isRecordThread) {
5583 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5584 // FIXME Abstract this out to a table.
5585 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5586 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5587 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5588 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5589 return NO_ERROR;
5590 }
5591 }
5592 }
5593 return BAD_VALUE;
5594}
5595
Eric Laurenta121f902014-06-03 13:32:54 -07005596status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5597{
5598 for (size_t i = 0; i < mFormats.size(); i ++) {
5599 if (mFormats[i] == format) {
5600 return NO_ERROR;
5601 }
5602 }
5603 return BAD_VALUE;
5604}
5605
Eric Laurent1e693b52014-07-09 15:03:28 -07005606
5607uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5608{
5609 // special case for uninitialized dynamic profile
5610 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5611 return 0;
5612 }
5613
5614 uint32_t samplingRate = 0;
5615 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5616
5617 // For mixed output and inputs, use max mixer sampling rates. Do not
5618 // limit sampling rate otherwise
5619 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5620 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5621 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5622 maxRate = UINT_MAX;
5623 }
5624 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5625 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5626 samplingRate = mSamplingRates[i];
5627 }
5628 }
5629 return samplingRate;
5630}
5631
5632audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5633{
5634 // special case for uninitialized dynamic profile
5635 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5636 return AUDIO_CHANNEL_NONE;
5637 }
5638
5639 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5640 uint32_t channelCount = 0;
5641 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5642
5643 // For mixed output and inputs, use max mixer channel count. Do not
5644 // limit channel count otherwise
5645 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5646 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5647 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5648 maxCount = UINT_MAX;
5649 }
5650 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5651 uint32_t cnlCount;
5652 if (mUseInChannelMask) {
5653 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5654 } else {
5655 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5656 }
5657 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5658 channelMask = mChannelMasks[i];
5659 }
5660 }
5661 return channelMask;
5662}
5663
Andy Hung9a605382014-07-28 16:16:31 -07005664/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005665const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5666 AUDIO_FORMAT_DEFAULT,
5667 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005668 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005669 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005670 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005671 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005672};
5673
5674int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5675 audio_format_t format2)
5676{
5677 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5678 // compressed format and better than any PCM format. This is by design of pickFormat()
5679 if (!audio_is_linear_pcm(format1)) {
5680 if (!audio_is_linear_pcm(format2)) {
5681 return 0;
5682 }
5683 return 1;
5684 }
5685 if (!audio_is_linear_pcm(format2)) {
5686 return -1;
5687 }
5688
5689 int index1 = -1, index2 = -1;
5690 for (size_t i = 0;
5691 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5692 i ++) {
5693 if (sPcmFormatCompareTable[i] == format1) {
5694 index1 = i;
5695 }
5696 if (sPcmFormatCompareTable[i] == format2) {
5697 index2 = i;
5698 }
5699 }
5700 // format1 not found => index1 < 0 => format2 > format1
5701 // format2 not found => index2 < 0 => format2 < format1
5702 return index1 - index2;
5703}
5704
5705audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5706{
5707 // special case for uninitialized dynamic profile
5708 if (mFormats.size() == 1 && mFormats[0] == 0) {
5709 return AUDIO_FORMAT_DEFAULT;
5710 }
5711
5712 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005713 audio_format_t bestFormat =
5714 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5715 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005716 // For mixed output and inputs, use best mixer output format. Do not
5717 // limit format otherwise
5718 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5719 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005720 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005721 bestFormat = AUDIO_FORMAT_INVALID;
5722 }
5723
5724 for (size_t i = 0; i < mFormats.size(); i ++) {
5725 if ((compareFormats(mFormats[i], format) > 0) &&
5726 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5727 format = mFormats[i];
5728 }
5729 }
5730 return format;
5731}
5732
Eric Laurenta121f902014-06-03 13:32:54 -07005733status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5734 int index) const
5735{
5736 if (index < 0 || (size_t)index >= mGains.size()) {
5737 return BAD_VALUE;
5738 }
5739 return mGains[index]->checkConfig(gainConfig);
5740}
5741
Eric Laurent1afeecb2014-05-14 08:52:28 -07005742void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5743{
5744 const size_t SIZE = 256;
5745 char buffer[SIZE];
5746 String8 result;
5747
5748 if (mName.size() != 0) {
5749 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5750 result.append(buffer);
5751 }
5752
5753 if (mSamplingRates.size() != 0) {
5754 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5755 result.append(buffer);
5756 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005757 if (i == 0 && mSamplingRates[i] == 0) {
5758 snprintf(buffer, SIZE, "Dynamic");
5759 } else {
5760 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5761 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005762 result.append(buffer);
5763 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5764 }
5765 result.append("\n");
5766 }
5767
5768 if (mChannelMasks.size() != 0) {
5769 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5770 result.append(buffer);
5771 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005772 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5773
5774 if (i == 0 && mChannelMasks[i] == 0) {
5775 snprintf(buffer, SIZE, "Dynamic");
5776 } else {
5777 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5778 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005779 result.append(buffer);
5780 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5781 }
5782 result.append("\n");
5783 }
5784
5785 if (mFormats.size() != 0) {
5786 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5787 result.append(buffer);
5788 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005789 const char *formatStr = enumToString(sFormatNameToEnumTable,
5790 ARRAY_SIZE(sFormatNameToEnumTable),
5791 mFormats[i]);
5792 if (i == 0 && strcmp(formatStr, "") == 0) {
5793 snprintf(buffer, SIZE, "Dynamic");
5794 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005795 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07005796 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005797 result.append(buffer);
5798 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5799 }
5800 result.append("\n");
5801 }
5802 write(fd, result.string(), result.size());
5803 if (mGains.size() != 0) {
5804 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5805 write(fd, buffer, strlen(buffer) + 1);
5806 result.append(buffer);
5807 for (size_t i = 0; i < mGains.size(); i++) {
5808 mGains[i]->dump(fd, spaces + 2, i);
5809 }
5810 }
5811}
5812
5813// --- AudioGain class implementation
5814
Eric Laurenta121f902014-06-03 13:32:54 -07005815AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005816{
Eric Laurenta121f902014-06-03 13:32:54 -07005817 mIndex = index;
5818 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005819 memset(&mGain, 0, sizeof(struct audio_gain));
5820}
5821
Eric Laurenta121f902014-06-03 13:32:54 -07005822void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5823{
5824 config->index = mIndex;
5825 config->mode = mGain.mode;
5826 config->channel_mask = mGain.channel_mask;
5827 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5828 config->values[0] = mGain.default_value;
5829 } else {
5830 uint32_t numValues;
5831 if (mUseInChannelMask) {
5832 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5833 } else {
5834 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5835 }
5836 for (size_t i = 0; i < numValues; i++) {
5837 config->values[i] = mGain.default_value;
5838 }
5839 }
5840 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5841 config->ramp_duration_ms = mGain.min_ramp_ms;
5842 }
5843}
5844
5845status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5846{
5847 if ((config->mode & ~mGain.mode) != 0) {
5848 return BAD_VALUE;
5849 }
5850 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5851 if ((config->values[0] < mGain.min_value) ||
5852 (config->values[0] > mGain.max_value)) {
5853 return BAD_VALUE;
5854 }
5855 } else {
5856 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5857 return BAD_VALUE;
5858 }
5859 uint32_t numValues;
5860 if (mUseInChannelMask) {
5861 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5862 } else {
5863 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5864 }
5865 for (size_t i = 0; i < numValues; i++) {
5866 if ((config->values[i] < mGain.min_value) ||
5867 (config->values[i] > mGain.max_value)) {
5868 return BAD_VALUE;
5869 }
5870 }
5871 }
5872 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5873 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5874 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5875 return BAD_VALUE;
5876 }
5877 }
5878 return NO_ERROR;
5879}
5880
Eric Laurent1afeecb2014-05-14 08:52:28 -07005881void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5882{
5883 const size_t SIZE = 256;
5884 char buffer[SIZE];
5885 String8 result;
5886
5887 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5888 result.append(buffer);
5889 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5890 result.append(buffer);
5891 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5892 result.append(buffer);
5893 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5894 result.append(buffer);
5895 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5896 result.append(buffer);
5897 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5898 result.append(buffer);
5899 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5900 result.append(buffer);
5901 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5902 result.append(buffer);
5903 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5904 result.append(buffer);
5905
5906 write(fd, result.string(), result.size());
5907}
5908
Eric Laurent1f2f2232014-06-02 12:01:23 -07005909// --- AudioPortConfig class implementation
5910
5911AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5912{
5913 mSamplingRate = 0;
5914 mChannelMask = AUDIO_CHANNEL_NONE;
5915 mFormat = AUDIO_FORMAT_INVALID;
5916 mGain.index = -1;
5917}
5918
Eric Laurenta121f902014-06-03 13:32:54 -07005919status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5920 const struct audio_port_config *config,
5921 struct audio_port_config *backupConfig)
5922{
5923 struct audio_port_config localBackupConfig;
5924 status_t status = NO_ERROR;
5925
5926 localBackupConfig.config_mask = config->config_mask;
5927 toAudioPortConfig(&localBackupConfig);
5928
5929 if (mAudioPort == 0) {
5930 status = NO_INIT;
5931 goto exit;
5932 }
5933 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005934 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005935 if (status != NO_ERROR) {
5936 goto exit;
5937 }
5938 mSamplingRate = config->sample_rate;
5939 }
5940 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005941 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005942 if (status != NO_ERROR) {
5943 goto exit;
5944 }
5945 mChannelMask = config->channel_mask;
5946 }
5947 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5948 status = mAudioPort->checkFormat(config->format);
5949 if (status != NO_ERROR) {
5950 goto exit;
5951 }
5952 mFormat = config->format;
5953 }
5954 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5955 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5956 if (status != NO_ERROR) {
5957 goto exit;
5958 }
5959 mGain = config->gain;
5960 }
5961
5962exit:
5963 if (status != NO_ERROR) {
5964 applyAudioPortConfig(&localBackupConfig);
5965 }
5966 if (backupConfig != NULL) {
5967 *backupConfig = localBackupConfig;
5968 }
5969 return status;
5970}
5971
Eric Laurent1f2f2232014-06-02 12:01:23 -07005972void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5973 struct audio_port_config *dstConfig,
5974 const struct audio_port_config *srcConfig) const
5975{
5976 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5977 dstConfig->sample_rate = mSamplingRate;
5978 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5979 dstConfig->sample_rate = srcConfig->sample_rate;
5980 }
5981 } else {
5982 dstConfig->sample_rate = 0;
5983 }
5984 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5985 dstConfig->channel_mask = mChannelMask;
5986 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5987 dstConfig->channel_mask = srcConfig->channel_mask;
5988 }
5989 } else {
5990 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5991 }
5992 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5993 dstConfig->format = mFormat;
5994 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5995 dstConfig->format = srcConfig->format;
5996 }
5997 } else {
5998 dstConfig->format = AUDIO_FORMAT_INVALID;
5999 }
6000 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6001 dstConfig->gain = mGain;
6002 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6003 dstConfig->gain = srcConfig->gain;
6004 }
6005 } else {
6006 dstConfig->gain.index = -1;
6007 }
6008 if (dstConfig->gain.index != -1) {
6009 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6010 } else {
6011 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6012 }
6013}
6014
Eric Laurent1c333e22014-05-20 10:48:17 -07006015// --- IOProfile class implementation
6016
Eric Laurent1afeecb2014-05-14 08:52:28 -07006017AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006018 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006019 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006020{
6021}
6022
Eric Laurente0720872014-03-11 09:30:41 -07006023AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006024{
6025}
6026
6027// checks if the IO profile is compatible with specified parameters.
6028// Sampling rate, format and channel mask must be specified in order to
6029// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006030bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006031 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006032 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006033 audio_format_t format,
6034 audio_channel_mask_t channelMask,
6035 audio_output_flags_t flags) const
6036{
Glenn Kastencbd48022014-07-24 13:46:44 -07006037 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6038 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6039 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006040
Glenn Kastencbd48022014-07-24 13:46:44 -07006041 if ((mSupportedDevices.types() & device) != device) {
6042 return false;
6043 }
6044
6045 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006046 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006047 }
6048 uint32_t myUpdatedSamplingRate = samplingRate;
6049 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006050 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006051 }
6052 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6053 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006054 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006055 }
6056
6057 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6058 return false;
6059 }
6060
6061 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6062 checkExactChannelMask(channelMask) != NO_ERROR)) {
6063 return false;
6064 }
6065 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6066 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6067 return false;
6068 }
6069
6070 if (isPlaybackThread && (mFlags & flags) != flags) {
6071 return false;
6072 }
6073 // The only input flag that is allowed to be different is the fast flag.
6074 // An existing fast stream is compatible with a normal track request.
6075 // An existing normal stream is compatible with a fast track request,
6076 // but the fast request will be denied by AudioFlinger and converted to normal track.
6077 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6078 ~AUDIO_INPUT_FLAG_FAST)) {
6079 return false;
6080 }
6081
6082 if (updatedSamplingRate != NULL) {
6083 *updatedSamplingRate = myUpdatedSamplingRate;
6084 }
6085 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006086}
6087
Eric Laurente0720872014-03-11 09:30:41 -07006088void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006089{
6090 const size_t SIZE = 256;
6091 char buffer[SIZE];
6092 String8 result;
6093
Eric Laurent1afeecb2014-05-14 08:52:28 -07006094 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006095
Eric Laurente552edb2014-03-10 17:42:56 -07006096 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6097 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006098 snprintf(buffer, SIZE, " - devices:\n");
6099 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006100 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006101 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6102 mSupportedDevices[i]->dump(fd, 6, i);
6103 }
Eric Laurente552edb2014-03-10 17:42:56 -07006104}
6105
Eric Laurentd4692962014-05-05 18:13:44 -07006106void AudioPolicyManager::IOProfile::log()
6107{
6108 const size_t SIZE = 256;
6109 char buffer[SIZE];
6110 String8 result;
6111
6112 ALOGV(" - sampling rates: ");
6113 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6114 ALOGV(" %d", mSamplingRates[i]);
6115 }
6116
6117 ALOGV(" - channel masks: ");
6118 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6119 ALOGV(" 0x%04x", mChannelMasks[i]);
6120 }
6121
6122 ALOGV(" - formats: ");
6123 for (size_t i = 0; i < mFormats.size(); i++) {
6124 ALOGV(" 0x%08x", mFormats[i]);
6125 }
6126
6127 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6128 ALOGV(" - flags: 0x%04x\n", mFlags);
6129}
6130
6131
Eric Laurent3a4311c2014-03-17 12:00:47 -07006132// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006133
Eric Laurent1f2f2232014-06-02 12:01:23 -07006134
6135AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6136 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6137 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6138 AUDIO_PORT_ROLE_SOURCE,
6139 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006140 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006141{
6142 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006143 if (mGains.size() > 0) {
6144 mGains[0]->getDefaultConfig(&mGain);
6145 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006146}
6147
Eric Laurent3a4311c2014-03-17 12:00:47 -07006148bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006149{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006150 // Devices are considered equal if they:
6151 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6152 // - have the same address or one device does not specify the address
6153 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006154 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006155 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006156 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006157 mChannelMask == other->mChannelMask);
6158}
6159
6160void AudioPolicyManager::DeviceVector::refreshTypes()
6161{
Eric Laurent1c333e22014-05-20 10:48:17 -07006162 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006163 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006164 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006165 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006166 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006167}
6168
6169ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6170{
6171 for(size_t i = 0; i < size(); i++) {
6172 if (item->equals(itemAt(i))) {
6173 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006174 }
6175 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006176 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006177}
6178
Eric Laurent3a4311c2014-03-17 12:00:47 -07006179ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006180{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006181 ssize_t ret = indexOf(item);
6182
6183 if (ret < 0) {
6184 ret = SortedVector::add(item);
6185 if (ret >= 0) {
6186 refreshTypes();
6187 }
6188 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006189 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006190 ret = -1;
6191 }
6192 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006193}
6194
Eric Laurent3a4311c2014-03-17 12:00:47 -07006195ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6196{
6197 size_t i;
6198 ssize_t ret = indexOf(item);
6199
6200 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006201 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006202 } else {
6203 ret = SortedVector::removeAt(ret);
6204 if (ret >= 0) {
6205 refreshTypes();
6206 }
6207 }
6208 return ret;
6209}
6210
6211void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6212{
6213 DeviceVector deviceList;
6214
6215 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6216 types &= ~role_bit;
6217
6218 while (types) {
6219 uint32_t i = 31 - __builtin_clz(types);
6220 uint32_t type = 1 << i;
6221 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006222 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006223 }
6224}
6225
Eric Laurent1afeecb2014-05-14 08:52:28 -07006226void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6227 const DeviceVector& declaredDevices)
6228{
6229 char *devName = strtok(name, "|");
6230 while (devName != NULL) {
6231 if (strlen(devName) != 0) {
6232 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6233 ARRAY_SIZE(sDeviceNameToEnumTable),
6234 devName);
6235 if (type != AUDIO_DEVICE_NONE) {
6236 add(new DeviceDescriptor(String8(""), type));
6237 } else {
6238 sp<DeviceDescriptor> deviceDesc =
6239 declaredDevices.getDeviceFromName(String8(devName));
6240 if (deviceDesc != 0) {
6241 add(deviceDesc);
6242 }
6243 }
6244 }
6245 devName = strtok(NULL, "|");
6246 }
6247}
6248
Eric Laurent1c333e22014-05-20 10:48:17 -07006249sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6250 audio_devices_t type, String8 address) const
6251{
6252 sp<DeviceDescriptor> device;
6253 for (size_t i = 0; i < size(); i++) {
6254 if (itemAt(i)->mDeviceType == type) {
6255 device = itemAt(i);
6256 if (itemAt(i)->mAddress = address) {
6257 break;
6258 }
6259 }
6260 }
6261 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6262 type, address.string(), device.get());
6263 return device;
6264}
6265
Eric Laurent6a94d692014-05-20 11:18:06 -07006266sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6267 audio_port_handle_t id) const
6268{
6269 sp<DeviceDescriptor> device;
6270 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006271 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006272 if (itemAt(i)->mId == id) {
6273 device = itemAt(i);
6274 break;
6275 }
6276 }
6277 return device;
6278}
6279
Eric Laurent1c333e22014-05-20 10:48:17 -07006280AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6281 audio_devices_t type) const
6282{
6283 DeviceVector devices;
6284 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6285 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6286 devices.add(itemAt(i));
6287 type &= ~itemAt(i)->mDeviceType;
6288 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6289 itemAt(i)->mDeviceType, itemAt(i).get());
6290 }
6291 }
6292 return devices;
6293}
6294
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006295AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6296 audio_devices_t type, String8 address) const
6297{
6298 DeviceVector devices;
6299 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6300 for (size_t i = 0; i < size(); i++) {
6301 //ALOGV(" at i=%d: device=%x, addr=%s",
6302 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6303 if (itemAt(i)->mDeviceType == type) {
6304 if (itemAt(i)->mAddress == address) {
6305 //ALOGV(" found matching address %s", address.string());
6306 devices.add(itemAt(i));
6307 }
6308 }
6309 }
6310 return devices;
6311}
6312
Eric Laurent1afeecb2014-05-14 08:52:28 -07006313sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6314 const String8& name) const
6315{
6316 sp<DeviceDescriptor> device;
6317 for (size_t i = 0; i < size(); i++) {
6318 if (itemAt(i)->mName == name) {
6319 device = itemAt(i);
6320 break;
6321 }
6322 }
6323 return device;
6324}
6325
Eric Laurent6a94d692014-05-20 11:18:06 -07006326void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6327 struct audio_port_config *dstConfig,
6328 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006329{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006330 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6331 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006332 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006333 }
6334
6335 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6336
Eric Laurent6a94d692014-05-20 11:18:06 -07006337 dstConfig->id = mId;
6338 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006339 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006340 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006341 dstConfig->ext.device.type = mDeviceType;
6342 dstConfig->ext.device.hw_module = mModule->mHandle;
6343 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006344}
6345
6346void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6347{
Eric Laurent83b88082014-06-20 18:31:16 -07006348 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006349 AudioPort::toAudioPort(port);
6350 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006351 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006352 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006353 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006354 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6355}
6356
Eric Laurent1afeecb2014-05-14 08:52:28 -07006357status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006358{
6359 const size_t SIZE = 256;
6360 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006361 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006362
Eric Laurent1afeecb2014-05-14 08:52:28 -07006363 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6364 result.append(buffer);
6365 if (mId != 0) {
6366 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6367 result.append(buffer);
6368 }
6369 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6370 enumToString(sDeviceNameToEnumTable,
6371 ARRAY_SIZE(sDeviceNameToEnumTable),
6372 mDeviceType));
6373 result.append(buffer);
6374 if (mAddress.size() != 0) {
6375 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6376 result.append(buffer);
6377 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006378 write(fd, result.string(), result.size());
6379 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006380
6381 return NO_ERROR;
6382}
6383
6384
6385// --- audio_policy.conf file parsing
6386
Eric Laurente0720872014-03-11 09:30:41 -07006387audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006388{
6389 uint32_t flag = 0;
6390
6391 // it is OK to cast name to non const here as we are not going to use it after
6392 // strtok() modifies it
6393 char *flagName = strtok(name, "|");
6394 while (flagName != NULL) {
6395 if (strlen(flagName) != 0) {
6396 flag |= stringToEnum(sFlagNameToEnumTable,
6397 ARRAY_SIZE(sFlagNameToEnumTable),
6398 flagName);
6399 }
6400 flagName = strtok(NULL, "|");
6401 }
6402 //force direct flag if offload flag is set: offloading implies a direct output stream
6403 // and all common behaviors are driven by checking only the direct flag
6404 // this should normally be set appropriately in the policy configuration file
6405 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6406 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6407 }
6408
6409 return (audio_output_flags_t)flag;
6410}
6411
Eric Laurente0720872014-03-11 09:30:41 -07006412audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006413{
6414 uint32_t device = 0;
6415
6416 char *devName = strtok(name, "|");
6417 while (devName != NULL) {
6418 if (strlen(devName) != 0) {
6419 device |= stringToEnum(sDeviceNameToEnumTable,
6420 ARRAY_SIZE(sDeviceNameToEnumTable),
6421 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006422 }
Eric Laurente552edb2014-03-10 17:42:56 -07006423 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006424 }
Eric Laurente552edb2014-03-10 17:42:56 -07006425 return device;
6426}
6427
Eric Laurente0720872014-03-11 09:30:41 -07006428void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006429{
Eric Laurente552edb2014-03-10 17:42:56 -07006430 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006431 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006432 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006433
Eric Laurent1afeecb2014-05-14 08:52:28 -07006434 node = config_find(root, DEVICES_TAG);
6435 if (node != NULL) {
6436 node = node->first_child;
6437 while (node) {
6438 ALOGV("loadHwModule() loading device %s", node->name);
6439 status_t tmpStatus = module->loadDevice(node);
6440 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6441 status = tmpStatus;
6442 }
6443 node = node->next;
6444 }
6445 }
6446 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006447 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006448 node = node->first_child;
6449 while (node) {
6450 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006451 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006452 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6453 status = tmpStatus;
6454 }
6455 node = node->next;
6456 }
6457 }
6458 node = config_find(root, INPUTS_TAG);
6459 if (node != NULL) {
6460 node = node->first_child;
6461 while (node) {
6462 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006463 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006464 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6465 status = tmpStatus;
6466 }
6467 node = node->next;
6468 }
6469 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006470 loadGlobalConfig(root, module);
6471
Eric Laurente552edb2014-03-10 17:42:56 -07006472 if (status == NO_ERROR) {
6473 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006474 }
6475}
6476
Eric Laurente0720872014-03-11 09:30:41 -07006477void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006478{
6479 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6480 if (node == NULL) {
6481 return;
6482 }
6483
6484 node = node->first_child;
6485 while (node) {
6486 ALOGV("loadHwModules() loading module %s", node->name);
6487 loadHwModule(node);
6488 node = node->next;
6489 }
6490}
6491
Eric Laurent1f2f2232014-06-02 12:01:23 -07006492void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006493{
6494 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006495
Eric Laurente552edb2014-03-10 17:42:56 -07006496 if (node == NULL) {
6497 return;
6498 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006499 DeviceVector declaredDevices;
6500 if (module != NULL) {
6501 declaredDevices = module->mDeclaredDevices;
6502 }
6503
Eric Laurente552edb2014-03-10 17:42:56 -07006504 node = node->first_child;
6505 while (node) {
6506 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006507 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6508 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006509 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6510 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006511 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006512 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006513 ARRAY_SIZE(sDeviceNameToEnumTable),
6514 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006515 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006516 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006517 } else {
6518 ALOGW("loadGlobalConfig() default device not specified");
6519 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006520 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006521 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006522 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6523 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006524 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006525 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6526 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6527 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006528 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6529 uint32_t major, minor;
6530 sscanf((char *)node->value, "%u.%u", &major, &minor);
6531 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6532 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6533 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006534 }
6535 node = node->next;
6536 }
6537}
6538
Eric Laurente0720872014-03-11 09:30:41 -07006539status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006540{
6541 cnode *root;
6542 char *data;
6543
6544 data = (char *)load_file(path, NULL);
6545 if (data == NULL) {
6546 return -ENODEV;
6547 }
6548 root = config_node("", "");
6549 config_load(root, data);
6550
Eric Laurente552edb2014-03-10 17:42:56 -07006551 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006552 // legacy audio_policy.conf files have one global_configuration section
6553 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006554 config_free(root);
6555 free(root);
6556 free(data);
6557
6558 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6559
6560 return NO_ERROR;
6561}
6562
Eric Laurente0720872014-03-11 09:30:41 -07006563void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006564{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006565 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006566 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006567 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6568 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006569 mAvailableOutputDevices.add(mDefaultOutputDevice);
6570 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006571
6572 module = new HwModule("primary");
6573
Eric Laurent1afeecb2014-05-14 08:52:28 -07006574 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006575 profile->mSamplingRates.add(44100);
6576 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6577 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006578 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006579 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6580 module->mOutputProfiles.add(profile);
6581
Eric Laurent1afeecb2014-05-14 08:52:28 -07006582 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006583 profile->mSamplingRates.add(8000);
6584 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6585 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006586 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006587 module->mInputProfiles.add(profile);
6588
6589 mHwModules.add(module);
6590}
6591
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006592audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6593{
6594 // flags to stream type mapping
6595 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6596 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6597 }
6598 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6599 return AUDIO_STREAM_BLUETOOTH_SCO;
6600 }
6601
6602 // usage to stream type mapping
6603 switch (attr->usage) {
6604 case AUDIO_USAGE_MEDIA:
6605 case AUDIO_USAGE_GAME:
6606 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6607 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6608 return AUDIO_STREAM_MUSIC;
6609 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6610 return AUDIO_STREAM_SYSTEM;
6611 case AUDIO_USAGE_VOICE_COMMUNICATION:
6612 return AUDIO_STREAM_VOICE_CALL;
6613
6614 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6615 return AUDIO_STREAM_DTMF;
6616
6617 case AUDIO_USAGE_ALARM:
6618 return AUDIO_STREAM_ALARM;
6619 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6620 return AUDIO_STREAM_RING;
6621
6622 case AUDIO_USAGE_NOTIFICATION:
6623 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6624 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6625 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6626 case AUDIO_USAGE_NOTIFICATION_EVENT:
6627 return AUDIO_STREAM_NOTIFICATION;
6628
6629 case AUDIO_USAGE_UNKNOWN:
6630 default:
6631 return AUDIO_STREAM_MUSIC;
6632 }
6633}
Eric Laurente552edb2014-03-10 17:42:56 -07006634}; // namespace android