blob: f716358ba3d2164997d06eff0c02f03938256f77 [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 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003709 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003710 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003711 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003712 if (device == AUDIO_DEVICE_NONE) {
3713 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3714 }
3715 break;
3716 }
3717 break;
3718
3719 case STRATEGY_SONIFICATION:
3720
3721 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3722 // handleIncallSonification().
3723 if (isInCall()) {
3724 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3725 break;
3726 }
3727 // FALL THROUGH
3728
3729 case STRATEGY_ENFORCED_AUDIBLE:
3730 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3731 // except:
3732 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3733 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3734
3735 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003736 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003737 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003738 if (device == AUDIO_DEVICE_NONE) {
3739 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3740 }
3741 }
3742 // The second device used for sonification is the same as the device used by media strategy
3743 // FALL THROUGH
3744
3745 case STRATEGY_MEDIA: {
3746 uint32_t device2 = AUDIO_DEVICE_NONE;
3747 if (strategy != STRATEGY_SONIFICATION) {
3748 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003749 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003750 }
3751 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003752 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003753 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003754 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003755 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003756 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003757 }
3758 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003759 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003760 }
3761 }
3762 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003763 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003764 }
3765 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003766 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003767 }
3768 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003769 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003770 }
3771 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003772 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003773 }
3774 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003775 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003776 }
3777 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3778 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003779 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003780 }
3781 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003782 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003783 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003784 }
3785 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003786 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003787 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003788 int device3 = AUDIO_DEVICE_NONE;
3789 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003790 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003791 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3792 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003793 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003794 }
Eric Laurente552edb2014-03-10 17:42:56 -07003795
Jungshik Jang839e4f32014-06-26 17:23:40 +09003796 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003797 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3798 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3799 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003800
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003801 // If hdmi system audio mode is on, remove speaker out of output list.
3802 if ((strategy == STRATEGY_MEDIA) &&
3803 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3804 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3805 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3806 }
3807
Eric Laurente552edb2014-03-10 17:42:56 -07003808 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003809 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003810 if (device == AUDIO_DEVICE_NONE) {
3811 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3812 }
3813 } break;
3814
3815 default:
3816 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3817 break;
3818 }
3819
3820 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3821 return device;
3822}
3823
Eric Laurente0720872014-03-11 09:30:41 -07003824void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003825{
3826 for (int i = 0; i < NUM_STRATEGIES; i++) {
3827 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3828 }
3829 mPreviousOutputs = mOutputs;
3830}
3831
Eric Laurent1f2f2232014-06-02 12:01:23 -07003832uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003833 audio_devices_t prevDevice,
3834 uint32_t delayMs)
3835{
3836 // mute/unmute strategies using an incompatible device combination
3837 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3838 // if unmuting, unmute only after the specified delay
3839 if (outputDesc->isDuplicated()) {
3840 return 0;
3841 }
3842
3843 uint32_t muteWaitMs = 0;
3844 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003845 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003846
3847 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3848 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3849 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3850 bool doMute = false;
3851
3852 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3853 doMute = true;
3854 outputDesc->mStrategyMutedByDevice[i] = true;
3855 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3856 doMute = true;
3857 outputDesc->mStrategyMutedByDevice[i] = false;
3858 }
Eric Laurent99401132014-05-07 19:48:15 -07003859 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003860 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003861 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003862 // skip output if it does not share any device with current output
3863 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3864 == AUDIO_DEVICE_NONE) {
3865 continue;
3866 }
3867 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3868 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3869 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3870 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3871 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003872 if (mute) {
3873 // FIXME: should not need to double latency if volume could be applied
3874 // immediately by the audioflinger mixer. We must account for the delay
3875 // between now and the next time the audioflinger thread for this output
3876 // will process a buffer (which corresponds to one buffer size,
3877 // usually 1/2 or 1/4 of the latency).
3878 if (muteWaitMs < desc->latency() * 2) {
3879 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003880 }
3881 }
3882 }
3883 }
3884 }
3885 }
3886
Eric Laurent99401132014-05-07 19:48:15 -07003887 // temporary mute output if device selection changes to avoid volume bursts due to
3888 // different per device volumes
3889 if (outputDesc->isActive() && (device != prevDevice)) {
3890 if (muteWaitMs < outputDesc->latency() * 2) {
3891 muteWaitMs = outputDesc->latency() * 2;
3892 }
3893 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3894 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003895 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003896 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003897 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003898 muteWaitMs *2, device);
3899 }
3900 }
3901 }
3902
Eric Laurente552edb2014-03-10 17:42:56 -07003903 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3904 if (muteWaitMs > delayMs) {
3905 muteWaitMs -= delayMs;
3906 usleep(muteWaitMs * 1000);
3907 return muteWaitMs;
3908 }
3909 return 0;
3910}
3911
Eric Laurente0720872014-03-11 09:30:41 -07003912uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003913 audio_devices_t device,
3914 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003915 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003916 audio_patch_handle_t *patchHandle,
3917 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003918{
3919 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003920 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003921 AudioParameter param;
3922 uint32_t muteWaitMs;
3923
3924 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003925 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3926 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003927 return muteWaitMs;
3928 }
3929 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3930 // output profile
3931 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003932 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003933 return 0;
3934 }
3935
3936 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003938
3939 audio_devices_t prevDevice = outputDesc->mDevice;
3940
3941 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3942
3943 if (device != AUDIO_DEVICE_NONE) {
3944 outputDesc->mDevice = device;
3945 }
3946 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3947
3948 // Do not change the routing if:
3949 // - the requested device is AUDIO_DEVICE_NONE
3950 // - the requested device is the same as current device and force is not specified.
3951 // Doing this check here allows the caller to call setOutputDevice() without conditions
3952 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3953 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3954 return muteWaitMs;
3955 }
3956
3957 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003958
Eric Laurente552edb2014-03-10 17:42:56 -07003959 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003960 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003961 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003962 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003963 DeviceVector deviceList = (address == NULL) ?
3964 mAvailableOutputDevices.getDevicesFromType(device)
3965 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003966 if (!deviceList.isEmpty()) {
3967 struct audio_patch patch;
3968 outputDesc->toAudioPortConfig(&patch.sources[0]);
3969 patch.num_sources = 1;
3970 patch.num_sinks = 0;
3971 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3972 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003973 patch.num_sinks++;
3974 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003975 ssize_t index;
3976 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3977 index = mAudioPatches.indexOfKey(*patchHandle);
3978 } else {
3979 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3980 }
3981 sp< AudioPatch> patchDesc;
3982 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3983 if (index >= 0) {
3984 patchDesc = mAudioPatches.valueAt(index);
3985 afPatchHandle = patchDesc->mAfPatchHandle;
3986 }
3987
Eric Laurent1c333e22014-05-20 10:48:17 -07003988 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 &afPatchHandle,
3990 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003991 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3992 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003993 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003994 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 if (index < 0) {
3996 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3997 &patch, mUidCached);
3998 addAudioPatch(patchDesc->mHandle, patchDesc);
3999 } else {
4000 patchDesc->mPatch = patch;
4001 }
4002 patchDesc->mAfPatchHandle = afPatchHandle;
4003 patchDesc->mUid = mUidCached;
4004 if (patchHandle) {
4005 *patchHandle = patchDesc->mHandle;
4006 }
4007 outputDesc->mPatchHandle = patchDesc->mHandle;
4008 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004009 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004010 }
4011 }
4012 }
Eric Laurente552edb2014-03-10 17:42:56 -07004013
4014 // update stream volumes according to new device
4015 applyStreamVolumes(output, device, delayMs);
4016
4017 return muteWaitMs;
4018}
4019
Eric Laurent1c333e22014-05-20 10:48:17 -07004020status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004021 int delayMs,
4022 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004023{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004024 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004025 ssize_t index;
4026 if (patchHandle) {
4027 index = mAudioPatches.indexOfKey(*patchHandle);
4028 } else {
4029 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4030 }
4031 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004032 return INVALID_OPERATION;
4033 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004034 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4035 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004036 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4037 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004038 removeAudioPatch(patchDesc->mHandle);
4039 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004040 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004041 return status;
4042}
4043
4044status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4045 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004046 bool force,
4047 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004048{
4049 status_t status = NO_ERROR;
4050
Eric Laurent1f2f2232014-06-02 12:01:23 -07004051 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004052 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4053 inputDesc->mDevice = device;
4054
4055 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4056 if (!deviceList.isEmpty()) {
4057 struct audio_patch patch;
4058 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004059 // AUDIO_SOURCE_HOTWORD is for internal use only:
4060 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004061 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4062 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004063 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4064 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004065 patch.num_sinks = 1;
4066 //only one input device for now
4067 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004068 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004069 ssize_t index;
4070 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4071 index = mAudioPatches.indexOfKey(*patchHandle);
4072 } else {
4073 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4074 }
4075 sp< AudioPatch> patchDesc;
4076 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4077 if (index >= 0) {
4078 patchDesc = mAudioPatches.valueAt(index);
4079 afPatchHandle = patchDesc->mAfPatchHandle;
4080 }
4081
Eric Laurent1c333e22014-05-20 10:48:17 -07004082 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004083 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004084 0);
4085 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004086 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004087 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004088 if (index < 0) {
4089 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4090 &patch, mUidCached);
4091 addAudioPatch(patchDesc->mHandle, patchDesc);
4092 } else {
4093 patchDesc->mPatch = patch;
4094 }
4095 patchDesc->mAfPatchHandle = afPatchHandle;
4096 patchDesc->mUid = mUidCached;
4097 if (patchHandle) {
4098 *patchHandle = patchDesc->mHandle;
4099 }
4100 inputDesc->mPatchHandle = patchDesc->mHandle;
4101 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004102 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004103 }
4104 }
4105 }
4106 return status;
4107}
4108
Eric Laurent6a94d692014-05-20 11:18:06 -07004109status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4110 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004111{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004112 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004113 ssize_t index;
4114 if (patchHandle) {
4115 index = mAudioPatches.indexOfKey(*patchHandle);
4116 } else {
4117 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4118 }
4119 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004120 return INVALID_OPERATION;
4121 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004122 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4123 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004124 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4125 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004126 removeAudioPatch(patchDesc->mHandle);
4127 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004128 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004129 return status;
4130}
4131
4132sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004133 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004134 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004135 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004136 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004137{
4138 // Choose an input profile based on the requested capture parameters: select the first available
4139 // profile supporting all requested parameters.
4140
4141 for (size_t i = 0; i < mHwModules.size(); i++)
4142 {
4143 if (mHwModules[i]->mHandle == 0) {
4144 continue;
4145 }
4146 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4147 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004148 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004149 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004150 if (profile->isCompatibleProfile(device, samplingRate,
4151 &samplingRate /*updatedSamplingRate*/,
4152 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004153 return profile;
4154 }
4155 }
4156 }
4157 return NULL;
4158}
4159
Eric Laurente0720872014-03-11 09:30:41 -07004160audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004161{
4162 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004163 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4164 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004165 switch (inputSource) {
4166 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004167 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004168 device = AUDIO_DEVICE_IN_VOICE_CALL;
4169 break;
4170 }
4171 // FALL THROUGH
4172
4173 case AUDIO_SOURCE_DEFAULT:
4174 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004175 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4176 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4177 break;
4178 }
4179 // FALL THROUGH
4180
Eric Laurente552edb2014-03-10 17:42:56 -07004181 case AUDIO_SOURCE_VOICE_RECOGNITION:
4182 case AUDIO_SOURCE_HOTWORD:
4183 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004184 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004185 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004186 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004187 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004188 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004189 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4190 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004191 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004192 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4193 }
4194 break;
4195 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004196 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004197 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004198 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004199 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4200 }
4201 break;
4202 case AUDIO_SOURCE_VOICE_DOWNLINK:
4203 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004204 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004205 device = AUDIO_DEVICE_IN_VOICE_CALL;
4206 }
4207 break;
4208 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004209 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004210 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4211 }
4212 break;
4213 default:
4214 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4215 break;
4216 }
4217 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4218 return device;
4219}
4220
Eric Laurente0720872014-03-11 09:30:41 -07004221bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004222{
4223 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4224 device &= ~AUDIO_DEVICE_BIT_IN;
4225 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4226 return true;
4227 }
4228 return false;
4229}
4230
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004231bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4232 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4233}
4234
Eric Laurente0720872014-03-11 09:30:41 -07004235audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004236{
4237 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004238 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004239 if ((input_descriptor->mRefCount > 0)
4240 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4241 return mInputs.keyAt(i);
4242 }
4243 }
4244 return 0;
4245}
4246
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004247uint32_t AudioPolicyManager::activeInputsCount() const
4248{
4249 uint32_t count = 0;
4250 for (size_t i = 0; i < mInputs.size(); i++) {
4251 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4252 if (desc->mRefCount > 0) {
4253 return count++;
4254 }
4255 }
4256 return count;
4257}
4258
Eric Laurente552edb2014-03-10 17:42:56 -07004259
Eric Laurente0720872014-03-11 09:30:41 -07004260audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004261{
4262 if (device == AUDIO_DEVICE_NONE) {
4263 // this happens when forcing a route update and no track is active on an output.
4264 // In this case the returned category is not important.
4265 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004266 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004267 // Multiple device selection is either:
4268 // - speaker + one other device: give priority to speaker in this case.
4269 // - one A2DP device + another device: happens with duplicated output. In this case
4270 // retain the device on the A2DP output as the other must not correspond to an active
4271 // selection if not the speaker.
4272 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4273 device = AUDIO_DEVICE_OUT_SPEAKER;
4274 } else {
4275 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4276 }
4277 }
4278
Eric Laurent3b73df72014-03-11 09:06:29 -07004279 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004280 "getDeviceForVolume() invalid device combination: %08x",
4281 device);
4282
4283 return device;
4284}
4285
Eric Laurente0720872014-03-11 09:30:41 -07004286AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004287{
4288 switch(getDeviceForVolume(device)) {
4289 case AUDIO_DEVICE_OUT_EARPIECE:
4290 return DEVICE_CATEGORY_EARPIECE;
4291 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4292 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4293 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4294 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4295 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4296 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4297 return DEVICE_CATEGORY_HEADSET;
4298 case AUDIO_DEVICE_OUT_SPEAKER:
4299 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4300 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4301 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4302 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4303 case AUDIO_DEVICE_OUT_USB_DEVICE:
4304 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4305 default:
4306 return DEVICE_CATEGORY_SPEAKER;
4307 }
4308}
4309
Eric Laurente0720872014-03-11 09:30:41 -07004310float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004311 int indexInUi)
4312{
4313 device_category deviceCategory = getDeviceCategory(device);
4314 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4315
4316 // the volume index in the UI is relative to the min and max volume indices for this stream type
4317 int nbSteps = 1 + curve[VOLMAX].mIndex -
4318 curve[VOLMIN].mIndex;
4319 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4320 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4321
4322 // find what part of the curve this index volume belongs to, or if it's out of bounds
4323 int segment = 0;
4324 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4325 return 0.0f;
4326 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4327 segment = 0;
4328 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4329 segment = 1;
4330 } else if (volIdx <= curve[VOLMAX].mIndex) {
4331 segment = 2;
4332 } else { // out of bounds
4333 return 1.0f;
4334 }
4335
4336 // linear interpolation in the attenuation table in dB
4337 float decibels = curve[segment].mDBAttenuation +
4338 ((float)(volIdx - curve[segment].mIndex)) *
4339 ( (curve[segment+1].mDBAttenuation -
4340 curve[segment].mDBAttenuation) /
4341 ((float)(curve[segment+1].mIndex -
4342 curve[segment].mIndex)) );
4343
4344 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4345
4346 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4347 curve[segment].mIndex, volIdx,
4348 curve[segment+1].mIndex,
4349 curve[segment].mDBAttenuation,
4350 decibels,
4351 curve[segment+1].mDBAttenuation,
4352 amplification);
4353
4354 return amplification;
4355}
4356
Eric Laurente0720872014-03-11 09:30:41 -07004357const AudioPolicyManager::VolumeCurvePoint
4358 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004359 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4360};
4361
Eric Laurente0720872014-03-11 09:30:41 -07004362const AudioPolicyManager::VolumeCurvePoint
4363 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004364 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4365};
4366
Eric Laurente0720872014-03-11 09:30:41 -07004367const AudioPolicyManager::VolumeCurvePoint
4368 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004369 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4370};
4371
Eric Laurente0720872014-03-11 09:30:41 -07004372const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004373 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004374 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004375};
4376
4377const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004378 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004379 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4380};
4381
Eric Laurente0720872014-03-11 09:30:41 -07004382const AudioPolicyManager::VolumeCurvePoint
4383 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004384 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4385};
4386
4387// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4388// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4389// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4390// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4391
Eric Laurente0720872014-03-11 09:30:41 -07004392const AudioPolicyManager::VolumeCurvePoint
4393 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004394 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4395};
4396
Eric Laurente0720872014-03-11 09:30:41 -07004397const AudioPolicyManager::VolumeCurvePoint
4398 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004399 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4400};
4401
Eric Laurente0720872014-03-11 09:30:41 -07004402const AudioPolicyManager::VolumeCurvePoint
4403 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004404 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4405};
4406
Eric Laurente0720872014-03-11 09:30:41 -07004407const AudioPolicyManager::VolumeCurvePoint
4408 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004409 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4410};
4411
Eric Laurente0720872014-03-11 09:30:41 -07004412const AudioPolicyManager::VolumeCurvePoint
4413 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004414 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4415};
4416
Eric Laurente0720872014-03-11 09:30:41 -07004417const AudioPolicyManager::VolumeCurvePoint
4418 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4419 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004420 { // AUDIO_STREAM_VOICE_CALL
4421 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4422 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4423 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4424 },
4425 { // AUDIO_STREAM_SYSTEM
4426 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4427 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4428 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4429 },
4430 { // AUDIO_STREAM_RING
4431 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4432 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4433 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4434 },
4435 { // AUDIO_STREAM_MUSIC
4436 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4437 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4438 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4439 },
4440 { // AUDIO_STREAM_ALARM
4441 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4442 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4443 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4444 },
4445 { // AUDIO_STREAM_NOTIFICATION
4446 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4447 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4448 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4449 },
4450 { // AUDIO_STREAM_BLUETOOTH_SCO
4451 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4452 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4453 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4454 },
4455 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4456 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4457 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4458 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4459 },
4460 { // AUDIO_STREAM_DTMF
4461 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4462 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4463 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4464 },
4465 { // AUDIO_STREAM_TTS
4466 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4467 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4468 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4469 },
4470};
4471
Eric Laurente0720872014-03-11 09:30:41 -07004472void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004473{
4474 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4475 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4476 mStreams[i].mVolumeCurve[j] =
4477 sVolumeProfiles[i][j];
4478 }
4479 }
4480
4481 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4482 if (mSpeakerDrcEnabled) {
4483 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4484 sDefaultSystemVolumeCurveDrc;
4485 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4486 sSpeakerSonificationVolumeCurveDrc;
4487 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4488 sSpeakerSonificationVolumeCurveDrc;
4489 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4490 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004491 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4492 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004493 }
4494}
4495
Eric Laurente0720872014-03-11 09:30:41 -07004496float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004497 int index,
4498 audio_io_handle_t output,
4499 audio_devices_t device)
4500{
4501 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004502 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004503 StreamDescriptor &streamDesc = mStreams[stream];
4504
4505 if (device == AUDIO_DEVICE_NONE) {
4506 device = outputDesc->device();
4507 }
4508
Eric Laurente552edb2014-03-10 17:42:56 -07004509 volume = volIndexToAmpl(device, streamDesc, index);
4510
4511 // if a headset is connected, apply the following rules to ring tones and notifications
4512 // to avoid sound level bursts in user's ears:
4513 // - always attenuate ring tones and notifications volume by 6dB
4514 // - if music is playing, always limit the volume to current music volume,
4515 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004516 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004517 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4518 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4519 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4520 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4521 ((stream_strategy == STRATEGY_SONIFICATION)
4522 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004523 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004524 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004525 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004526 streamDesc.mCanBeMuted) {
4527 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4528 // when the phone is ringing we must consider that music could have been paused just before
4529 // by the music application and behave as if music was active if the last music track was
4530 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004531 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004532 mLimitRingtoneVolume) {
4533 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004534 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4535 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004536 output,
4537 musicDevice);
4538 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4539 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4540 if (volume > minVol) {
4541 volume = minVol;
4542 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4543 }
4544 }
4545 }
4546
4547 return volume;
4548}
4549
Eric Laurente0720872014-03-11 09:30:41 -07004550status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004551 int index,
4552 audio_io_handle_t output,
4553 audio_devices_t device,
4554 int delayMs,
4555 bool force)
4556{
4557
4558 // do not change actual stream volume if the stream is muted
4559 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4560 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4561 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4562 return NO_ERROR;
4563 }
4564
4565 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004566 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4567 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4568 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4569 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004570 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004571 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004572 return INVALID_OPERATION;
4573 }
4574
4575 float volume = computeVolume(stream, index, output, device);
4576 // We actually change the volume if:
4577 // - the float value returned by computeVolume() changed
4578 // - the force flag is set
4579 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4580 force) {
4581 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4582 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4583 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4584 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004585 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4586 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004587 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004588 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004589 }
4590
Eric Laurent3b73df72014-03-11 09:06:29 -07004591 if (stream == AUDIO_STREAM_VOICE_CALL ||
4592 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004593 float voiceVolume;
4594 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004595 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004596 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4597 } else {
4598 voiceVolume = 1.0;
4599 }
4600
4601 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4602 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4603 mLastVoiceVolume = voiceVolume;
4604 }
4605 }
4606
4607 return NO_ERROR;
4608}
4609
Eric Laurente0720872014-03-11 09:30:41 -07004610void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004611 audio_devices_t device,
4612 int delayMs,
4613 bool force)
4614{
4615 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4616
Eric Laurent3b73df72014-03-11 09:06:29 -07004617 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4618 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004619 mStreams[stream].getVolumeIndex(device),
4620 output,
4621 device,
4622 delayMs,
4623 force);
4624 }
4625}
4626
Eric Laurente0720872014-03-11 09:30:41 -07004627void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004628 bool on,
4629 audio_io_handle_t output,
4630 int delayMs,
4631 audio_devices_t device)
4632{
4633 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004634 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4635 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4636 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004637 }
4638 }
4639}
4640
Eric Laurente0720872014-03-11 09:30:41 -07004641void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004642 bool on,
4643 audio_io_handle_t output,
4644 int delayMs,
4645 audio_devices_t device)
4646{
4647 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004648 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004649 if (device == AUDIO_DEVICE_NONE) {
4650 device = outputDesc->device();
4651 }
4652
4653 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4654 stream, on, output, outputDesc->mMuteCount[stream], device);
4655
4656 if (on) {
4657 if (outputDesc->mMuteCount[stream] == 0) {
4658 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004659 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4660 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004661 checkAndSetVolume(stream, 0, output, device, delayMs);
4662 }
4663 }
4664 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4665 outputDesc->mMuteCount[stream]++;
4666 } else {
4667 if (outputDesc->mMuteCount[stream] == 0) {
4668 ALOGV("setStreamMute() unmuting non muted stream!");
4669 return;
4670 }
4671 if (--outputDesc->mMuteCount[stream] == 0) {
4672 checkAndSetVolume(stream,
4673 streamDesc.getVolumeIndex(device),
4674 output,
4675 device,
4676 delayMs);
4677 }
4678 }
4679}
4680
Eric Laurente0720872014-03-11 09:30:41 -07004681void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004682 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004683{
4684 // if the stream pertains to sonification strategy and we are in call we must
4685 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4686 // in the device used for phone strategy and play the tone if the selected device does not
4687 // interfere with the device used for phone strategy
4688 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4689 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004690 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004691 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4692 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004693 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004694 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4695 stream, starting, outputDesc->mDevice, stateChange);
4696 if (outputDesc->mRefCount[stream]) {
4697 int muteCount = 1;
4698 if (stateChange) {
4699 muteCount = outputDesc->mRefCount[stream];
4700 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004701 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004702 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4703 for (int i = 0; i < muteCount; i++) {
4704 setStreamMute(stream, starting, mPrimaryOutput);
4705 }
4706 } else {
4707 ALOGV("handleIncallSonification() high visibility");
4708 if (outputDesc->device() &
4709 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4710 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4711 for (int i = 0; i < muteCount; i++) {
4712 setStreamMute(stream, starting, mPrimaryOutput);
4713 }
4714 }
4715 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004716 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4717 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004718 } else {
4719 mpClientInterface->stopTone();
4720 }
4721 }
4722 }
4723 }
4724}
4725
Eric Laurente0720872014-03-11 09:30:41 -07004726bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004727{
4728 return isStateInCall(mPhoneState);
4729}
4730
Eric Laurente0720872014-03-11 09:30:41 -07004731bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004732 return ((state == AUDIO_MODE_IN_CALL) ||
4733 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004734}
4735
Eric Laurente0720872014-03-11 09:30:41 -07004736uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004737{
4738 return MAX_EFFECTS_CPU_LOAD;
4739}
4740
Eric Laurente0720872014-03-11 09:30:41 -07004741uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004742{
4743 return MAX_EFFECTS_MEMORY;
4744}
4745
Eric Laurent6a94d692014-05-20 11:18:06 -07004746
Eric Laurente552edb2014-03-10 17:42:56 -07004747// --- AudioOutputDescriptor class implementation
4748
Eric Laurente0720872014-03-11 09:30:41 -07004749AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004750 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004751 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004752 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004753 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4754{
4755 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004756 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004757 mRefCount[i] = 0;
4758 mCurVolume[i] = -1.0;
4759 mMuteCount[i] = 0;
4760 mStopTime[i] = 0;
4761 }
4762 for (int i = 0; i < NUM_STRATEGIES; i++) {
4763 mStrategyMutedByDevice[i] = false;
4764 }
4765 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004766 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004767 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004768 mSamplingRate = profile->pickSamplingRate();
4769 mFormat = profile->pickFormat();
4770 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004771 if (profile->mGains.size() > 0) {
4772 profile->mGains[0]->getDefaultConfig(&mGain);
4773 }
Eric Laurente552edb2014-03-10 17:42:56 -07004774 }
4775}
4776
Eric Laurente0720872014-03-11 09:30:41 -07004777audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004778{
4779 if (isDuplicated()) {
4780 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4781 } else {
4782 return mDevice;
4783 }
4784}
4785
Eric Laurente0720872014-03-11 09:30:41 -07004786uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004787{
4788 if (isDuplicated()) {
4789 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4790 } else {
4791 return mLatency;
4792 }
4793}
4794
Eric Laurente0720872014-03-11 09:30:41 -07004795bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004796 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004797{
4798 if (isDuplicated()) {
4799 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4800 } else if (outputDesc->isDuplicated()){
4801 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4802 } else {
4803 return (mProfile->mModule == outputDesc->mProfile->mModule);
4804 }
4805}
4806
Eric Laurente0720872014-03-11 09:30:41 -07004807void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004808 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004809{
4810 // forward usage count change to attached outputs
4811 if (isDuplicated()) {
4812 mOutput1->changeRefCount(stream, delta);
4813 mOutput2->changeRefCount(stream, delta);
4814 }
4815 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004816 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4817 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004818 mRefCount[stream] = 0;
4819 return;
4820 }
4821 mRefCount[stream] += delta;
4822 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4823}
4824
Eric Laurente0720872014-03-11 09:30:41 -07004825audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004826{
4827 if (isDuplicated()) {
4828 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4829 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004830 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004831 }
4832}
4833
Eric Laurente0720872014-03-11 09:30:41 -07004834bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004835{
4836 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4837}
4838
Eric Laurente0720872014-03-11 09:30:41 -07004839bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004840 uint32_t inPastMs,
4841 nsecs_t sysTime) const
4842{
4843 if ((sysTime == 0) && (inPastMs != 0)) {
4844 sysTime = systemTime();
4845 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004846 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4847 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004848 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004849 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004850 return true;
4851 }
4852 }
4853 return false;
4854}
4855
Eric Laurente0720872014-03-11 09:30:41 -07004856bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004857 uint32_t inPastMs,
4858 nsecs_t sysTime) const
4859{
4860 if (mRefCount[stream] != 0) {
4861 return true;
4862 }
4863 if (inPastMs == 0) {
4864 return false;
4865 }
4866 if (sysTime == 0) {
4867 sysTime = systemTime();
4868 }
4869 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4870 return true;
4871 }
4872 return false;
4873}
4874
Eric Laurent1c333e22014-05-20 10:48:17 -07004875void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004876 struct audio_port_config *dstConfig,
4877 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004878{
Eric Laurent84c70242014-06-23 08:46:27 -07004879 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4880
Eric Laurent1f2f2232014-06-02 12:01:23 -07004881 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4882 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4883 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004884 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004885 }
4886 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4887
Eric Laurent6a94d692014-05-20 11:18:06 -07004888 dstConfig->id = mId;
4889 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4890 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004891 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4892 dstConfig->ext.mix.handle = mIoHandle;
4893 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004894}
4895
4896void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4897 struct audio_port *port) const
4898{
Eric Laurent84c70242014-06-23 08:46:27 -07004899 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 mProfile->toAudioPort(port);
4901 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 toAudioPortConfig(&port->active_config);
4903 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004904 port->ext.mix.handle = mIoHandle;
4905 port->ext.mix.latency_class =
4906 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4907}
Eric Laurente552edb2014-03-10 17:42:56 -07004908
Eric Laurente0720872014-03-11 09:30:41 -07004909status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004910{
4911 const size_t SIZE = 256;
4912 char buffer[SIZE];
4913 String8 result;
4914
4915 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4916 result.append(buffer);
4917 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4918 result.append(buffer);
4919 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4920 result.append(buffer);
4921 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4922 result.append(buffer);
4923 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4924 result.append(buffer);
4925 snprintf(buffer, SIZE, " Devices %08x\n", device());
4926 result.append(buffer);
4927 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4928 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004929 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4930 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4931 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004932 result.append(buffer);
4933 }
4934 write(fd, result.string(), result.size());
4935
4936 return NO_ERROR;
4937}
4938
4939// --- AudioInputDescriptor class implementation
4940
Eric Laurent1c333e22014-05-20 10:48:17 -07004941AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004942 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004943 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004944 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004945{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004946 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004947 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004948 mSamplingRate = profile->pickSamplingRate();
4949 mFormat = profile->pickFormat();
4950 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004951 if (profile->mGains.size() > 0) {
4952 profile->mGains[0]->getDefaultConfig(&mGain);
4953 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004954 }
Eric Laurente552edb2014-03-10 17:42:56 -07004955}
4956
Eric Laurent1c333e22014-05-20 10:48:17 -07004957void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 struct audio_port_config *dstConfig,
4959 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004960{
Eric Laurent84c70242014-06-23 08:46:27 -07004961 ALOG_ASSERT(mProfile != 0,
4962 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004963 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4964 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4965 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004966 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004967 }
4968
4969 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4970
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 dstConfig->id = mId;
4972 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4973 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004974 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4975 dstConfig->ext.mix.handle = mIoHandle;
4976 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004977}
4978
4979void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4980 struct audio_port *port) const
4981{
Eric Laurent84c70242014-06-23 08:46:27 -07004982 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4983
Eric Laurent1c333e22014-05-20 10:48:17 -07004984 mProfile->toAudioPort(port);
4985 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 toAudioPortConfig(&port->active_config);
4987 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004988 port->ext.mix.handle = mIoHandle;
4989 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4990}
4991
Eric Laurente0720872014-03-11 09:30:41 -07004992status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004993{
4994 const size_t SIZE = 256;
4995 char buffer[SIZE];
4996 String8 result;
4997
4998 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4999 result.append(buffer);
5000 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5001 result.append(buffer);
5002 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5003 result.append(buffer);
5004 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5005 result.append(buffer);
5006 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5007 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005008 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5009 result.append(buffer);
5010
Eric Laurente552edb2014-03-10 17:42:56 -07005011 write(fd, result.string(), result.size());
5012
5013 return NO_ERROR;
5014}
5015
5016// --- StreamDescriptor class implementation
5017
Eric Laurente0720872014-03-11 09:30:41 -07005018AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005019 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5020{
5021 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5022}
5023
Eric Laurente0720872014-03-11 09:30:41 -07005024int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005025{
Eric Laurente0720872014-03-11 09:30:41 -07005026 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005027 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5028 if (mIndexCur.indexOfKey(device) < 0) {
5029 device = AUDIO_DEVICE_OUT_DEFAULT;
5030 }
5031 return mIndexCur.valueFor(device);
5032}
5033
Eric Laurente0720872014-03-11 09:30:41 -07005034void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005035{
5036 const size_t SIZE = 256;
5037 char buffer[SIZE];
5038 String8 result;
5039
5040 snprintf(buffer, SIZE, "%s %02d %02d ",
5041 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5042 result.append(buffer);
5043 for (size_t i = 0; i < mIndexCur.size(); i++) {
5044 snprintf(buffer, SIZE, "%04x : %02d, ",
5045 mIndexCur.keyAt(i),
5046 mIndexCur.valueAt(i));
5047 result.append(buffer);
5048 }
5049 result.append("\n");
5050
5051 write(fd, result.string(), result.size());
5052}
5053
5054// --- EffectDescriptor class implementation
5055
Eric Laurente0720872014-03-11 09:30:41 -07005056status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005057{
5058 const size_t SIZE = 256;
5059 char buffer[SIZE];
5060 String8 result;
5061
5062 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5063 result.append(buffer);
5064 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5065 result.append(buffer);
5066 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5067 result.append(buffer);
5068 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5069 result.append(buffer);
5070 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5071 result.append(buffer);
5072 write(fd, result.string(), result.size());
5073
5074 return NO_ERROR;
5075}
5076
Eric Laurent1c333e22014-05-20 10:48:17 -07005077// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005078
Eric Laurente0720872014-03-11 09:30:41 -07005079AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005080 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5081 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005082{
5083}
5084
Eric Laurente0720872014-03-11 09:30:41 -07005085AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005086{
5087 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005088 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005089 }
5090 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005091 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005092 }
5093 free((void *)mName);
5094}
5095
Eric Laurent1afeecb2014-05-14 08:52:28 -07005096status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5097{
5098 cnode *node = root->first_child;
5099
5100 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5101
5102 while (node) {
5103 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5104 profile->loadSamplingRates((char *)node->value);
5105 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5106 profile->loadFormats((char *)node->value);
5107 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5108 profile->loadInChannels((char *)node->value);
5109 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5110 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5111 mDeclaredDevices);
5112 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5113 profile->loadGains(node);
5114 }
5115 node = node->next;
5116 }
5117 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5118 "loadInput() invalid supported devices");
5119 ALOGW_IF(profile->mChannelMasks.size() == 0,
5120 "loadInput() invalid supported channel masks");
5121 ALOGW_IF(profile->mSamplingRates.size() == 0,
5122 "loadInput() invalid supported sampling rates");
5123 ALOGW_IF(profile->mFormats.size() == 0,
5124 "loadInput() invalid supported formats");
5125 if (!profile->mSupportedDevices.isEmpty() &&
5126 (profile->mChannelMasks.size() != 0) &&
5127 (profile->mSamplingRates.size() != 0) &&
5128 (profile->mFormats.size() != 0)) {
5129
5130 ALOGV("loadInput() adding input Supported Devices %04x",
5131 profile->mSupportedDevices.types());
5132
5133 mInputProfiles.add(profile);
5134 return NO_ERROR;
5135 } else {
5136 return BAD_VALUE;
5137 }
5138}
5139
5140status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5141{
5142 cnode *node = root->first_child;
5143
5144 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5145
5146 while (node) {
5147 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5148 profile->loadSamplingRates((char *)node->value);
5149 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5150 profile->loadFormats((char *)node->value);
5151 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5152 profile->loadOutChannels((char *)node->value);
5153 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5154 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5155 mDeclaredDevices);
5156 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5157 profile->mFlags = parseFlagNames((char *)node->value);
5158 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5159 profile->loadGains(node);
5160 }
5161 node = node->next;
5162 }
5163 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5164 "loadOutput() invalid supported devices");
5165 ALOGW_IF(profile->mChannelMasks.size() == 0,
5166 "loadOutput() invalid supported channel masks");
5167 ALOGW_IF(profile->mSamplingRates.size() == 0,
5168 "loadOutput() invalid supported sampling rates");
5169 ALOGW_IF(profile->mFormats.size() == 0,
5170 "loadOutput() invalid supported formats");
5171 if (!profile->mSupportedDevices.isEmpty() &&
5172 (profile->mChannelMasks.size() != 0) &&
5173 (profile->mSamplingRates.size() != 0) &&
5174 (profile->mFormats.size() != 0)) {
5175
5176 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5177 profile->mSupportedDevices.types(), profile->mFlags);
5178
5179 mOutputProfiles.add(profile);
5180 return NO_ERROR;
5181 } else {
5182 return BAD_VALUE;
5183 }
5184}
5185
5186status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5187{
5188 cnode *node = root->first_child;
5189
5190 audio_devices_t type = AUDIO_DEVICE_NONE;
5191 while (node) {
5192 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5193 type = parseDeviceNames((char *)node->value);
5194 break;
5195 }
5196 node = node->next;
5197 }
5198 if (type == AUDIO_DEVICE_NONE ||
5199 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5200 ALOGW("loadDevice() bad type %08x", type);
5201 return BAD_VALUE;
5202 }
5203 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5204 deviceDesc->mModule = this;
5205
5206 node = root->first_child;
5207 while (node) {
5208 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5209 deviceDesc->mAddress = String8((char *)node->value);
5210 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5211 if (audio_is_input_device(type)) {
5212 deviceDesc->loadInChannels((char *)node->value);
5213 } else {
5214 deviceDesc->loadOutChannels((char *)node->value);
5215 }
5216 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5217 deviceDesc->loadGains(node);
5218 }
5219 node = node->next;
5220 }
5221
5222 ALOGV("loadDevice() adding device name %s type %08x address %s",
5223 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5224
5225 mDeclaredDevices.add(deviceDesc);
5226
5227 return NO_ERROR;
5228}
5229
Eric Laurente0720872014-03-11 09:30:41 -07005230void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005231{
5232 const size_t SIZE = 256;
5233 char buffer[SIZE];
5234 String8 result;
5235
5236 snprintf(buffer, SIZE, " - name: %s\n", mName);
5237 result.append(buffer);
5238 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5239 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005240 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5241 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005242 write(fd, result.string(), result.size());
5243 if (mOutputProfiles.size()) {
5244 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5245 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005246 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005247 write(fd, buffer, strlen(buffer));
5248 mOutputProfiles[i]->dump(fd);
5249 }
5250 }
5251 if (mInputProfiles.size()) {
5252 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5253 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005254 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005255 write(fd, buffer, strlen(buffer));
5256 mInputProfiles[i]->dump(fd);
5257 }
5258 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005259 if (mDeclaredDevices.size()) {
5260 write(fd, " - devices:\n", strlen(" - devices:\n"));
5261 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5262 mDeclaredDevices[i]->dump(fd, 4, i);
5263 }
5264 }
Eric Laurente552edb2014-03-10 17:42:56 -07005265}
5266
Eric Laurent1c333e22014-05-20 10:48:17 -07005267// --- AudioPort class implementation
5268
Eric Laurenta121f902014-06-03 13:32:54 -07005269
5270AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5271 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005272 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005273{
5274 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5275 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5276}
5277
Eric Laurent1c333e22014-05-20 10:48:17 -07005278void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5279{
5280 port->role = mRole;
5281 port->type = mType;
5282 unsigned int i;
5283 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5284 port->sample_rates[i] = mSamplingRates[i];
5285 }
5286 port->num_sample_rates = i;
5287 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5288 port->channel_masks[i] = mChannelMasks[i];
5289 }
5290 port->num_channel_masks = i;
5291 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5292 port->formats[i] = mFormats[i];
5293 }
5294 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005295
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005296 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005297
5298 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5299 port->gains[i] = mGains[i]->mGain;
5300 }
5301 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005302}
5303
5304
5305void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5306{
5307 char *str = strtok(name, "|");
5308
5309 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5310 // rates should be read from the output stream after it is opened for the first time
5311 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5312 mSamplingRates.add(0);
5313 return;
5314 }
5315
5316 while (str != NULL) {
5317 uint32_t rate = atoi(str);
5318 if (rate != 0) {
5319 ALOGV("loadSamplingRates() adding rate %d", rate);
5320 mSamplingRates.add(rate);
5321 }
5322 str = strtok(NULL, "|");
5323 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005324}
5325
5326void AudioPolicyManager::AudioPort::loadFormats(char *name)
5327{
5328 char *str = strtok(name, "|");
5329
5330 // by convention, "0' in the first entry in mFormats indicates the supported formats
5331 // should be read from the output stream after it is opened for the first time
5332 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5333 mFormats.add(AUDIO_FORMAT_DEFAULT);
5334 return;
5335 }
5336
5337 while (str != NULL) {
5338 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5339 ARRAY_SIZE(sFormatNameToEnumTable),
5340 str);
5341 if (format != AUDIO_FORMAT_DEFAULT) {
5342 mFormats.add(format);
5343 }
5344 str = strtok(NULL, "|");
5345 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005346}
5347
5348void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5349{
5350 const char *str = strtok(name, "|");
5351
5352 ALOGV("loadInChannels() %s", name);
5353
5354 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5355 mChannelMasks.add(0);
5356 return;
5357 }
5358
5359 while (str != NULL) {
5360 audio_channel_mask_t channelMask =
5361 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5362 ARRAY_SIZE(sInChannelsNameToEnumTable),
5363 str);
5364 if (channelMask != 0) {
5365 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5366 mChannelMasks.add(channelMask);
5367 }
5368 str = strtok(NULL, "|");
5369 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005370}
5371
5372void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5373{
5374 const char *str = strtok(name, "|");
5375
5376 ALOGV("loadOutChannels() %s", name);
5377
5378 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5379 // masks should be read from the output stream after it is opened for the first time
5380 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5381 mChannelMasks.add(0);
5382 return;
5383 }
5384
5385 while (str != NULL) {
5386 audio_channel_mask_t channelMask =
5387 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5388 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5389 str);
5390 if (channelMask != 0) {
5391 mChannelMasks.add(channelMask);
5392 }
5393 str = strtok(NULL, "|");
5394 }
5395 return;
5396}
5397
Eric Laurent1afeecb2014-05-14 08:52:28 -07005398audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5399{
5400 const char *str = strtok(name, "|");
5401
5402 ALOGV("loadGainMode() %s", name);
5403 audio_gain_mode_t mode = 0;
5404 while (str != NULL) {
5405 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5406 ARRAY_SIZE(sGainModeNameToEnumTable),
5407 str);
5408 str = strtok(NULL, "|");
5409 }
5410 return mode;
5411}
5412
Eric Laurenta121f902014-06-03 13:32:54 -07005413void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005414{
5415 cnode *node = root->first_child;
5416
Eric Laurenta121f902014-06-03 13:32:54 -07005417 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005418
5419 while (node) {
5420 if (strcmp(node->name, GAIN_MODE) == 0) {
5421 gain->mGain.mode = loadGainMode((char *)node->value);
5422 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005423 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005424 gain->mGain.channel_mask =
5425 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5426 ARRAY_SIZE(sInChannelsNameToEnumTable),
5427 (char *)node->value);
5428 } else {
5429 gain->mGain.channel_mask =
5430 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5431 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5432 (char *)node->value);
5433 }
5434 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5435 gain->mGain.min_value = atoi((char *)node->value);
5436 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5437 gain->mGain.max_value = atoi((char *)node->value);
5438 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5439 gain->mGain.default_value = atoi((char *)node->value);
5440 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5441 gain->mGain.step_value = atoi((char *)node->value);
5442 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5443 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5444 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5445 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5446 }
5447 node = node->next;
5448 }
5449
5450 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5451 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5452
5453 if (gain->mGain.mode == 0) {
5454 return;
5455 }
5456 mGains.add(gain);
5457}
5458
5459void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5460{
5461 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005462 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005463 while (node) {
5464 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005465 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005466 node = node->next;
5467 }
5468}
5469
Glenn Kastencbd48022014-07-24 13:46:44 -07005470status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005471{
5472 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5473 if (mSamplingRates[i] == samplingRate) {
5474 return NO_ERROR;
5475 }
5476 }
5477 return BAD_VALUE;
5478}
5479
Glenn Kastencbd48022014-07-24 13:46:44 -07005480status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5481 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005482{
Glenn Kastencbd48022014-07-24 13:46:44 -07005483 // Search for the closest supported sampling rate that is above (preferred)
5484 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5485 // The sampling rates do not need to be sorted in ascending order.
5486 ssize_t maxBelow = -1;
5487 ssize_t minAbove = -1;
5488 uint32_t candidate;
5489 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5490 candidate = mSamplingRates[i];
5491 if (candidate == samplingRate) {
5492 if (updatedSamplingRate != NULL) {
5493 *updatedSamplingRate = candidate;
5494 }
5495 return NO_ERROR;
5496 }
5497 // candidate < desired
5498 if (candidate < samplingRate) {
5499 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5500 maxBelow = i;
5501 }
5502 // candidate > desired
5503 } else {
5504 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5505 minAbove = i;
5506 }
5507 }
5508 }
5509 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5510 // TODO Move these assumptions out.
5511 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5512 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5513 // due to approximation by an int32_t of the
5514 // phase increments
5515 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5516 if (minAbove >= 0) {
5517 candidate = mSamplingRates[minAbove];
5518 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5519 if (updatedSamplingRate != NULL) {
5520 *updatedSamplingRate = candidate;
5521 }
5522 return NO_ERROR;
5523 }
5524 }
5525 // But if we have to up-sample from a lower sampling rate, that's OK.
5526 if (maxBelow >= 0) {
5527 candidate = mSamplingRates[maxBelow];
5528 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5529 if (updatedSamplingRate != NULL) {
5530 *updatedSamplingRate = candidate;
5531 }
5532 return NO_ERROR;
5533 }
5534 }
5535 // leave updatedSamplingRate unmodified
5536 return BAD_VALUE;
5537}
5538
5539status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5540{
5541 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005542 if (mChannelMasks[i] == channelMask) {
5543 return NO_ERROR;
5544 }
5545 }
5546 return BAD_VALUE;
5547}
5548
Glenn Kastencbd48022014-07-24 13:46:44 -07005549status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5550 const
5551{
5552 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5553 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5554 // FIXME Does not handle multi-channel automatic conversions yet
5555 audio_channel_mask_t supported = mChannelMasks[i];
5556 if (supported == channelMask) {
5557 return NO_ERROR;
5558 }
5559 if (isRecordThread) {
5560 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5561 // FIXME Abstract this out to a table.
5562 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5563 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5564 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5565 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5566 return NO_ERROR;
5567 }
5568 }
5569 }
5570 return BAD_VALUE;
5571}
5572
Eric Laurenta121f902014-06-03 13:32:54 -07005573status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5574{
5575 for (size_t i = 0; i < mFormats.size(); i ++) {
5576 if (mFormats[i] == format) {
5577 return NO_ERROR;
5578 }
5579 }
5580 return BAD_VALUE;
5581}
5582
Eric Laurent1e693b52014-07-09 15:03:28 -07005583
5584uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5585{
5586 // special case for uninitialized dynamic profile
5587 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5588 return 0;
5589 }
5590
5591 uint32_t samplingRate = 0;
5592 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5593
5594 // For mixed output and inputs, use max mixer sampling rates. Do not
5595 // limit sampling rate otherwise
5596 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5597 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5598 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5599 maxRate = UINT_MAX;
5600 }
5601 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5602 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5603 samplingRate = mSamplingRates[i];
5604 }
5605 }
5606 return samplingRate;
5607}
5608
5609audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5610{
5611 // special case for uninitialized dynamic profile
5612 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5613 return AUDIO_CHANNEL_NONE;
5614 }
5615
5616 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5617 uint32_t channelCount = 0;
5618 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5619
5620 // For mixed output and inputs, use max mixer channel count. Do not
5621 // limit channel count otherwise
5622 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5623 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5624 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5625 maxCount = UINT_MAX;
5626 }
5627 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5628 uint32_t cnlCount;
5629 if (mUseInChannelMask) {
5630 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5631 } else {
5632 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5633 }
5634 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5635 channelMask = mChannelMasks[i];
5636 }
5637 }
5638 return channelMask;
5639}
5640
Andy Hung9a605382014-07-28 16:16:31 -07005641/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005642const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5643 AUDIO_FORMAT_DEFAULT,
5644 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005645 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005646 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005647 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005648 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005649};
5650
5651int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5652 audio_format_t format2)
5653{
5654 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5655 // compressed format and better than any PCM format. This is by design of pickFormat()
5656 if (!audio_is_linear_pcm(format1)) {
5657 if (!audio_is_linear_pcm(format2)) {
5658 return 0;
5659 }
5660 return 1;
5661 }
5662 if (!audio_is_linear_pcm(format2)) {
5663 return -1;
5664 }
5665
5666 int index1 = -1, index2 = -1;
5667 for (size_t i = 0;
5668 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5669 i ++) {
5670 if (sPcmFormatCompareTable[i] == format1) {
5671 index1 = i;
5672 }
5673 if (sPcmFormatCompareTable[i] == format2) {
5674 index2 = i;
5675 }
5676 }
5677 // format1 not found => index1 < 0 => format2 > format1
5678 // format2 not found => index2 < 0 => format2 < format1
5679 return index1 - index2;
5680}
5681
5682audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5683{
5684 // special case for uninitialized dynamic profile
5685 if (mFormats.size() == 1 && mFormats[0] == 0) {
5686 return AUDIO_FORMAT_DEFAULT;
5687 }
5688
5689 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005690 audio_format_t bestFormat =
5691 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5692 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005693 // For mixed output and inputs, use best mixer output format. Do not
5694 // limit format otherwise
5695 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5696 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005697 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005698 bestFormat = AUDIO_FORMAT_INVALID;
5699 }
5700
5701 for (size_t i = 0; i < mFormats.size(); i ++) {
5702 if ((compareFormats(mFormats[i], format) > 0) &&
5703 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5704 format = mFormats[i];
5705 }
5706 }
5707 return format;
5708}
5709
Eric Laurenta121f902014-06-03 13:32:54 -07005710status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5711 int index) const
5712{
5713 if (index < 0 || (size_t)index >= mGains.size()) {
5714 return BAD_VALUE;
5715 }
5716 return mGains[index]->checkConfig(gainConfig);
5717}
5718
Eric Laurent1afeecb2014-05-14 08:52:28 -07005719void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5720{
5721 const size_t SIZE = 256;
5722 char buffer[SIZE];
5723 String8 result;
5724
5725 if (mName.size() != 0) {
5726 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5727 result.append(buffer);
5728 }
5729
5730 if (mSamplingRates.size() != 0) {
5731 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5732 result.append(buffer);
5733 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005734 if (i == 0 && mSamplingRates[i] == 0) {
5735 snprintf(buffer, SIZE, "Dynamic");
5736 } else {
5737 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5738 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005739 result.append(buffer);
5740 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5741 }
5742 result.append("\n");
5743 }
5744
5745 if (mChannelMasks.size() != 0) {
5746 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5747 result.append(buffer);
5748 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005749 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5750
5751 if (i == 0 && mChannelMasks[i] == 0) {
5752 snprintf(buffer, SIZE, "Dynamic");
5753 } else {
5754 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5755 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005756 result.append(buffer);
5757 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5758 }
5759 result.append("\n");
5760 }
5761
5762 if (mFormats.size() != 0) {
5763 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5764 result.append(buffer);
5765 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005766 const char *formatStr = enumToString(sFormatNameToEnumTable,
5767 ARRAY_SIZE(sFormatNameToEnumTable),
5768 mFormats[i]);
5769 if (i == 0 && strcmp(formatStr, "") == 0) {
5770 snprintf(buffer, SIZE, "Dynamic");
5771 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005772 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07005773 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005774 result.append(buffer);
5775 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5776 }
5777 result.append("\n");
5778 }
5779 write(fd, result.string(), result.size());
5780 if (mGains.size() != 0) {
5781 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5782 write(fd, buffer, strlen(buffer) + 1);
5783 result.append(buffer);
5784 for (size_t i = 0; i < mGains.size(); i++) {
5785 mGains[i]->dump(fd, spaces + 2, i);
5786 }
5787 }
5788}
5789
5790// --- AudioGain class implementation
5791
Eric Laurenta121f902014-06-03 13:32:54 -07005792AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005793{
Eric Laurenta121f902014-06-03 13:32:54 -07005794 mIndex = index;
5795 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005796 memset(&mGain, 0, sizeof(struct audio_gain));
5797}
5798
Eric Laurenta121f902014-06-03 13:32:54 -07005799void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5800{
5801 config->index = mIndex;
5802 config->mode = mGain.mode;
5803 config->channel_mask = mGain.channel_mask;
5804 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5805 config->values[0] = mGain.default_value;
5806 } else {
5807 uint32_t numValues;
5808 if (mUseInChannelMask) {
5809 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5810 } else {
5811 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5812 }
5813 for (size_t i = 0; i < numValues; i++) {
5814 config->values[i] = mGain.default_value;
5815 }
5816 }
5817 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5818 config->ramp_duration_ms = mGain.min_ramp_ms;
5819 }
5820}
5821
5822status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5823{
5824 if ((config->mode & ~mGain.mode) != 0) {
5825 return BAD_VALUE;
5826 }
5827 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5828 if ((config->values[0] < mGain.min_value) ||
5829 (config->values[0] > mGain.max_value)) {
5830 return BAD_VALUE;
5831 }
5832 } else {
5833 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5834 return BAD_VALUE;
5835 }
5836 uint32_t numValues;
5837 if (mUseInChannelMask) {
5838 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5839 } else {
5840 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5841 }
5842 for (size_t i = 0; i < numValues; i++) {
5843 if ((config->values[i] < mGain.min_value) ||
5844 (config->values[i] > mGain.max_value)) {
5845 return BAD_VALUE;
5846 }
5847 }
5848 }
5849 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5850 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5851 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5852 return BAD_VALUE;
5853 }
5854 }
5855 return NO_ERROR;
5856}
5857
Eric Laurent1afeecb2014-05-14 08:52:28 -07005858void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5859{
5860 const size_t SIZE = 256;
5861 char buffer[SIZE];
5862 String8 result;
5863
5864 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5865 result.append(buffer);
5866 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5867 result.append(buffer);
5868 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5869 result.append(buffer);
5870 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5871 result.append(buffer);
5872 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5873 result.append(buffer);
5874 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5875 result.append(buffer);
5876 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5877 result.append(buffer);
5878 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5879 result.append(buffer);
5880 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5881 result.append(buffer);
5882
5883 write(fd, result.string(), result.size());
5884}
5885
Eric Laurent1f2f2232014-06-02 12:01:23 -07005886// --- AudioPortConfig class implementation
5887
5888AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5889{
5890 mSamplingRate = 0;
5891 mChannelMask = AUDIO_CHANNEL_NONE;
5892 mFormat = AUDIO_FORMAT_INVALID;
5893 mGain.index = -1;
5894}
5895
Eric Laurenta121f902014-06-03 13:32:54 -07005896status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5897 const struct audio_port_config *config,
5898 struct audio_port_config *backupConfig)
5899{
5900 struct audio_port_config localBackupConfig;
5901 status_t status = NO_ERROR;
5902
5903 localBackupConfig.config_mask = config->config_mask;
5904 toAudioPortConfig(&localBackupConfig);
5905
5906 if (mAudioPort == 0) {
5907 status = NO_INIT;
5908 goto exit;
5909 }
5910 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005911 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005912 if (status != NO_ERROR) {
5913 goto exit;
5914 }
5915 mSamplingRate = config->sample_rate;
5916 }
5917 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005918 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005919 if (status != NO_ERROR) {
5920 goto exit;
5921 }
5922 mChannelMask = config->channel_mask;
5923 }
5924 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5925 status = mAudioPort->checkFormat(config->format);
5926 if (status != NO_ERROR) {
5927 goto exit;
5928 }
5929 mFormat = config->format;
5930 }
5931 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5932 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5933 if (status != NO_ERROR) {
5934 goto exit;
5935 }
5936 mGain = config->gain;
5937 }
5938
5939exit:
5940 if (status != NO_ERROR) {
5941 applyAudioPortConfig(&localBackupConfig);
5942 }
5943 if (backupConfig != NULL) {
5944 *backupConfig = localBackupConfig;
5945 }
5946 return status;
5947}
5948
Eric Laurent1f2f2232014-06-02 12:01:23 -07005949void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5950 struct audio_port_config *dstConfig,
5951 const struct audio_port_config *srcConfig) const
5952{
5953 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5954 dstConfig->sample_rate = mSamplingRate;
5955 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5956 dstConfig->sample_rate = srcConfig->sample_rate;
5957 }
5958 } else {
5959 dstConfig->sample_rate = 0;
5960 }
5961 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5962 dstConfig->channel_mask = mChannelMask;
5963 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5964 dstConfig->channel_mask = srcConfig->channel_mask;
5965 }
5966 } else {
5967 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5968 }
5969 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5970 dstConfig->format = mFormat;
5971 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5972 dstConfig->format = srcConfig->format;
5973 }
5974 } else {
5975 dstConfig->format = AUDIO_FORMAT_INVALID;
5976 }
5977 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5978 dstConfig->gain = mGain;
5979 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5980 dstConfig->gain = srcConfig->gain;
5981 }
5982 } else {
5983 dstConfig->gain.index = -1;
5984 }
5985 if (dstConfig->gain.index != -1) {
5986 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5987 } else {
5988 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5989 }
5990}
5991
Eric Laurent1c333e22014-05-20 10:48:17 -07005992// --- IOProfile class implementation
5993
Eric Laurent1afeecb2014-05-14 08:52:28 -07005994AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005995 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07005996 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07005997{
5998}
5999
Eric Laurente0720872014-03-11 09:30:41 -07006000AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006001{
6002}
6003
6004// checks if the IO profile is compatible with specified parameters.
6005// Sampling rate, format and channel mask must be specified in order to
6006// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006007bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006008 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006009 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006010 audio_format_t format,
6011 audio_channel_mask_t channelMask,
6012 audio_output_flags_t flags) const
6013{
Glenn Kastencbd48022014-07-24 13:46:44 -07006014 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6015 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6016 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006017
Glenn Kastencbd48022014-07-24 13:46:44 -07006018 if ((mSupportedDevices.types() & device) != device) {
6019 return false;
6020 }
6021
6022 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006023 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006024 }
6025 uint32_t myUpdatedSamplingRate = samplingRate;
6026 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006027 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006028 }
6029 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6030 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006031 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006032 }
6033
6034 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6035 return false;
6036 }
6037
6038 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6039 checkExactChannelMask(channelMask) != NO_ERROR)) {
6040 return false;
6041 }
6042 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6043 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6044 return false;
6045 }
6046
6047 if (isPlaybackThread && (mFlags & flags) != flags) {
6048 return false;
6049 }
6050 // The only input flag that is allowed to be different is the fast flag.
6051 // An existing fast stream is compatible with a normal track request.
6052 // An existing normal stream is compatible with a fast track request,
6053 // but the fast request will be denied by AudioFlinger and converted to normal track.
6054 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6055 ~AUDIO_INPUT_FLAG_FAST)) {
6056 return false;
6057 }
6058
6059 if (updatedSamplingRate != NULL) {
6060 *updatedSamplingRate = myUpdatedSamplingRate;
6061 }
6062 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006063}
6064
Eric Laurente0720872014-03-11 09:30:41 -07006065void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006066{
6067 const size_t SIZE = 256;
6068 char buffer[SIZE];
6069 String8 result;
6070
Eric Laurent1afeecb2014-05-14 08:52:28 -07006071 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006072
Eric Laurente552edb2014-03-10 17:42:56 -07006073 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6074 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006075 snprintf(buffer, SIZE, " - devices:\n");
6076 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006077 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006078 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6079 mSupportedDevices[i]->dump(fd, 6, i);
6080 }
Eric Laurente552edb2014-03-10 17:42:56 -07006081}
6082
Eric Laurentd4692962014-05-05 18:13:44 -07006083void AudioPolicyManager::IOProfile::log()
6084{
6085 const size_t SIZE = 256;
6086 char buffer[SIZE];
6087 String8 result;
6088
6089 ALOGV(" - sampling rates: ");
6090 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6091 ALOGV(" %d", mSamplingRates[i]);
6092 }
6093
6094 ALOGV(" - channel masks: ");
6095 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6096 ALOGV(" 0x%04x", mChannelMasks[i]);
6097 }
6098
6099 ALOGV(" - formats: ");
6100 for (size_t i = 0; i < mFormats.size(); i++) {
6101 ALOGV(" 0x%08x", mFormats[i]);
6102 }
6103
6104 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6105 ALOGV(" - flags: 0x%04x\n", mFlags);
6106}
6107
6108
Eric Laurent3a4311c2014-03-17 12:00:47 -07006109// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006110
Eric Laurent1f2f2232014-06-02 12:01:23 -07006111
6112AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6113 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6114 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6115 AUDIO_PORT_ROLE_SOURCE,
6116 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006117 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006118{
6119 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006120 if (mGains.size() > 0) {
6121 mGains[0]->getDefaultConfig(&mGain);
6122 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006123}
6124
Eric Laurent3a4311c2014-03-17 12:00:47 -07006125bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006126{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006127 // Devices are considered equal if they:
6128 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6129 // - have the same address or one device does not specify the address
6130 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006131 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006132 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006133 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006134 mChannelMask == other->mChannelMask);
6135}
6136
6137void AudioPolicyManager::DeviceVector::refreshTypes()
6138{
Eric Laurent1c333e22014-05-20 10:48:17 -07006139 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006140 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006141 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006142 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006143 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006144}
6145
6146ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6147{
6148 for(size_t i = 0; i < size(); i++) {
6149 if (item->equals(itemAt(i))) {
6150 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006151 }
6152 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006153 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006154}
6155
Eric Laurent3a4311c2014-03-17 12:00:47 -07006156ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006157{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006158 ssize_t ret = indexOf(item);
6159
6160 if (ret < 0) {
6161 ret = SortedVector::add(item);
6162 if (ret >= 0) {
6163 refreshTypes();
6164 }
6165 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006166 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006167 ret = -1;
6168 }
6169 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006170}
6171
Eric Laurent3a4311c2014-03-17 12:00:47 -07006172ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6173{
6174 size_t i;
6175 ssize_t ret = indexOf(item);
6176
6177 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006178 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006179 } else {
6180 ret = SortedVector::removeAt(ret);
6181 if (ret >= 0) {
6182 refreshTypes();
6183 }
6184 }
6185 return ret;
6186}
6187
6188void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6189{
6190 DeviceVector deviceList;
6191
6192 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6193 types &= ~role_bit;
6194
6195 while (types) {
6196 uint32_t i = 31 - __builtin_clz(types);
6197 uint32_t type = 1 << i;
6198 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006199 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006200 }
6201}
6202
Eric Laurent1afeecb2014-05-14 08:52:28 -07006203void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6204 const DeviceVector& declaredDevices)
6205{
6206 char *devName = strtok(name, "|");
6207 while (devName != NULL) {
6208 if (strlen(devName) != 0) {
6209 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6210 ARRAY_SIZE(sDeviceNameToEnumTable),
6211 devName);
6212 if (type != AUDIO_DEVICE_NONE) {
6213 add(new DeviceDescriptor(String8(""), type));
6214 } else {
6215 sp<DeviceDescriptor> deviceDesc =
6216 declaredDevices.getDeviceFromName(String8(devName));
6217 if (deviceDesc != 0) {
6218 add(deviceDesc);
6219 }
6220 }
6221 }
6222 devName = strtok(NULL, "|");
6223 }
6224}
6225
Eric Laurent1c333e22014-05-20 10:48:17 -07006226sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6227 audio_devices_t type, String8 address) const
6228{
6229 sp<DeviceDescriptor> device;
6230 for (size_t i = 0; i < size(); i++) {
6231 if (itemAt(i)->mDeviceType == type) {
6232 device = itemAt(i);
6233 if (itemAt(i)->mAddress = address) {
6234 break;
6235 }
6236 }
6237 }
6238 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6239 type, address.string(), device.get());
6240 return device;
6241}
6242
Eric Laurent6a94d692014-05-20 11:18:06 -07006243sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6244 audio_port_handle_t id) const
6245{
6246 sp<DeviceDescriptor> device;
6247 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006248 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006249 if (itemAt(i)->mId == id) {
6250 device = itemAt(i);
6251 break;
6252 }
6253 }
6254 return device;
6255}
6256
Eric Laurent1c333e22014-05-20 10:48:17 -07006257AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6258 audio_devices_t type) const
6259{
6260 DeviceVector devices;
6261 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6262 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6263 devices.add(itemAt(i));
6264 type &= ~itemAt(i)->mDeviceType;
6265 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6266 itemAt(i)->mDeviceType, itemAt(i).get());
6267 }
6268 }
6269 return devices;
6270}
6271
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006272AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6273 audio_devices_t type, String8 address) const
6274{
6275 DeviceVector devices;
6276 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6277 for (size_t i = 0; i < size(); i++) {
6278 //ALOGV(" at i=%d: device=%x, addr=%s",
6279 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6280 if (itemAt(i)->mDeviceType == type) {
6281 if (itemAt(i)->mAddress == address) {
6282 //ALOGV(" found matching address %s", address.string());
6283 devices.add(itemAt(i));
6284 }
6285 }
6286 }
6287 return devices;
6288}
6289
Eric Laurent1afeecb2014-05-14 08:52:28 -07006290sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6291 const String8& name) const
6292{
6293 sp<DeviceDescriptor> device;
6294 for (size_t i = 0; i < size(); i++) {
6295 if (itemAt(i)->mName == name) {
6296 device = itemAt(i);
6297 break;
6298 }
6299 }
6300 return device;
6301}
6302
Eric Laurent6a94d692014-05-20 11:18:06 -07006303void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6304 struct audio_port_config *dstConfig,
6305 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006306{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006307 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6308 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006309 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006310 }
6311
6312 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6313
Eric Laurent6a94d692014-05-20 11:18:06 -07006314 dstConfig->id = mId;
6315 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006316 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006317 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006318 dstConfig->ext.device.type = mDeviceType;
6319 dstConfig->ext.device.hw_module = mModule->mHandle;
6320 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006321}
6322
6323void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6324{
Eric Laurent83b88082014-06-20 18:31:16 -07006325 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006326 AudioPort::toAudioPort(port);
6327 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006328 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006329 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006330 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006331 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6332}
6333
Eric Laurent1afeecb2014-05-14 08:52:28 -07006334status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006335{
6336 const size_t SIZE = 256;
6337 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006338 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006339
Eric Laurent1afeecb2014-05-14 08:52:28 -07006340 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6341 result.append(buffer);
6342 if (mId != 0) {
6343 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6344 result.append(buffer);
6345 }
6346 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6347 enumToString(sDeviceNameToEnumTable,
6348 ARRAY_SIZE(sDeviceNameToEnumTable),
6349 mDeviceType));
6350 result.append(buffer);
6351 if (mAddress.size() != 0) {
6352 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6353 result.append(buffer);
6354 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006355 write(fd, result.string(), result.size());
6356 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006357
6358 return NO_ERROR;
6359}
6360
6361
6362// --- audio_policy.conf file parsing
6363
Eric Laurente0720872014-03-11 09:30:41 -07006364audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006365{
6366 uint32_t flag = 0;
6367
6368 // it is OK to cast name to non const here as we are not going to use it after
6369 // strtok() modifies it
6370 char *flagName = strtok(name, "|");
6371 while (flagName != NULL) {
6372 if (strlen(flagName) != 0) {
6373 flag |= stringToEnum(sFlagNameToEnumTable,
6374 ARRAY_SIZE(sFlagNameToEnumTable),
6375 flagName);
6376 }
6377 flagName = strtok(NULL, "|");
6378 }
6379 //force direct flag if offload flag is set: offloading implies a direct output stream
6380 // and all common behaviors are driven by checking only the direct flag
6381 // this should normally be set appropriately in the policy configuration file
6382 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6383 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6384 }
6385
6386 return (audio_output_flags_t)flag;
6387}
6388
Eric Laurente0720872014-03-11 09:30:41 -07006389audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006390{
6391 uint32_t device = 0;
6392
6393 char *devName = strtok(name, "|");
6394 while (devName != NULL) {
6395 if (strlen(devName) != 0) {
6396 device |= stringToEnum(sDeviceNameToEnumTable,
6397 ARRAY_SIZE(sDeviceNameToEnumTable),
6398 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006399 }
Eric Laurente552edb2014-03-10 17:42:56 -07006400 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006401 }
Eric Laurente552edb2014-03-10 17:42:56 -07006402 return device;
6403}
6404
Eric Laurente0720872014-03-11 09:30:41 -07006405void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006406{
Eric Laurente552edb2014-03-10 17:42:56 -07006407 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006408 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006409 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006410
Eric Laurent1afeecb2014-05-14 08:52:28 -07006411 node = config_find(root, DEVICES_TAG);
6412 if (node != NULL) {
6413 node = node->first_child;
6414 while (node) {
6415 ALOGV("loadHwModule() loading device %s", node->name);
6416 status_t tmpStatus = module->loadDevice(node);
6417 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6418 status = tmpStatus;
6419 }
6420 node = node->next;
6421 }
6422 }
6423 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006424 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006425 node = node->first_child;
6426 while (node) {
6427 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006428 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006429 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6430 status = tmpStatus;
6431 }
6432 node = node->next;
6433 }
6434 }
6435 node = config_find(root, INPUTS_TAG);
6436 if (node != NULL) {
6437 node = node->first_child;
6438 while (node) {
6439 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006440 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006441 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6442 status = tmpStatus;
6443 }
6444 node = node->next;
6445 }
6446 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006447 loadGlobalConfig(root, module);
6448
Eric Laurente552edb2014-03-10 17:42:56 -07006449 if (status == NO_ERROR) {
6450 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006451 }
6452}
6453
Eric Laurente0720872014-03-11 09:30:41 -07006454void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006455{
6456 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6457 if (node == NULL) {
6458 return;
6459 }
6460
6461 node = node->first_child;
6462 while (node) {
6463 ALOGV("loadHwModules() loading module %s", node->name);
6464 loadHwModule(node);
6465 node = node->next;
6466 }
6467}
6468
Eric Laurent1f2f2232014-06-02 12:01:23 -07006469void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006470{
6471 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006472
Eric Laurente552edb2014-03-10 17:42:56 -07006473 if (node == NULL) {
6474 return;
6475 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006476 DeviceVector declaredDevices;
6477 if (module != NULL) {
6478 declaredDevices = module->mDeclaredDevices;
6479 }
6480
Eric Laurente552edb2014-03-10 17:42:56 -07006481 node = node->first_child;
6482 while (node) {
6483 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006484 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6485 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006486 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6487 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006488 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006489 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006490 ARRAY_SIZE(sDeviceNameToEnumTable),
6491 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006492 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006493 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006494 } else {
6495 ALOGW("loadGlobalConfig() default device not specified");
6496 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006497 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006498 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006499 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6500 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006501 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006502 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6503 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6504 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006505 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6506 uint32_t major, minor;
6507 sscanf((char *)node->value, "%u.%u", &major, &minor);
6508 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6509 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6510 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006511 }
6512 node = node->next;
6513 }
6514}
6515
Eric Laurente0720872014-03-11 09:30:41 -07006516status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006517{
6518 cnode *root;
6519 char *data;
6520
6521 data = (char *)load_file(path, NULL);
6522 if (data == NULL) {
6523 return -ENODEV;
6524 }
6525 root = config_node("", "");
6526 config_load(root, data);
6527
Eric Laurente552edb2014-03-10 17:42:56 -07006528 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006529 // legacy audio_policy.conf files have one global_configuration section
6530 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006531 config_free(root);
6532 free(root);
6533 free(data);
6534
6535 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6536
6537 return NO_ERROR;
6538}
6539
Eric Laurente0720872014-03-11 09:30:41 -07006540void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006541{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006542 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006543 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006544 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6545 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006546 mAvailableOutputDevices.add(mDefaultOutputDevice);
6547 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006548
6549 module = new HwModule("primary");
6550
Eric Laurent1afeecb2014-05-14 08:52:28 -07006551 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006552 profile->mSamplingRates.add(44100);
6553 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6554 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006555 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006556 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6557 module->mOutputProfiles.add(profile);
6558
Eric Laurent1afeecb2014-05-14 08:52:28 -07006559 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006560 profile->mSamplingRates.add(8000);
6561 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6562 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006563 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006564 module->mInputProfiles.add(profile);
6565
6566 mHwModules.add(module);
6567}
6568
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006569audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6570{
6571 // flags to stream type mapping
6572 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6573 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6574 }
6575 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6576 return AUDIO_STREAM_BLUETOOTH_SCO;
6577 }
6578
6579 // usage to stream type mapping
6580 switch (attr->usage) {
6581 case AUDIO_USAGE_MEDIA:
6582 case AUDIO_USAGE_GAME:
6583 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6584 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6585 return AUDIO_STREAM_MUSIC;
6586 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6587 return AUDIO_STREAM_SYSTEM;
6588 case AUDIO_USAGE_VOICE_COMMUNICATION:
6589 return AUDIO_STREAM_VOICE_CALL;
6590
6591 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6592 return AUDIO_STREAM_DTMF;
6593
6594 case AUDIO_USAGE_ALARM:
6595 return AUDIO_STREAM_ALARM;
6596 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6597 return AUDIO_STREAM_RING;
6598
6599 case AUDIO_USAGE_NOTIFICATION:
6600 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6601 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6602 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6603 case AUDIO_USAGE_NOTIFICATION_EVENT:
6604 return AUDIO_STREAM_NOTIFICATION;
6605
6606 case AUDIO_USAGE_UNKNOWN:
6607 default:
6608 return AUDIO_STREAM_MUSIC;
6609 }
6610}
Eric Laurente552edb2014-03-10 17:42:56 -07006611}; // namespace android